Remove some unnecessary includes of PseudoSourceValue.h.
[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::UNPCKHPS:
2855   case X86ISD::UNPCKHPD:
2856   case X86ISD::VUNPCKHPSY:
2857   case X86ISD::VUNPCKHPDY:
2858   case X86ISD::PUNPCKHWD:
2859   case X86ISD::PUNPCKHBW:
2860   case X86ISD::PUNPCKHDQ:
2861   case X86ISD::PUNPCKHQDQ:
2862   case X86ISD::VPERMILPS:
2863   case X86ISD::VPERMILPSY:
2864   case X86ISD::VPERMILPD:
2865   case X86ISD::VPERMILPDY:
2866   case X86ISD::VPERM2F128:
2867     return true;
2868   }
2869   return false;
2870 }
2871
2872 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2873                                                SDValue V1, SelectionDAG &DAG) {
2874   switch(Opc) {
2875   default: llvm_unreachable("Unknown x86 shuffle node");
2876   case X86ISD::MOVSHDUP:
2877   case X86ISD::MOVSLDUP:
2878   case X86ISD::MOVDDUP:
2879     return DAG.getNode(Opc, dl, VT, V1);
2880   }
2881
2882   return SDValue();
2883 }
2884
2885 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2886                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2887   switch(Opc) {
2888   default: llvm_unreachable("Unknown x86 shuffle node");
2889   case X86ISD::PSHUFD:
2890   case X86ISD::PSHUFHW:
2891   case X86ISD::PSHUFLW:
2892   case X86ISD::VPERMILPS:
2893   case X86ISD::VPERMILPSY:
2894   case X86ISD::VPERMILPD:
2895   case X86ISD::VPERMILPDY:
2896     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2897   }
2898
2899   return SDValue();
2900 }
2901
2902 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2903                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2904   switch(Opc) {
2905   default: llvm_unreachable("Unknown x86 shuffle node");
2906   case X86ISD::PALIGN:
2907   case X86ISD::SHUFPD:
2908   case X86ISD::SHUFPS:
2909   case X86ISD::VPERM2F128:
2910     return DAG.getNode(Opc, dl, VT, V1, V2,
2911                        DAG.getConstant(TargetMask, MVT::i8));
2912   }
2913   return SDValue();
2914 }
2915
2916 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2917                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2918   switch(Opc) {
2919   default: llvm_unreachable("Unknown x86 shuffle node");
2920   case X86ISD::MOVLHPS:
2921   case X86ISD::MOVLHPD:
2922   case X86ISD::MOVHLPS:
2923   case X86ISD::MOVLPS:
2924   case X86ISD::MOVLPD:
2925   case X86ISD::MOVSS:
2926   case X86ISD::MOVSD:
2927   case X86ISD::UNPCKLPS:
2928   case X86ISD::UNPCKLPD:
2929   case X86ISD::VUNPCKLPSY:
2930   case X86ISD::VUNPCKLPDY:
2931   case X86ISD::PUNPCKLWD:
2932   case X86ISD::PUNPCKLBW:
2933   case X86ISD::PUNPCKLDQ:
2934   case X86ISD::PUNPCKLQDQ:
2935   case X86ISD::UNPCKHPS:
2936   case X86ISD::UNPCKHPD:
2937   case X86ISD::VUNPCKHPSY:
2938   case X86ISD::VUNPCKHPDY:
2939   case X86ISD::PUNPCKHWD:
2940   case X86ISD::PUNPCKHBW:
2941   case X86ISD::PUNPCKHDQ:
2942   case X86ISD::PUNPCKHQDQ:
2943     return DAG.getNode(Opc, dl, VT, V1, V2);
2944   }
2945   return SDValue();
2946 }
2947
2948 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2949   MachineFunction &MF = DAG.getMachineFunction();
2950   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2951   int ReturnAddrIndex = FuncInfo->getRAIndex();
2952
2953   if (ReturnAddrIndex == 0) {
2954     // Set up a frame object for the return address.
2955     uint64_t SlotSize = TD->getPointerSize();
2956     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2957                                                            false);
2958     FuncInfo->setRAIndex(ReturnAddrIndex);
2959   }
2960
2961   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2962 }
2963
2964
2965 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2966                                        bool hasSymbolicDisplacement) {
2967   // Offset should fit into 32 bit immediate field.
2968   if (!isInt<32>(Offset))
2969     return false;
2970
2971   // If we don't have a symbolic displacement - we don't have any extra
2972   // restrictions.
2973   if (!hasSymbolicDisplacement)
2974     return true;
2975
2976   // FIXME: Some tweaks might be needed for medium code model.
2977   if (M != CodeModel::Small && M != CodeModel::Kernel)
2978     return false;
2979
2980   // For small code model we assume that latest object is 16MB before end of 31
2981   // bits boundary. We may also accept pretty large negative constants knowing
2982   // that all objects are in the positive half of address space.
2983   if (M == CodeModel::Small && Offset < 16*1024*1024)
2984     return true;
2985
2986   // For kernel code model we know that all object resist in the negative half
2987   // of 32bits address space. We may not accept negative offsets, since they may
2988   // be just off and we may accept pretty large positive ones.
2989   if (M == CodeModel::Kernel && Offset > 0)
2990     return true;
2991
2992   return false;
2993 }
2994
2995 /// isCalleePop - Determines whether the callee is required to pop its
2996 /// own arguments. Callee pop is necessary to support tail calls.
2997 bool X86::isCalleePop(CallingConv::ID CallingConv,
2998                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2999   if (IsVarArg)
3000     return false;
3001
3002   switch (CallingConv) {
3003   default:
3004     return false;
3005   case CallingConv::X86_StdCall:
3006     return !is64Bit;
3007   case CallingConv::X86_FastCall:
3008     return !is64Bit;
3009   case CallingConv::X86_ThisCall:
3010     return !is64Bit;
3011   case CallingConv::Fast:
3012     return TailCallOpt;
3013   case CallingConv::GHC:
3014     return TailCallOpt;
3015   }
3016 }
3017
3018 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3019 /// specific condition code, returning the condition code and the LHS/RHS of the
3020 /// comparison to make.
3021 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3022                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3023   if (!isFP) {
3024     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3025       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3026         // X > -1   -> X == 0, jump !sign.
3027         RHS = DAG.getConstant(0, RHS.getValueType());
3028         return X86::COND_NS;
3029       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3030         // X < 0   -> X == 0, jump on sign.
3031         return X86::COND_S;
3032       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3033         // X < 1   -> X <= 0
3034         RHS = DAG.getConstant(0, RHS.getValueType());
3035         return X86::COND_LE;
3036       }
3037     }
3038
3039     switch (SetCCOpcode) {
3040     default: llvm_unreachable("Invalid integer condition!");
3041     case ISD::SETEQ:  return X86::COND_E;
3042     case ISD::SETGT:  return X86::COND_G;
3043     case ISD::SETGE:  return X86::COND_GE;
3044     case ISD::SETLT:  return X86::COND_L;
3045     case ISD::SETLE:  return X86::COND_LE;
3046     case ISD::SETNE:  return X86::COND_NE;
3047     case ISD::SETULT: return X86::COND_B;
3048     case ISD::SETUGT: return X86::COND_A;
3049     case ISD::SETULE: return X86::COND_BE;
3050     case ISD::SETUGE: return X86::COND_AE;
3051     }
3052   }
3053
3054   // First determine if it is required or is profitable to flip the operands.
3055
3056   // If LHS is a foldable load, but RHS is not, flip the condition.
3057   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3058       !ISD::isNON_EXTLoad(RHS.getNode())) {
3059     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3060     std::swap(LHS, RHS);
3061   }
3062
3063   switch (SetCCOpcode) {
3064   default: break;
3065   case ISD::SETOLT:
3066   case ISD::SETOLE:
3067   case ISD::SETUGT:
3068   case ISD::SETUGE:
3069     std::swap(LHS, RHS);
3070     break;
3071   }
3072
3073   // On a floating point condition, the flags are set as follows:
3074   // ZF  PF  CF   op
3075   //  0 | 0 | 0 | X > Y
3076   //  0 | 0 | 1 | X < Y
3077   //  1 | 0 | 0 | X == Y
3078   //  1 | 1 | 1 | unordered
3079   switch (SetCCOpcode) {
3080   default: llvm_unreachable("Condcode should be pre-legalized away");
3081   case ISD::SETUEQ:
3082   case ISD::SETEQ:   return X86::COND_E;
3083   case ISD::SETOLT:              // flipped
3084   case ISD::SETOGT:
3085   case ISD::SETGT:   return X86::COND_A;
3086   case ISD::SETOLE:              // flipped
3087   case ISD::SETOGE:
3088   case ISD::SETGE:   return X86::COND_AE;
3089   case ISD::SETUGT:              // flipped
3090   case ISD::SETULT:
3091   case ISD::SETLT:   return X86::COND_B;
3092   case ISD::SETUGE:              // flipped
3093   case ISD::SETULE:
3094   case ISD::SETLE:   return X86::COND_BE;
3095   case ISD::SETONE:
3096   case ISD::SETNE:   return X86::COND_NE;
3097   case ISD::SETUO:   return X86::COND_P;
3098   case ISD::SETO:    return X86::COND_NP;
3099   case ISD::SETOEQ:
3100   case ISD::SETUNE:  return X86::COND_INVALID;
3101   }
3102 }
3103
3104 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3105 /// code. Current x86 isa includes the following FP cmov instructions:
3106 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3107 static bool hasFPCMov(unsigned X86CC) {
3108   switch (X86CC) {
3109   default:
3110     return false;
3111   case X86::COND_B:
3112   case X86::COND_BE:
3113   case X86::COND_E:
3114   case X86::COND_P:
3115   case X86::COND_A:
3116   case X86::COND_AE:
3117   case X86::COND_NE:
3118   case X86::COND_NP:
3119     return true;
3120   }
3121 }
3122
3123 /// isFPImmLegal - Returns true if the target can instruction select the
3124 /// specified FP immediate natively. If false, the legalizer will
3125 /// materialize the FP immediate as a load from a constant pool.
3126 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3127   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3128     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3129       return true;
3130   }
3131   return false;
3132 }
3133
3134 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3135 /// the specified range (L, H].
3136 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3137   return (Val < 0) || (Val >= Low && Val < Hi);
3138 }
3139
3140 /// isUndefOrInRange - Return true if every element in Mask, begining
3141 /// from position Pos and ending in Pos+Size, falls within the specified
3142 /// range (L, L+Pos]. or is undef.
3143 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3144                              int Pos, int Size, int Low, int Hi) {
3145   for (int i = Pos, e = Pos+Size; i != e; ++i)
3146     if (!isUndefOrInRange(Mask[i], Low, Hi))
3147       return false;
3148   return true;
3149 }
3150
3151 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3152 /// specified value.
3153 static bool isUndefOrEqual(int Val, int CmpVal) {
3154   if (Val < 0 || Val == CmpVal)
3155     return true;
3156   return false;
3157 }
3158
3159 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3160 /// from position Pos and ending in Pos+Size, falls within the specified
3161 /// sequential range (L, L+Pos]. or is undef.
3162 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3163                                        int Pos, int Size, int Low) {
3164   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3165     if (!isUndefOrEqual(Mask[i], Low))
3166       return false;
3167   return true;
3168 }
3169
3170 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3171 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3172 /// the second operand.
3173 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3174   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3175     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3176   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3177     return (Mask[0] < 2 && Mask[1] < 2);
3178   return false;
3179 }
3180
3181 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3182   SmallVector<int, 8> M;
3183   N->getMask(M);
3184   return ::isPSHUFDMask(M, N->getValueType(0));
3185 }
3186
3187 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3188 /// is suitable for input to PSHUFHW.
3189 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3190   if (VT != MVT::v8i16)
3191     return false;
3192
3193   // Lower quadword copied in order or undef.
3194   for (int i = 0; i != 4; ++i)
3195     if (Mask[i] >= 0 && Mask[i] != i)
3196       return false;
3197
3198   // Upper quadword shuffled.
3199   for (int i = 4; i != 8; ++i)
3200     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3201       return false;
3202
3203   return true;
3204 }
3205
3206 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3207   SmallVector<int, 8> M;
3208   N->getMask(M);
3209   return ::isPSHUFHWMask(M, N->getValueType(0));
3210 }
3211
3212 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3213 /// is suitable for input to PSHUFLW.
3214 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3215   if (VT != MVT::v8i16)
3216     return false;
3217
3218   // Upper quadword copied in order.
3219   for (int i = 4; i != 8; ++i)
3220     if (Mask[i] >= 0 && Mask[i] != i)
3221       return false;
3222
3223   // Lower quadword shuffled.
3224   for (int i = 0; i != 4; ++i)
3225     if (Mask[i] >= 4)
3226       return false;
3227
3228   return true;
3229 }
3230
3231 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3232   SmallVector<int, 8> M;
3233   N->getMask(M);
3234   return ::isPSHUFLWMask(M, N->getValueType(0));
3235 }
3236
3237 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3238 /// is suitable for input to PALIGNR.
3239 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3240                           bool hasSSSE3OrAVX) {
3241   int i, e = VT.getVectorNumElements();
3242   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3243     return false;
3244
3245   // Do not handle v2i64 / v2f64 shuffles with palignr.
3246   if (e < 4 || !hasSSSE3OrAVX)
3247     return false;
3248
3249   for (i = 0; i != e; ++i)
3250     if (Mask[i] >= 0)
3251       break;
3252
3253   // All undef, not a palignr.
3254   if (i == e)
3255     return false;
3256
3257   // Make sure we're shifting in the right direction.
3258   if (Mask[i] <= i)
3259     return false;
3260
3261   int s = Mask[i] - i;
3262
3263   // Check the rest of the elements to see if they are consecutive.
3264   for (++i; i != e; ++i) {
3265     int m = Mask[i];
3266     if (m >= 0 && m != s+i)
3267       return false;
3268   }
3269   return true;
3270 }
3271
3272 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3273 /// specifies a shuffle of elements that is suitable for input to 256-bit
3274 /// VSHUFPSY.
3275 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3276                           const X86Subtarget *Subtarget) {
3277   int NumElems = VT.getVectorNumElements();
3278
3279   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3280     return false;
3281
3282   if (NumElems != 8)
3283     return false;
3284
3285   // VSHUFPSY divides the resulting vector into 4 chunks.
3286   // The sources are also splitted into 4 chunks, and each destination
3287   // chunk must come from a different source chunk.
3288   //
3289   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3290   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3291   //
3292   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3293   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3294   //
3295   int QuarterSize = NumElems/4;
3296   int HalfSize = QuarterSize*2;
3297   for (int i = 0; i < QuarterSize; ++i)
3298     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3299       return false;
3300   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3301     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3302       return false;
3303
3304   // The mask of the second half must be the same as the first but with
3305   // the appropriate offsets. This works in the same way as VPERMILPS
3306   // works with masks.
3307   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3308     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3309       return false;
3310     int FstHalfIdx = i-HalfSize;
3311     if (Mask[FstHalfIdx] < 0)
3312       continue;
3313     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3314       return false;
3315   }
3316   for (int i = QuarterSize*3; i < NumElems; ++i) {
3317     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3318       return false;
3319     int FstHalfIdx = i-HalfSize;
3320     if (Mask[FstHalfIdx] < 0)
3321       continue;
3322     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3323       return false;
3324
3325   }
3326
3327   return true;
3328 }
3329
3330 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3331 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3332 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3333   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3334   EVT VT = SVOp->getValueType(0);
3335   int NumElems = VT.getVectorNumElements();
3336
3337   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3338          "Only supports v8i32 and v8f32 types");
3339
3340   int HalfSize = NumElems/2;
3341   unsigned Mask = 0;
3342   for (int i = 0; i != NumElems ; ++i) {
3343     if (SVOp->getMaskElt(i) < 0)
3344       continue;
3345     // The mask of the first half must be equal to the second one.
3346     unsigned Shamt = (i%HalfSize)*2;
3347     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3348     Mask |= Elt << Shamt;
3349   }
3350
3351   return Mask;
3352 }
3353
3354 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3355 /// specifies a shuffle of elements that is suitable for input to 256-bit
3356 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3357 /// version and the mask of the second half isn't binded with the first
3358 /// one.
3359 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3360                            const X86Subtarget *Subtarget) {
3361   int NumElems = VT.getVectorNumElements();
3362
3363   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3364     return false;
3365
3366   if (NumElems != 4)
3367     return false;
3368
3369   // VSHUFPSY divides the resulting vector into 4 chunks.
3370   // The sources are also splitted into 4 chunks, and each destination
3371   // chunk must come from a different source chunk.
3372   //
3373   //  SRC1 =>      X3       X2       X1       X0
3374   //  SRC2 =>      Y3       Y2       Y1       Y0
3375   //
3376   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3377   //
3378   int QuarterSize = NumElems/4;
3379   int HalfSize = QuarterSize*2;
3380   for (int i = 0; i < QuarterSize; ++i)
3381     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3382       return false;
3383   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3384     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3385       return false;
3386   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3387     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3388       return false;
3389   for (int i = QuarterSize*3; i < NumElems; ++i)
3390     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3391       return false;
3392
3393   return true;
3394 }
3395
3396 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3397 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3398 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3399   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3400   EVT VT = SVOp->getValueType(0);
3401   int NumElems = VT.getVectorNumElements();
3402
3403   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3404          "Only supports v4i64 and v4f64 types");
3405
3406   int HalfSize = NumElems/2;
3407   unsigned Mask = 0;
3408   for (int i = 0; i != NumElems ; ++i) {
3409     if (SVOp->getMaskElt(i) < 0)
3410       continue;
3411     int Elt = SVOp->getMaskElt(i) % HalfSize;
3412     Mask |= Elt << i;
3413   }
3414
3415   return Mask;
3416 }
3417
3418 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3419 /// specifies a shuffle of elements that is suitable for input to 128-bit
3420 /// SHUFPS and SHUFPD.
3421 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3422   int NumElems = VT.getVectorNumElements();
3423
3424   if (VT.getSizeInBits() != 128)
3425     return false;
3426
3427   if (NumElems != 2 && NumElems != 4)
3428     return false;
3429
3430   int Half = NumElems / 2;
3431   for (int i = 0; i < Half; ++i)
3432     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3433       return false;
3434   for (int i = Half; i < NumElems; ++i)
3435     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3436       return false;
3437
3438   return true;
3439 }
3440
3441 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3442   SmallVector<int, 8> M;
3443   N->getMask(M);
3444   return ::isSHUFPMask(M, N->getValueType(0));
3445 }
3446
3447 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3448 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3449 /// half elements to come from vector 1 (which would equal the dest.) and
3450 /// the upper half to come from vector 2.
3451 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3452   int NumElems = VT.getVectorNumElements();
3453
3454   if (NumElems != 2 && NumElems != 4)
3455     return false;
3456
3457   int Half = NumElems / 2;
3458   for (int i = 0; i < Half; ++i)
3459     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3460       return false;
3461   for (int i = Half; i < NumElems; ++i)
3462     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3463       return false;
3464   return true;
3465 }
3466
3467 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3468   SmallVector<int, 8> M;
3469   N->getMask(M);
3470   return isCommutedSHUFPMask(M, N->getValueType(0));
3471 }
3472
3473 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3474 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3475 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3476   EVT VT = N->getValueType(0);
3477   unsigned NumElems = VT.getVectorNumElements();
3478
3479   if (VT.getSizeInBits() != 128)
3480     return false;
3481
3482   if (NumElems != 4)
3483     return false;
3484
3485   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3486   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3487          isUndefOrEqual(N->getMaskElt(1), 7) &&
3488          isUndefOrEqual(N->getMaskElt(2), 2) &&
3489          isUndefOrEqual(N->getMaskElt(3), 3);
3490 }
3491
3492 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3493 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3494 /// <2, 3, 2, 3>
3495 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3496   EVT VT = N->getValueType(0);
3497   unsigned NumElems = VT.getVectorNumElements();
3498
3499   if (VT.getSizeInBits() != 128)
3500     return false;
3501
3502   if (NumElems != 4)
3503     return false;
3504
3505   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3506          isUndefOrEqual(N->getMaskElt(1), 3) &&
3507          isUndefOrEqual(N->getMaskElt(2), 2) &&
3508          isUndefOrEqual(N->getMaskElt(3), 3);
3509 }
3510
3511 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3512 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3513 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3514   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3515
3516   if (NumElems != 2 && NumElems != 4)
3517     return false;
3518
3519   for (unsigned i = 0; i < NumElems/2; ++i)
3520     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3521       return false;
3522
3523   for (unsigned i = NumElems/2; i < NumElems; ++i)
3524     if (!isUndefOrEqual(N->getMaskElt(i), i))
3525       return false;
3526
3527   return true;
3528 }
3529
3530 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3531 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3532 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3533   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3534
3535   if ((NumElems != 2 && NumElems != 4)
3536       || N->getValueType(0).getSizeInBits() > 128)
3537     return false;
3538
3539   for (unsigned i = 0; i < NumElems/2; ++i)
3540     if (!isUndefOrEqual(N->getMaskElt(i), i))
3541       return false;
3542
3543   for (unsigned i = 0; i < NumElems/2; ++i)
3544     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3545       return false;
3546
3547   return true;
3548 }
3549
3550 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3551 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3552 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3553                          bool V2IsSplat = false) {
3554   int NumElts = VT.getVectorNumElements();
3555
3556   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3557          "Unsupported vector type for unpckh");
3558
3559   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3560     return false;
3561
3562   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3563   // independently on 128-bit lanes.
3564   unsigned NumLanes = VT.getSizeInBits()/128;
3565   unsigned NumLaneElts = NumElts/NumLanes;
3566
3567   unsigned Start = 0;
3568   unsigned End = NumLaneElts;
3569   for (unsigned s = 0; s < NumLanes; ++s) {
3570     for (unsigned i = Start, j = s * NumLaneElts;
3571          i != End;
3572          i += 2, ++j) {
3573       int BitI  = Mask[i];
3574       int BitI1 = Mask[i+1];
3575       if (!isUndefOrEqual(BitI, j))
3576         return false;
3577       if (V2IsSplat) {
3578         if (!isUndefOrEqual(BitI1, NumElts))
3579           return false;
3580       } else {
3581         if (!isUndefOrEqual(BitI1, j + NumElts))
3582           return false;
3583       }
3584     }
3585     // Process the next 128 bits.
3586     Start += NumLaneElts;
3587     End += NumLaneElts;
3588   }
3589
3590   return true;
3591 }
3592
3593 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3594   SmallVector<int, 8> M;
3595   N->getMask(M);
3596   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3597 }
3598
3599 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3600 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3601 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3602                          bool V2IsSplat = false) {
3603   int NumElts = VT.getVectorNumElements();
3604
3605   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3606          "Unsupported vector type for unpckh");
3607
3608   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3609     return false;
3610
3611   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3612   // independently on 128-bit lanes.
3613   unsigned NumLanes = VT.getSizeInBits()/128;
3614   unsigned NumLaneElts = NumElts/NumLanes;
3615
3616   unsigned Start = 0;
3617   unsigned End = NumLaneElts;
3618   for (unsigned l = 0; l != NumLanes; ++l) {
3619     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3620                              i != End; i += 2, ++j) {
3621       int BitI  = Mask[i];
3622       int BitI1 = Mask[i+1];
3623       if (!isUndefOrEqual(BitI, j))
3624         return false;
3625       if (V2IsSplat) {
3626         if (isUndefOrEqual(BitI1, NumElts))
3627           return false;
3628       } else {
3629         if (!isUndefOrEqual(BitI1, j+NumElts))
3630           return false;
3631       }
3632     }
3633     // Process the next 128 bits.
3634     Start += NumLaneElts;
3635     End += NumLaneElts;
3636   }
3637   return true;
3638 }
3639
3640 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3641   SmallVector<int, 8> M;
3642   N->getMask(M);
3643   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3644 }
3645
3646 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3647 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3648 /// <0, 0, 1, 1>
3649 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3650   int NumElems = VT.getVectorNumElements();
3651   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3652     return false;
3653
3654   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3655   // FIXME: Need a better way to get rid of this, there's no latency difference
3656   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3657   // the former later. We should also remove the "_undef" special mask.
3658   if (NumElems == 4 && VT.getSizeInBits() == 256)
3659     return false;
3660
3661   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3662   // independently on 128-bit lanes.
3663   unsigned NumLanes = VT.getSizeInBits() / 128;
3664   unsigned NumLaneElts = NumElems / NumLanes;
3665
3666   for (unsigned s = 0; s < NumLanes; ++s) {
3667     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3668          i != NumLaneElts * (s + 1);
3669          i += 2, ++j) {
3670       int BitI  = Mask[i];
3671       int BitI1 = Mask[i+1];
3672
3673       if (!isUndefOrEqual(BitI, j))
3674         return false;
3675       if (!isUndefOrEqual(BitI1, j))
3676         return false;
3677     }
3678   }
3679
3680   return true;
3681 }
3682
3683 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3684   SmallVector<int, 8> M;
3685   N->getMask(M);
3686   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3687 }
3688
3689 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3690 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3691 /// <2, 2, 3, 3>
3692 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3693   int NumElems = VT.getVectorNumElements();
3694   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3695     return false;
3696
3697   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3698     int BitI  = Mask[i];
3699     int BitI1 = Mask[i+1];
3700     if (!isUndefOrEqual(BitI, j))
3701       return false;
3702     if (!isUndefOrEqual(BitI1, j))
3703       return false;
3704   }
3705   return true;
3706 }
3707
3708 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3709   SmallVector<int, 8> M;
3710   N->getMask(M);
3711   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3712 }
3713
3714 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3715 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3716 /// MOVSD, and MOVD, i.e. setting the lowest element.
3717 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3718   if (VT.getVectorElementType().getSizeInBits() < 32)
3719     return false;
3720
3721   int NumElts = VT.getVectorNumElements();
3722
3723   if (!isUndefOrEqual(Mask[0], NumElts))
3724     return false;
3725
3726   for (int i = 1; i < NumElts; ++i)
3727     if (!isUndefOrEqual(Mask[i], i))
3728       return false;
3729
3730   return true;
3731 }
3732
3733 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3734   SmallVector<int, 8> M;
3735   N->getMask(M);
3736   return ::isMOVLMask(M, N->getValueType(0));
3737 }
3738
3739 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3740 /// as permutations between 128-bit chunks or halves. As an example: this
3741 /// shuffle bellow:
3742 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3743 /// The first half comes from the second half of V1 and the second half from the
3744 /// the second half of V2.
3745 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3746                              const X86Subtarget *Subtarget) {
3747   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3748     return false;
3749
3750   // The shuffle result is divided into half A and half B. In total the two
3751   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3752   // B must come from C, D, E or F.
3753   int HalfSize = VT.getVectorNumElements()/2;
3754   bool MatchA = false, MatchB = false;
3755
3756   // Check if A comes from one of C, D, E, F.
3757   for (int Half = 0; Half < 4; ++Half) {
3758     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3759       MatchA = true;
3760       break;
3761     }
3762   }
3763
3764   // Check if B comes from one of C, D, E, F.
3765   for (int Half = 0; Half < 4; ++Half) {
3766     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3767       MatchB = true;
3768       break;
3769     }
3770   }
3771
3772   return MatchA && MatchB;
3773 }
3774
3775 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3776 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3777 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3778   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3779   EVT VT = SVOp->getValueType(0);
3780
3781   int HalfSize = VT.getVectorNumElements()/2;
3782
3783   int FstHalf = 0, SndHalf = 0;
3784   for (int i = 0; i < HalfSize; ++i) {
3785     if (SVOp->getMaskElt(i) > 0) {
3786       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3787       break;
3788     }
3789   }
3790   for (int i = HalfSize; i < HalfSize*2; ++i) {
3791     if (SVOp->getMaskElt(i) > 0) {
3792       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3793       break;
3794     }
3795   }
3796
3797   return (FstHalf | (SndHalf << 4));
3798 }
3799
3800 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3801 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3802 /// Note that VPERMIL mask matching is different depending whether theunderlying
3803 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3804 /// to the same elements of the low, but to the higher half of the source.
3805 /// In VPERMILPD the two lanes could be shuffled independently of each other
3806 /// with the same restriction that lanes can't be crossed.
3807 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3808                             const X86Subtarget *Subtarget) {
3809   int NumElts = VT.getVectorNumElements();
3810   int NumLanes = VT.getSizeInBits()/128;
3811
3812   if (!Subtarget->hasAVX())
3813     return false;
3814
3815   // Only match 256-bit with 64-bit types
3816   if (VT.getSizeInBits() != 256 || NumElts != 4)
3817     return false;
3818
3819   // The mask on the high lane is independent of the low. Both can match
3820   // any element in inside its own lane, but can't cross.
3821   int LaneSize = NumElts/NumLanes;
3822   for (int l = 0; l < NumLanes; ++l)
3823     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3824       int LaneStart = l*LaneSize;
3825       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3826         return false;
3827     }
3828
3829   return true;
3830 }
3831
3832 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3833 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3834 /// Note that VPERMIL mask matching is different depending whether theunderlying
3835 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3836 /// to the same elements of the low, but to the higher half of the source.
3837 /// In VPERMILPD the two lanes could be shuffled independently of each other
3838 /// with the same restriction that lanes can't be crossed.
3839 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3840                             const X86Subtarget *Subtarget) {
3841   unsigned NumElts = VT.getVectorNumElements();
3842   unsigned NumLanes = VT.getSizeInBits()/128;
3843
3844   if (!Subtarget->hasAVX())
3845     return false;
3846
3847   // Only match 256-bit with 32-bit types
3848   if (VT.getSizeInBits() != 256 || NumElts != 8)
3849     return false;
3850
3851   // The mask on the high lane should be the same as the low. Actually,
3852   // they can differ if any of the corresponding index in a lane is undef
3853   // and the other stays in range.
3854   int LaneSize = NumElts/NumLanes;
3855   for (int i = 0; i < LaneSize; ++i) {
3856     int HighElt = i+LaneSize;
3857     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3858     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3859
3860     if (!HighValid || !LowValid)
3861       return false;
3862     if (Mask[i] < 0 || Mask[HighElt] < 0)
3863       continue;
3864     if (Mask[HighElt]-Mask[i] != LaneSize)
3865       return false;
3866   }
3867
3868   return true;
3869 }
3870
3871 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3872 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3873 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3875   EVT VT = SVOp->getValueType(0);
3876
3877   int NumElts = VT.getVectorNumElements();
3878   int NumLanes = VT.getSizeInBits()/128;
3879   int LaneSize = NumElts/NumLanes;
3880
3881   // Although the mask is equal for both lanes do it twice to get the cases
3882   // where a mask will match because the same mask element is undef on the
3883   // first half but valid on the second. This would get pathological cases
3884   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3885   unsigned Mask = 0;
3886   for (int l = 0; l < NumLanes; ++l) {
3887     for (int i = 0; i < LaneSize; ++i) {
3888       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3889       if (MaskElt < 0)
3890         continue;
3891       if (MaskElt >= LaneSize)
3892         MaskElt -= LaneSize;
3893       Mask |= MaskElt << (i*2);
3894     }
3895   }
3896
3897   return Mask;
3898 }
3899
3900 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3901 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3902 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3903   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3904   EVT VT = SVOp->getValueType(0);
3905
3906   int NumElts = VT.getVectorNumElements();
3907   int NumLanes = VT.getSizeInBits()/128;
3908
3909   unsigned Mask = 0;
3910   int LaneSize = NumElts/NumLanes;
3911   for (int l = 0; l < NumLanes; ++l)
3912     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3913       int MaskElt = SVOp->getMaskElt(i);
3914       if (MaskElt < 0)
3915         continue;
3916       Mask |= (MaskElt-l*LaneSize) << i;
3917     }
3918
3919   return Mask;
3920 }
3921
3922 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3923 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3924 /// element of vector 2 and the other elements to come from vector 1 in order.
3925 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3926                                bool V2IsSplat = false, bool V2IsUndef = false) {
3927   int NumOps = VT.getVectorNumElements();
3928   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3929     return false;
3930
3931   if (!isUndefOrEqual(Mask[0], 0))
3932     return false;
3933
3934   for (int i = 1; i < NumOps; ++i)
3935     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3936           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3937           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3938       return false;
3939
3940   return true;
3941 }
3942
3943 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3944                            bool V2IsUndef = false) {
3945   SmallVector<int, 8> M;
3946   N->getMask(M);
3947   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3948 }
3949
3950 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3951 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3952 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3953 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3954                          const X86Subtarget *Subtarget) {
3955   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3956     return false;
3957
3958   // The second vector must be undef
3959   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3960     return false;
3961
3962   EVT VT = N->getValueType(0);
3963   unsigned NumElems = VT.getVectorNumElements();
3964
3965   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3966       (VT.getSizeInBits() == 256 && NumElems != 8))
3967     return false;
3968
3969   // "i+1" is the value the indexed mask element must have
3970   for (unsigned i = 0; i < NumElems; i += 2)
3971     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3972         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3973       return false;
3974
3975   return true;
3976 }
3977
3978 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3980 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3981 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3982                          const X86Subtarget *Subtarget) {
3983   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3984     return false;
3985
3986   // The second vector must be undef
3987   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3988     return false;
3989
3990   EVT VT = N->getValueType(0);
3991   unsigned NumElems = VT.getVectorNumElements();
3992
3993   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3994       (VT.getSizeInBits() == 256 && NumElems != 8))
3995     return false;
3996
3997   // "i" is the value the indexed mask element must have
3998   for (unsigned i = 0; i < NumElems; i += 2)
3999     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4000         !isUndefOrEqual(N->getMaskElt(i+1), i))
4001       return false;
4002
4003   return true;
4004 }
4005
4006 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4007 /// specifies a shuffle of elements that is suitable for input to 256-bit
4008 /// version of MOVDDUP.
4009 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4010                            const X86Subtarget *Subtarget) {
4011   EVT VT = N->getValueType(0);
4012   int NumElts = VT.getVectorNumElements();
4013   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4014
4015   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4016       !V2IsUndef || NumElts != 4)
4017     return false;
4018
4019   for (int i = 0; i != NumElts/2; ++i)
4020     if (!isUndefOrEqual(N->getMaskElt(i), 0))
4021       return false;
4022   for (int i = NumElts/2; i != NumElts; ++i)
4023     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4024       return false;
4025   return true;
4026 }
4027
4028 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4029 /// specifies a shuffle of elements that is suitable for input to 128-bit
4030 /// version of MOVDDUP.
4031 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4032   EVT VT = N->getValueType(0);
4033
4034   if (VT.getSizeInBits() != 128)
4035     return false;
4036
4037   int e = VT.getVectorNumElements() / 2;
4038   for (int i = 0; i < e; ++i)
4039     if (!isUndefOrEqual(N->getMaskElt(i), i))
4040       return false;
4041   for (int i = 0; i < e; ++i)
4042     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4043       return false;
4044   return true;
4045 }
4046
4047 /// isVEXTRACTF128Index - Return true if the specified
4048 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4049 /// suitable for input to VEXTRACTF128.
4050 bool X86::isVEXTRACTF128Index(SDNode *N) {
4051   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4052     return false;
4053
4054   // The index should be aligned on a 128-bit boundary.
4055   uint64_t Index =
4056     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4057
4058   unsigned VL = N->getValueType(0).getVectorNumElements();
4059   unsigned VBits = N->getValueType(0).getSizeInBits();
4060   unsigned ElSize = VBits / VL;
4061   bool Result = (Index * ElSize) % 128 == 0;
4062
4063   return Result;
4064 }
4065
4066 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4067 /// operand specifies a subvector insert that is suitable for input to
4068 /// VINSERTF128.
4069 bool X86::isVINSERTF128Index(SDNode *N) {
4070   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4071     return false;
4072
4073   // The index should be aligned on a 128-bit boundary.
4074   uint64_t Index =
4075     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4076
4077   unsigned VL = N->getValueType(0).getVectorNumElements();
4078   unsigned VBits = N->getValueType(0).getSizeInBits();
4079   unsigned ElSize = VBits / VL;
4080   bool Result = (Index * ElSize) % 128 == 0;
4081
4082   return Result;
4083 }
4084
4085 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4086 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4087 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4088   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4089   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4090
4091   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4092   unsigned Mask = 0;
4093   for (int i = 0; i < NumOperands; ++i) {
4094     int Val = SVOp->getMaskElt(NumOperands-i-1);
4095     if (Val < 0) Val = 0;
4096     if (Val >= NumOperands) Val -= NumOperands;
4097     Mask |= Val;
4098     if (i != NumOperands - 1)
4099       Mask <<= Shift;
4100   }
4101   return Mask;
4102 }
4103
4104 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4105 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4106 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4107   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4108   unsigned Mask = 0;
4109   // 8 nodes, but we only care about the last 4.
4110   for (unsigned i = 7; i >= 4; --i) {
4111     int Val = SVOp->getMaskElt(i);
4112     if (Val >= 0)
4113       Mask |= (Val - 4);
4114     if (i != 4)
4115       Mask <<= 2;
4116   }
4117   return Mask;
4118 }
4119
4120 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4121 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4122 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4123   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4124   unsigned Mask = 0;
4125   // 8 nodes, but we only care about the first 4.
4126   for (int i = 3; i >= 0; --i) {
4127     int Val = SVOp->getMaskElt(i);
4128     if (Val >= 0)
4129       Mask |= Val;
4130     if (i != 0)
4131       Mask <<= 2;
4132   }
4133   return Mask;
4134 }
4135
4136 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4137 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4138 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4139   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4140   EVT VVT = N->getValueType(0);
4141   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4142   int Val = 0;
4143
4144   unsigned i, e;
4145   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4146     Val = SVOp->getMaskElt(i);
4147     if (Val >= 0)
4148       break;
4149   }
4150   assert(Val - i > 0 && "PALIGNR imm should be positive");
4151   return (Val - i) * EltSize;
4152 }
4153
4154 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4155 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4156 /// instructions.
4157 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4158   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4159     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4160
4161   uint64_t Index =
4162     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4163
4164   EVT VecVT = N->getOperand(0).getValueType();
4165   EVT ElVT = VecVT.getVectorElementType();
4166
4167   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4168   return Index / NumElemsPerChunk;
4169 }
4170
4171 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4172 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4173 /// instructions.
4174 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4175   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4176     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4177
4178   uint64_t Index =
4179     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4180
4181   EVT VecVT = N->getValueType(0);
4182   EVT ElVT = VecVT.getVectorElementType();
4183
4184   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4185   return Index / NumElemsPerChunk;
4186 }
4187
4188 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4189 /// constant +0.0.
4190 bool X86::isZeroNode(SDValue Elt) {
4191   return ((isa<ConstantSDNode>(Elt) &&
4192            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4193           (isa<ConstantFPSDNode>(Elt) &&
4194            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4195 }
4196
4197 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4198 /// their permute mask.
4199 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4200                                     SelectionDAG &DAG) {
4201   EVT VT = SVOp->getValueType(0);
4202   unsigned NumElems = VT.getVectorNumElements();
4203   SmallVector<int, 8> MaskVec;
4204
4205   for (unsigned i = 0; i != NumElems; ++i) {
4206     int idx = SVOp->getMaskElt(i);
4207     if (idx < 0)
4208       MaskVec.push_back(idx);
4209     else if (idx < (int)NumElems)
4210       MaskVec.push_back(idx + NumElems);
4211     else
4212       MaskVec.push_back(idx - NumElems);
4213   }
4214   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4215                               SVOp->getOperand(0), &MaskVec[0]);
4216 }
4217
4218 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4219 /// the two vector operands have swapped position.
4220 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4221   unsigned NumElems = VT.getVectorNumElements();
4222   for (unsigned i = 0; i != NumElems; ++i) {
4223     int idx = Mask[i];
4224     if (idx < 0)
4225       continue;
4226     else if (idx < (int)NumElems)
4227       Mask[i] = idx + NumElems;
4228     else
4229       Mask[i] = idx - NumElems;
4230   }
4231 }
4232
4233 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4234 /// match movhlps. The lower half elements should come from upper half of
4235 /// V1 (and in order), and the upper half elements should come from the upper
4236 /// half of V2 (and in order).
4237 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4238   EVT VT = Op->getValueType(0);
4239   if (VT.getSizeInBits() != 128)
4240     return false;
4241   if (VT.getVectorNumElements() != 4)
4242     return false;
4243   for (unsigned i = 0, e = 2; i != e; ++i)
4244     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4245       return false;
4246   for (unsigned i = 2; i != 4; ++i)
4247     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4248       return false;
4249   return true;
4250 }
4251
4252 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4253 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4254 /// required.
4255 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4256   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4257     return false;
4258   N = N->getOperand(0).getNode();
4259   if (!ISD::isNON_EXTLoad(N))
4260     return false;
4261   if (LD)
4262     *LD = cast<LoadSDNode>(N);
4263   return true;
4264 }
4265
4266 // Test whether the given value is a vector value which will be legalized
4267 // into a load.
4268 static bool WillBeConstantPoolLoad(SDNode *N) {
4269   if (N->getOpcode() != ISD::BUILD_VECTOR)
4270     return false;
4271
4272   // Check for any non-constant elements.
4273   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4274     switch (N->getOperand(i).getNode()->getOpcode()) {
4275     case ISD::UNDEF:
4276     case ISD::ConstantFP:
4277     case ISD::Constant:
4278       break;
4279     default:
4280       return false;
4281     }
4282
4283   // Vectors of all-zeros and all-ones are materialized with special
4284   // instructions rather than being loaded.
4285   return !ISD::isBuildVectorAllZeros(N) &&
4286          !ISD::isBuildVectorAllOnes(N);
4287 }
4288
4289 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4290 /// match movlp{s|d}. The lower half elements should come from lower half of
4291 /// V1 (and in order), and the upper half elements should come from the upper
4292 /// half of V2 (and in order). And since V1 will become the source of the
4293 /// MOVLP, it must be either a vector load or a scalar load to vector.
4294 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4295                                ShuffleVectorSDNode *Op) {
4296   EVT VT = Op->getValueType(0);
4297   if (VT.getSizeInBits() != 128)
4298     return false;
4299
4300   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4301     return false;
4302   // Is V2 is a vector load, don't do this transformation. We will try to use
4303   // load folding shufps op.
4304   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4305     return false;
4306
4307   unsigned NumElems = VT.getVectorNumElements();
4308
4309   if (NumElems != 2 && NumElems != 4)
4310     return false;
4311   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4312     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4313       return false;
4314   for (unsigned i = NumElems/2; i != NumElems; ++i)
4315     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4316       return false;
4317   return true;
4318 }
4319
4320 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4321 /// all the same.
4322 static bool isSplatVector(SDNode *N) {
4323   if (N->getOpcode() != ISD::BUILD_VECTOR)
4324     return false;
4325
4326   SDValue SplatValue = N->getOperand(0);
4327   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4328     if (N->getOperand(i) != SplatValue)
4329       return false;
4330   return true;
4331 }
4332
4333 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4334 /// to an zero vector.
4335 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4336 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4337   SDValue V1 = N->getOperand(0);
4338   SDValue V2 = N->getOperand(1);
4339   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4340   for (unsigned i = 0; i != NumElems; ++i) {
4341     int Idx = N->getMaskElt(i);
4342     if (Idx >= (int)NumElems) {
4343       unsigned Opc = V2.getOpcode();
4344       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4345         continue;
4346       if (Opc != ISD::BUILD_VECTOR ||
4347           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4348         return false;
4349     } else if (Idx >= 0) {
4350       unsigned Opc = V1.getOpcode();
4351       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4352         continue;
4353       if (Opc != ISD::BUILD_VECTOR ||
4354           !X86::isZeroNode(V1.getOperand(Idx)))
4355         return false;
4356     }
4357   }
4358   return true;
4359 }
4360
4361 /// getZeroVector - Returns a vector of specified type with all zero elements.
4362 ///
4363 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4364                              DebugLoc dl) {
4365   assert(VT.isVector() && "Expected a vector type");
4366
4367   // Always build SSE zero vectors as <4 x i32> bitcasted
4368   // to their dest type. This ensures they get CSE'd.
4369   SDValue Vec;
4370   if (VT.getSizeInBits() == 128) {  // SSE
4371     if (HasXMMInt) {  // SSE2
4372       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4373       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4374     } else { // SSE1
4375       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4376       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4377     }
4378   } else if (VT.getSizeInBits() == 256) { // AVX
4379     // 256-bit logic and arithmetic instructions in AVX are
4380     // all floating-point, no support for integer ops. Default
4381     // to emitting fp zeroed vectors then.
4382     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4383     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4384     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4385   }
4386   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4387 }
4388
4389 /// getOnesVector - Returns a vector of specified type with all bits set.
4390 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4391 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4392 /// original type, ensuring they get CSE'd.
4393 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4394   assert(VT.isVector() && "Expected a vector type");
4395   assert((VT.is128BitVector() || VT.is256BitVector())
4396          && "Expected a 128-bit or 256-bit vector type");
4397
4398   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4399   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4400                             Cst, Cst, Cst, Cst);
4401
4402   if (VT.is256BitVector()) {
4403     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4404                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4405     Vec = Insert128BitVector(InsV, Vec,
4406                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4407   }
4408
4409   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4410 }
4411
4412 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4413 /// that point to V2 points to its first element.
4414 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4415   EVT VT = SVOp->getValueType(0);
4416   unsigned NumElems = VT.getVectorNumElements();
4417
4418   bool Changed = false;
4419   SmallVector<int, 8> MaskVec;
4420   SVOp->getMask(MaskVec);
4421
4422   for (unsigned i = 0; i != NumElems; ++i) {
4423     if (MaskVec[i] > (int)NumElems) {
4424       MaskVec[i] = NumElems;
4425       Changed = true;
4426     }
4427   }
4428   if (Changed)
4429     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4430                                 SVOp->getOperand(1), &MaskVec[0]);
4431   return SDValue(SVOp, 0);
4432 }
4433
4434 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4435 /// operation of specified width.
4436 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4437                        SDValue V2) {
4438   unsigned NumElems = VT.getVectorNumElements();
4439   SmallVector<int, 8> Mask;
4440   Mask.push_back(NumElems);
4441   for (unsigned i = 1; i != NumElems; ++i)
4442     Mask.push_back(i);
4443   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4444 }
4445
4446 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4447 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4448                           SDValue V2) {
4449   unsigned NumElems = VT.getVectorNumElements();
4450   SmallVector<int, 8> Mask;
4451   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4452     Mask.push_back(i);
4453     Mask.push_back(i + NumElems);
4454   }
4455   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4456 }
4457
4458 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4459 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4460                           SDValue V2) {
4461   unsigned NumElems = VT.getVectorNumElements();
4462   unsigned Half = NumElems/2;
4463   SmallVector<int, 8> Mask;
4464   for (unsigned i = 0; i != Half; ++i) {
4465     Mask.push_back(i + Half);
4466     Mask.push_back(i + NumElems + Half);
4467   }
4468   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4469 }
4470
4471 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4472 // a generic shuffle instruction because the target has no such instructions.
4473 // Generate shuffles which repeat i16 and i8 several times until they can be
4474 // represented by v4f32 and then be manipulated by target suported shuffles.
4475 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4476   EVT VT = V.getValueType();
4477   int NumElems = VT.getVectorNumElements();
4478   DebugLoc dl = V.getDebugLoc();
4479
4480   while (NumElems > 4) {
4481     if (EltNo < NumElems/2) {
4482       V = getUnpackl(DAG, dl, VT, V, V);
4483     } else {
4484       V = getUnpackh(DAG, dl, VT, V, V);
4485       EltNo -= NumElems/2;
4486     }
4487     NumElems >>= 1;
4488   }
4489   return V;
4490 }
4491
4492 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4493 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4494   EVT VT = V.getValueType();
4495   DebugLoc dl = V.getDebugLoc();
4496   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4497          && "Vector size not supported");
4498
4499   if (VT.getSizeInBits() == 128) {
4500     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4501     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4502     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4503                              &SplatMask[0]);
4504   } else {
4505     // To use VPERMILPS to splat scalars, the second half of indicies must
4506     // refer to the higher part, which is a duplication of the lower one,
4507     // because VPERMILPS can only handle in-lane permutations.
4508     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4509                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4510
4511     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4512     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4513                              &SplatMask[0]);
4514   }
4515
4516   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4517 }
4518
4519 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4520 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4521   EVT SrcVT = SV->getValueType(0);
4522   SDValue V1 = SV->getOperand(0);
4523   DebugLoc dl = SV->getDebugLoc();
4524
4525   int EltNo = SV->getSplatIndex();
4526   int NumElems = SrcVT.getVectorNumElements();
4527   unsigned Size = SrcVT.getSizeInBits();
4528
4529   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4530           "Unknown how to promote splat for type");
4531
4532   // Extract the 128-bit part containing the splat element and update
4533   // the splat element index when it refers to the higher register.
4534   if (Size == 256) {
4535     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4536     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4537     if (Idx > 0)
4538       EltNo -= NumElems/2;
4539   }
4540
4541   // All i16 and i8 vector types can't be used directly by a generic shuffle
4542   // instruction because the target has no such instruction. Generate shuffles
4543   // which repeat i16 and i8 several times until they fit in i32, and then can
4544   // be manipulated by target suported shuffles.
4545   EVT EltVT = SrcVT.getVectorElementType();
4546   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4547     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4548
4549   // Recreate the 256-bit vector and place the same 128-bit vector
4550   // into the low and high part. This is necessary because we want
4551   // to use VPERM* to shuffle the vectors
4552   if (Size == 256) {
4553     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4554                          DAG.getConstant(0, MVT::i32), DAG, dl);
4555     V1 = Insert128BitVector(InsV, V1,
4556                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4557   }
4558
4559   return getLegalSplat(DAG, V1, EltNo);
4560 }
4561
4562 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4563 /// vector of zero or undef vector.  This produces a shuffle where the low
4564 /// element of V2 is swizzled into the zero/undef vector, landing at element
4565 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4566 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4567                                            bool isZero, bool HasXMMInt,
4568                                            SelectionDAG &DAG) {
4569   EVT VT = V2.getValueType();
4570   SDValue V1 = isZero
4571     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4572   unsigned NumElems = VT.getVectorNumElements();
4573   SmallVector<int, 16> MaskVec;
4574   for (unsigned i = 0; i != NumElems; ++i)
4575     // If this is the insertion idx, put the low elt of V2 here.
4576     MaskVec.push_back(i == Idx ? NumElems : i);
4577   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4578 }
4579
4580 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4581 /// element of the result of the vector shuffle.
4582 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4583                                    unsigned Depth) {
4584   if (Depth == 6)
4585     return SDValue();  // Limit search depth.
4586
4587   SDValue V = SDValue(N, 0);
4588   EVT VT = V.getValueType();
4589   unsigned Opcode = V.getOpcode();
4590
4591   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4592   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4593     Index = SV->getMaskElt(Index);
4594
4595     if (Index < 0)
4596       return DAG.getUNDEF(VT.getVectorElementType());
4597
4598     int NumElems = VT.getVectorNumElements();
4599     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4600     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4601   }
4602
4603   // Recurse into target specific vector shuffles to find scalars.
4604   if (isTargetShuffle(Opcode)) {
4605     int NumElems = VT.getVectorNumElements();
4606     SmallVector<unsigned, 16> ShuffleMask;
4607     SDValue ImmN;
4608
4609     switch(Opcode) {
4610     case X86ISD::SHUFPS:
4611     case X86ISD::SHUFPD:
4612       ImmN = N->getOperand(N->getNumOperands()-1);
4613       DecodeSHUFPSMask(NumElems,
4614                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4615                        ShuffleMask);
4616       break;
4617     case X86ISD::PUNPCKHBW:
4618     case X86ISD::PUNPCKHWD:
4619     case X86ISD::PUNPCKHDQ:
4620     case X86ISD::PUNPCKHQDQ:
4621       DecodePUNPCKHMask(NumElems, ShuffleMask);
4622       break;
4623     case X86ISD::UNPCKHPS:
4624     case X86ISD::UNPCKHPD:
4625     case X86ISD::VUNPCKHPSY:
4626     case X86ISD::VUNPCKHPDY:
4627       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4628       break;
4629     case X86ISD::PUNPCKLBW:
4630     case X86ISD::PUNPCKLWD:
4631     case X86ISD::PUNPCKLDQ:
4632     case X86ISD::PUNPCKLQDQ:
4633       DecodePUNPCKLMask(VT, ShuffleMask);
4634       break;
4635     case X86ISD::UNPCKLPS:
4636     case X86ISD::UNPCKLPD:
4637     case X86ISD::VUNPCKLPSY:
4638     case X86ISD::VUNPCKLPDY:
4639       DecodeUNPCKLPMask(VT, ShuffleMask);
4640       break;
4641     case X86ISD::MOVHLPS:
4642       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4643       break;
4644     case X86ISD::MOVLHPS:
4645       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4646       break;
4647     case X86ISD::PSHUFD:
4648       ImmN = N->getOperand(N->getNumOperands()-1);
4649       DecodePSHUFMask(NumElems,
4650                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4651                       ShuffleMask);
4652       break;
4653     case X86ISD::PSHUFHW:
4654       ImmN = N->getOperand(N->getNumOperands()-1);
4655       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4656                         ShuffleMask);
4657       break;
4658     case X86ISD::PSHUFLW:
4659       ImmN = N->getOperand(N->getNumOperands()-1);
4660       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4661                         ShuffleMask);
4662       break;
4663     case X86ISD::MOVSS:
4664     case X86ISD::MOVSD: {
4665       // The index 0 always comes from the first element of the second source,
4666       // this is why MOVSS and MOVSD are used in the first place. The other
4667       // elements come from the other positions of the first source vector.
4668       unsigned OpNum = (Index == 0) ? 1 : 0;
4669       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4670                                  Depth+1);
4671     }
4672     case X86ISD::VPERMILPS:
4673       ImmN = N->getOperand(N->getNumOperands()-1);
4674       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4675                         ShuffleMask);
4676       break;
4677     case X86ISD::VPERMILPSY:
4678       ImmN = N->getOperand(N->getNumOperands()-1);
4679       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4680                         ShuffleMask);
4681       break;
4682     case X86ISD::VPERMILPD:
4683       ImmN = N->getOperand(N->getNumOperands()-1);
4684       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4685                         ShuffleMask);
4686       break;
4687     case X86ISD::VPERMILPDY:
4688       ImmN = N->getOperand(N->getNumOperands()-1);
4689       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4690                         ShuffleMask);
4691       break;
4692     case X86ISD::VPERM2F128:
4693       ImmN = N->getOperand(N->getNumOperands()-1);
4694       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4695                            ShuffleMask);
4696       break;
4697     case X86ISD::MOVDDUP:
4698     case X86ISD::MOVLHPD:
4699     case X86ISD::MOVLPD:
4700     case X86ISD::MOVLPS:
4701     case X86ISD::MOVSHDUP:
4702     case X86ISD::MOVSLDUP:
4703     case X86ISD::PALIGN:
4704       return SDValue(); // Not yet implemented.
4705     default:
4706       assert(0 && "unknown target shuffle node");
4707       return SDValue();
4708     }
4709
4710     Index = ShuffleMask[Index];
4711     if (Index < 0)
4712       return DAG.getUNDEF(VT.getVectorElementType());
4713
4714     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4715     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4716                                Depth+1);
4717   }
4718
4719   // Actual nodes that may contain scalar elements
4720   if (Opcode == ISD::BITCAST) {
4721     V = V.getOperand(0);
4722     EVT SrcVT = V.getValueType();
4723     unsigned NumElems = VT.getVectorNumElements();
4724
4725     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4726       return SDValue();
4727   }
4728
4729   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4730     return (Index == 0) ? V.getOperand(0)
4731                           : DAG.getUNDEF(VT.getVectorElementType());
4732
4733   if (V.getOpcode() == ISD::BUILD_VECTOR)
4734     return V.getOperand(Index);
4735
4736   return SDValue();
4737 }
4738
4739 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4740 /// shuffle operation which come from a consecutively from a zero. The
4741 /// search can start in two different directions, from left or right.
4742 static
4743 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4744                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4745   int i = 0;
4746
4747   while (i < NumElems) {
4748     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4749     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4750     if (!(Elt.getNode() &&
4751          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4752       break;
4753     ++i;
4754   }
4755
4756   return i;
4757 }
4758
4759 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4760 /// MaskE correspond consecutively to elements from one of the vector operands,
4761 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4762 static
4763 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4764                               int OpIdx, int NumElems, unsigned &OpNum) {
4765   bool SeenV1 = false;
4766   bool SeenV2 = false;
4767
4768   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4769     int Idx = SVOp->getMaskElt(i);
4770     // Ignore undef indicies
4771     if (Idx < 0)
4772       continue;
4773
4774     if (Idx < NumElems)
4775       SeenV1 = true;
4776     else
4777       SeenV2 = true;
4778
4779     // Only accept consecutive elements from the same vector
4780     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4781       return false;
4782   }
4783
4784   OpNum = SeenV1 ? 0 : 1;
4785   return true;
4786 }
4787
4788 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4789 /// logical left shift of a vector.
4790 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4791                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4792   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4793   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4794               false /* check zeros from right */, DAG);
4795   unsigned OpSrc;
4796
4797   if (!NumZeros)
4798     return false;
4799
4800   // Considering the elements in the mask that are not consecutive zeros,
4801   // check if they consecutively come from only one of the source vectors.
4802   //
4803   //               V1 = {X, A, B, C}     0
4804   //                         \  \  \    /
4805   //   vector_shuffle V1, V2 <1, 2, 3, X>
4806   //
4807   if (!isShuffleMaskConsecutive(SVOp,
4808             0,                   // Mask Start Index
4809             NumElems-NumZeros-1, // Mask End Index
4810             NumZeros,            // Where to start looking in the src vector
4811             NumElems,            // Number of elements in vector
4812             OpSrc))              // Which source operand ?
4813     return false;
4814
4815   isLeft = false;
4816   ShAmt = NumZeros;
4817   ShVal = SVOp->getOperand(OpSrc);
4818   return true;
4819 }
4820
4821 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4822 /// logical left shift of a vector.
4823 static bool isVectorShiftLeft(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               true /* check zeros from left */, 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   //                           0    { A, B, X, X } = V2
4837   //                          / \    /  /
4838   //   vector_shuffle V1, V2 <X, X, 4, 5>
4839   //
4840   if (!isShuffleMaskConsecutive(SVOp,
4841             NumZeros,     // Mask Start Index
4842             NumElems-1,   // Mask End Index
4843             0,            // 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 = true;
4849   ShAmt = NumZeros;
4850   ShVal = SVOp->getOperand(OpSrc);
4851   return true;
4852 }
4853
4854 /// isVectorShift - Returns true if the shuffle can be implemented as a
4855 /// logical left or right shift of a vector.
4856 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4857                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4858   // Although the logic below support any bitwidth size, there are no
4859   // shift instructions which handle more than 128-bit vectors.
4860   if (SVOp->getValueType(0).getSizeInBits() > 128)
4861     return false;
4862
4863   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4864       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4865     return true;
4866
4867   return false;
4868 }
4869
4870 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4871 ///
4872 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4873                                        unsigned NumNonZero, unsigned NumZero,
4874                                        SelectionDAG &DAG,
4875                                        const TargetLowering &TLI) {
4876   if (NumNonZero > 8)
4877     return SDValue();
4878
4879   DebugLoc dl = Op.getDebugLoc();
4880   SDValue V(0, 0);
4881   bool First = true;
4882   for (unsigned i = 0; i < 16; ++i) {
4883     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4884     if (ThisIsNonZero && First) {
4885       if (NumZero)
4886         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4887       else
4888         V = DAG.getUNDEF(MVT::v8i16);
4889       First = false;
4890     }
4891
4892     if ((i & 1) != 0) {
4893       SDValue ThisElt(0, 0), LastElt(0, 0);
4894       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4895       if (LastIsNonZero) {
4896         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4897                               MVT::i16, Op.getOperand(i-1));
4898       }
4899       if (ThisIsNonZero) {
4900         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4901         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4902                               ThisElt, DAG.getConstant(8, MVT::i8));
4903         if (LastIsNonZero)
4904           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4905       } else
4906         ThisElt = LastElt;
4907
4908       if (ThisElt.getNode())
4909         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4910                         DAG.getIntPtrConstant(i/2));
4911     }
4912   }
4913
4914   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4915 }
4916
4917 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4918 ///
4919 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4920                                      unsigned NumNonZero, unsigned NumZero,
4921                                      SelectionDAG &DAG,
4922                                      const TargetLowering &TLI) {
4923   if (NumNonZero > 4)
4924     return SDValue();
4925
4926   DebugLoc dl = Op.getDebugLoc();
4927   SDValue V(0, 0);
4928   bool First = true;
4929   for (unsigned i = 0; i < 8; ++i) {
4930     bool isNonZero = (NonZeros & (1 << i)) != 0;
4931     if (isNonZero) {
4932       if (First) {
4933         if (NumZero)
4934           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4935         else
4936           V = DAG.getUNDEF(MVT::v8i16);
4937         First = false;
4938       }
4939       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4940                       MVT::v8i16, V, Op.getOperand(i),
4941                       DAG.getIntPtrConstant(i));
4942     }
4943   }
4944
4945   return V;
4946 }
4947
4948 /// getVShift - Return a vector logical shift node.
4949 ///
4950 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4951                          unsigned NumBits, SelectionDAG &DAG,
4952                          const TargetLowering &TLI, DebugLoc dl) {
4953   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4954   EVT ShVT = MVT::v2i64;
4955   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4956   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4957   return DAG.getNode(ISD::BITCAST, dl, VT,
4958                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4959                              DAG.getConstant(NumBits,
4960                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4961 }
4962
4963 SDValue
4964 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4965                                           SelectionDAG &DAG) const {
4966
4967   // Check if the scalar load can be widened into a vector load. And if
4968   // the address is "base + cst" see if the cst can be "absorbed" into
4969   // the shuffle mask.
4970   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4971     SDValue Ptr = LD->getBasePtr();
4972     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4973       return SDValue();
4974     EVT PVT = LD->getValueType(0);
4975     if (PVT != MVT::i32 && PVT != MVT::f32)
4976       return SDValue();
4977
4978     int FI = -1;
4979     int64_t Offset = 0;
4980     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4981       FI = FINode->getIndex();
4982       Offset = 0;
4983     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4984                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4985       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4986       Offset = Ptr.getConstantOperandVal(1);
4987       Ptr = Ptr.getOperand(0);
4988     } else {
4989       return SDValue();
4990     }
4991
4992     // FIXME: 256-bit vector instructions don't require a strict alignment,
4993     // improve this code to support it better.
4994     unsigned RequiredAlign = VT.getSizeInBits()/8;
4995     SDValue Chain = LD->getChain();
4996     // Make sure the stack object alignment is at least 16 or 32.
4997     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4998     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4999       if (MFI->isFixedObjectIndex(FI)) {
5000         // Can't change the alignment. FIXME: It's possible to compute
5001         // the exact stack offset and reference FI + adjust offset instead.
5002         // If someone *really* cares about this. That's the way to implement it.
5003         return SDValue();
5004       } else {
5005         MFI->setObjectAlignment(FI, RequiredAlign);
5006       }
5007     }
5008
5009     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5010     // Ptr + (Offset & ~15).
5011     if (Offset < 0)
5012       return SDValue();
5013     if ((Offset % RequiredAlign) & 3)
5014       return SDValue();
5015     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5016     if (StartOffset)
5017       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5018                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5019
5020     int EltNo = (Offset - StartOffset) >> 2;
5021     int NumElems = VT.getVectorNumElements();
5022
5023     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5024     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5025     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5026                              LD->getPointerInfo().getWithOffset(StartOffset),
5027                              false, false, false, 0);
5028
5029     // Canonicalize it to a v4i32 or v8i32 shuffle.
5030     SmallVector<int, 8> Mask;
5031     for (int i = 0; i < NumElems; ++i)
5032       Mask.push_back(EltNo);
5033
5034     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5035     return DAG.getNode(ISD::BITCAST, dl, NVT,
5036                        DAG.getVectorShuffle(CanonVT, dl, V1,
5037                                             DAG.getUNDEF(CanonVT),&Mask[0]));
5038   }
5039
5040   return SDValue();
5041 }
5042
5043 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5044 /// vector of type 'VT', see if the elements can be replaced by a single large
5045 /// load which has the same value as a build_vector whose operands are 'elts'.
5046 ///
5047 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5048 ///
5049 /// FIXME: we'd also like to handle the case where the last elements are zero
5050 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5051 /// There's even a handy isZeroNode for that purpose.
5052 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5053                                         DebugLoc &DL, SelectionDAG &DAG) {
5054   EVT EltVT = VT.getVectorElementType();
5055   unsigned NumElems = Elts.size();
5056
5057   LoadSDNode *LDBase = NULL;
5058   unsigned LastLoadedElt = -1U;
5059
5060   // For each element in the initializer, see if we've found a load or an undef.
5061   // If we don't find an initial load element, or later load elements are
5062   // non-consecutive, bail out.
5063   for (unsigned i = 0; i < NumElems; ++i) {
5064     SDValue Elt = Elts[i];
5065
5066     if (!Elt.getNode() ||
5067         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5068       return SDValue();
5069     if (!LDBase) {
5070       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5071         return SDValue();
5072       LDBase = cast<LoadSDNode>(Elt.getNode());
5073       LastLoadedElt = i;
5074       continue;
5075     }
5076     if (Elt.getOpcode() == ISD::UNDEF)
5077       continue;
5078
5079     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5080     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5081       return SDValue();
5082     LastLoadedElt = i;
5083   }
5084
5085   // If we have found an entire vector of loads and undefs, then return a large
5086   // load of the entire vector width starting at the base pointer.  If we found
5087   // consecutive loads for the low half, generate a vzext_load node.
5088   if (LastLoadedElt == NumElems - 1) {
5089     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5090       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5091                          LDBase->getPointerInfo(),
5092                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5093                          LDBase->isInvariant(), 0);
5094     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5095                        LDBase->getPointerInfo(),
5096                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5097                        LDBase->isInvariant(), LDBase->getAlignment());
5098   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5099              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5100     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5101     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5102     SDValue ResNode =
5103         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5104                                 LDBase->getPointerInfo(),
5105                                 LDBase->getAlignment(),
5106                                 false/*isVolatile*/, true/*ReadMem*/,
5107                                 false/*WriteMem*/);
5108     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5109   }
5110   return SDValue();
5111 }
5112
5113 SDValue
5114 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5115   DebugLoc dl = Op.getDebugLoc();
5116
5117   EVT VT = Op.getValueType();
5118   EVT ExtVT = VT.getVectorElementType();
5119   unsigned NumElems = Op.getNumOperands();
5120
5121   // Vectors containing all zeros can be matched by pxor and xorps later
5122   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5123     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5124     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5125     if (Op.getValueType() == MVT::v4i32 ||
5126         Op.getValueType() == MVT::v8i32)
5127       return Op;
5128
5129     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5130   }
5131
5132   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5133   // vectors or broken into v4i32 operations on 256-bit vectors.
5134   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5135     if (Op.getValueType() == MVT::v4i32)
5136       return Op;
5137
5138     return getOnesVector(Op.getValueType(), DAG, dl);
5139   }
5140
5141   unsigned EVTBits = ExtVT.getSizeInBits();
5142
5143   unsigned NumZero  = 0;
5144   unsigned NumNonZero = 0;
5145   unsigned NonZeros = 0;
5146   bool IsAllConstants = true;
5147   SmallSet<SDValue, 8> Values;
5148   for (unsigned i = 0; i < NumElems; ++i) {
5149     SDValue Elt = Op.getOperand(i);
5150     if (Elt.getOpcode() == ISD::UNDEF)
5151       continue;
5152     Values.insert(Elt);
5153     if (Elt.getOpcode() != ISD::Constant &&
5154         Elt.getOpcode() != ISD::ConstantFP)
5155       IsAllConstants = false;
5156     if (X86::isZeroNode(Elt))
5157       NumZero++;
5158     else {
5159       NonZeros |= (1 << i);
5160       NumNonZero++;
5161     }
5162   }
5163
5164   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5165   if (NumNonZero == 0)
5166     return DAG.getUNDEF(VT);
5167
5168   // Special case for single non-zero, non-undef, element.
5169   if (NumNonZero == 1) {
5170     unsigned Idx = CountTrailingZeros_32(NonZeros);
5171     SDValue Item = Op.getOperand(Idx);
5172
5173     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5174     // the value are obviously zero, truncate the value to i32 and do the
5175     // insertion that way.  Only do this if the value is non-constant or if the
5176     // value is a constant being inserted into element 0.  It is cheaper to do
5177     // a constant pool load than it is to do a movd + shuffle.
5178     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5179         (!IsAllConstants || Idx == 0)) {
5180       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5181         // Handle SSE only.
5182         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5183         EVT VecVT = MVT::v4i32;
5184         unsigned VecElts = 4;
5185
5186         // Truncate the value (which may itself be a constant) to i32, and
5187         // convert it to a vector with movd (S2V+shuffle to zero extend).
5188         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5189         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5190         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5191                                            Subtarget->hasXMMInt(), DAG);
5192
5193         // Now we have our 32-bit value zero extended in the low element of
5194         // a vector.  If Idx != 0, swizzle it into place.
5195         if (Idx != 0) {
5196           SmallVector<int, 4> Mask;
5197           Mask.push_back(Idx);
5198           for (unsigned i = 1; i != VecElts; ++i)
5199             Mask.push_back(i);
5200           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5201                                       DAG.getUNDEF(Item.getValueType()),
5202                                       &Mask[0]);
5203         }
5204         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5205       }
5206     }
5207
5208     // If we have a constant or non-constant insertion into the low element of
5209     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5210     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5211     // depending on what the source datatype is.
5212     if (Idx == 0) {
5213       if (NumZero == 0) {
5214         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5215       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5216           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5217         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5218         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5219         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5220                                            DAG);
5221       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5222         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5223         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5224         EVT MiddleVT = MVT::v4i32;
5225         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5226         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5227                                            Subtarget->hasXMMInt(), DAG);
5228         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5229       }
5230     }
5231
5232     // Is it a vector logical left shift?
5233     if (NumElems == 2 && Idx == 1 &&
5234         X86::isZeroNode(Op.getOperand(0)) &&
5235         !X86::isZeroNode(Op.getOperand(1))) {
5236       unsigned NumBits = VT.getSizeInBits();
5237       return getVShift(true, VT,
5238                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5239                                    VT, Op.getOperand(1)),
5240                        NumBits/2, DAG, *this, dl);
5241     }
5242
5243     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5244       return SDValue();
5245
5246     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5247     // is a non-constant being inserted into an element other than the low one,
5248     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5249     // movd/movss) to move this into the low element, then shuffle it into
5250     // place.
5251     if (EVTBits == 32) {
5252       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5253
5254       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5255       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5256                                          Subtarget->hasXMMInt(), DAG);
5257       SmallVector<int, 8> MaskVec;
5258       for (unsigned i = 0; i < NumElems; i++)
5259         MaskVec.push_back(i == Idx ? 0 : 1);
5260       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5261     }
5262   }
5263
5264   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5265   if (Values.size() == 1) {
5266     if (EVTBits == 32) {
5267       // Instead of a shuffle like this:
5268       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5269       // Check if it's possible to issue this instead.
5270       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5271       unsigned Idx = CountTrailingZeros_32(NonZeros);
5272       SDValue Item = Op.getOperand(Idx);
5273       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5274         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5275     }
5276     return SDValue();
5277   }
5278
5279   // A vector full of immediates; various special cases are already
5280   // handled, so this is best done with a single constant-pool load.
5281   if (IsAllConstants)
5282     return SDValue();
5283
5284   // For AVX-length vectors, build the individual 128-bit pieces and use
5285   // shuffles to put them in place.
5286   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5287     SmallVector<SDValue, 32> V;
5288     for (unsigned i = 0; i < NumElems; ++i)
5289       V.push_back(Op.getOperand(i));
5290
5291     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5292
5293     // Build both the lower and upper subvector.
5294     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5295     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5296                                 NumElems/2);
5297
5298     // Recreate the wider vector with the lower and upper part.
5299     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5300                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5301     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5302                               DAG, dl);
5303   }
5304
5305   // Let legalizer expand 2-wide build_vectors.
5306   if (EVTBits == 64) {
5307     if (NumNonZero == 1) {
5308       // One half is zero or undef.
5309       unsigned Idx = CountTrailingZeros_32(NonZeros);
5310       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5311                                  Op.getOperand(Idx));
5312       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5313                                          Subtarget->hasXMMInt(), DAG);
5314     }
5315     return SDValue();
5316   }
5317
5318   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5319   if (EVTBits == 8 && NumElems == 16) {
5320     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5321                                         *this);
5322     if (V.getNode()) return V;
5323   }
5324
5325   if (EVTBits == 16 && NumElems == 8) {
5326     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5327                                       *this);
5328     if (V.getNode()) return V;
5329   }
5330
5331   // If element VT is == 32 bits, turn it into a number of shuffles.
5332   SmallVector<SDValue, 8> V;
5333   V.resize(NumElems);
5334   if (NumElems == 4 && NumZero > 0) {
5335     for (unsigned i = 0; i < 4; ++i) {
5336       bool isZero = !(NonZeros & (1 << i));
5337       if (isZero)
5338         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5339       else
5340         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5341     }
5342
5343     for (unsigned i = 0; i < 2; ++i) {
5344       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5345         default: break;
5346         case 0:
5347           V[i] = V[i*2];  // Must be a zero vector.
5348           break;
5349         case 1:
5350           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5351           break;
5352         case 2:
5353           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5354           break;
5355         case 3:
5356           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5357           break;
5358       }
5359     }
5360
5361     SmallVector<int, 8> MaskVec;
5362     bool Reverse = (NonZeros & 0x3) == 2;
5363     for (unsigned i = 0; i < 2; ++i)
5364       MaskVec.push_back(Reverse ? 1-i : i);
5365     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5366     for (unsigned i = 0; i < 2; ++i)
5367       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5368     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5369   }
5370
5371   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5372     // Check for a build vector of consecutive loads.
5373     for (unsigned i = 0; i < NumElems; ++i)
5374       V[i] = Op.getOperand(i);
5375
5376     // Check for elements which are consecutive loads.
5377     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5378     if (LD.getNode())
5379       return LD;
5380
5381     // For SSE 4.1, use insertps to put the high elements into the low element.
5382     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5383       SDValue Result;
5384       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5385         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5386       else
5387         Result = DAG.getUNDEF(VT);
5388
5389       for (unsigned i = 1; i < NumElems; ++i) {
5390         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5391         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5392                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5393       }
5394       return Result;
5395     }
5396
5397     // Otherwise, expand into a number of unpckl*, start by extending each of
5398     // our (non-undef) elements to the full vector width with the element in the
5399     // bottom slot of the vector (which generates no code for SSE).
5400     for (unsigned i = 0; i < NumElems; ++i) {
5401       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5402         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5403       else
5404         V[i] = DAG.getUNDEF(VT);
5405     }
5406
5407     // Next, we iteratively mix elements, e.g. for v4f32:
5408     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5409     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5410     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5411     unsigned EltStride = NumElems >> 1;
5412     while (EltStride != 0) {
5413       for (unsigned i = 0; i < EltStride; ++i) {
5414         // If V[i+EltStride] is undef and this is the first round of mixing,
5415         // then it is safe to just drop this shuffle: V[i] is already in the
5416         // right place, the one element (since it's the first round) being
5417         // inserted as undef can be dropped.  This isn't safe for successive
5418         // rounds because they will permute elements within both vectors.
5419         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5420             EltStride == NumElems/2)
5421           continue;
5422
5423         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5424       }
5425       EltStride >>= 1;
5426     }
5427     return V[0];
5428   }
5429   return SDValue();
5430 }
5431
5432 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5433 // them in a MMX register.  This is better than doing a stack convert.
5434 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5435   DebugLoc dl = Op.getDebugLoc();
5436   EVT ResVT = Op.getValueType();
5437
5438   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5439          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5440   int Mask[2];
5441   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5442   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5443   InVec = Op.getOperand(1);
5444   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5445     unsigned NumElts = ResVT.getVectorNumElements();
5446     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5447     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5448                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5449   } else {
5450     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5451     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5452     Mask[0] = 0; Mask[1] = 2;
5453     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5454   }
5455   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5456 }
5457
5458 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5459 // to create 256-bit vectors from two other 128-bit ones.
5460 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5461   DebugLoc dl = Op.getDebugLoc();
5462   EVT ResVT = Op.getValueType();
5463
5464   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5465
5466   SDValue V1 = Op.getOperand(0);
5467   SDValue V2 = Op.getOperand(1);
5468   unsigned NumElems = ResVT.getVectorNumElements();
5469
5470   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5471                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5472   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5473                             DAG, dl);
5474 }
5475
5476 SDValue
5477 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5478   EVT ResVT = Op.getValueType();
5479
5480   assert(Op.getNumOperands() == 2);
5481   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5482          "Unsupported CONCAT_VECTORS for value type");
5483
5484   // We support concatenate two MMX registers and place them in a MMX register.
5485   // This is better than doing a stack convert.
5486   if (ResVT.is128BitVector())
5487     return LowerMMXCONCAT_VECTORS(Op, DAG);
5488
5489   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5490   // from two other 128-bit ones.
5491   return LowerAVXCONCAT_VECTORS(Op, DAG);
5492 }
5493
5494 // v8i16 shuffles - Prefer shuffles in the following order:
5495 // 1. [all]   pshuflw, pshufhw, optional move
5496 // 2. [ssse3] 1 x pshufb
5497 // 3. [ssse3] 2 x pshufb + 1 x por
5498 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5499 SDValue
5500 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5501                                             SelectionDAG &DAG) const {
5502   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5503   SDValue V1 = SVOp->getOperand(0);
5504   SDValue V2 = SVOp->getOperand(1);
5505   DebugLoc dl = SVOp->getDebugLoc();
5506   SmallVector<int, 8> MaskVals;
5507
5508   // Determine if more than 1 of the words in each of the low and high quadwords
5509   // of the result come from the same quadword of one of the two inputs.  Undef
5510   // mask values count as coming from any quadword, for better codegen.
5511   unsigned LoQuad[] = { 0, 0, 0, 0 };
5512   unsigned HiQuad[] = { 0, 0, 0, 0 };
5513   BitVector InputQuads(4);
5514   for (unsigned i = 0; i < 8; ++i) {
5515     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5516     int EltIdx = SVOp->getMaskElt(i);
5517     MaskVals.push_back(EltIdx);
5518     if (EltIdx < 0) {
5519       ++Quad[0];
5520       ++Quad[1];
5521       ++Quad[2];
5522       ++Quad[3];
5523       continue;
5524     }
5525     ++Quad[EltIdx / 4];
5526     InputQuads.set(EltIdx / 4);
5527   }
5528
5529   int BestLoQuad = -1;
5530   unsigned MaxQuad = 1;
5531   for (unsigned i = 0; i < 4; ++i) {
5532     if (LoQuad[i] > MaxQuad) {
5533       BestLoQuad = i;
5534       MaxQuad = LoQuad[i];
5535     }
5536   }
5537
5538   int BestHiQuad = -1;
5539   MaxQuad = 1;
5540   for (unsigned i = 0; i < 4; ++i) {
5541     if (HiQuad[i] > MaxQuad) {
5542       BestHiQuad = i;
5543       MaxQuad = HiQuad[i];
5544     }
5545   }
5546
5547   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5548   // of the two input vectors, shuffle them into one input vector so only a
5549   // single pshufb instruction is necessary. If There are more than 2 input
5550   // quads, disable the next transformation since it does not help SSSE3.
5551   bool V1Used = InputQuads[0] || InputQuads[1];
5552   bool V2Used = InputQuads[2] || InputQuads[3];
5553   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5554     if (InputQuads.count() == 2 && V1Used && V2Used) {
5555       BestLoQuad = InputQuads.find_first();
5556       BestHiQuad = InputQuads.find_next(BestLoQuad);
5557     }
5558     if (InputQuads.count() > 2) {
5559       BestLoQuad = -1;
5560       BestHiQuad = -1;
5561     }
5562   }
5563
5564   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5565   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5566   // words from all 4 input quadwords.
5567   SDValue NewV;
5568   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5569     SmallVector<int, 8> MaskV;
5570     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5571     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5572     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5573                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5574                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5575     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5576
5577     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5578     // source words for the shuffle, to aid later transformations.
5579     bool AllWordsInNewV = true;
5580     bool InOrder[2] = { true, true };
5581     for (unsigned i = 0; i != 8; ++i) {
5582       int idx = MaskVals[i];
5583       if (idx != (int)i)
5584         InOrder[i/4] = false;
5585       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5586         continue;
5587       AllWordsInNewV = false;
5588       break;
5589     }
5590
5591     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5592     if (AllWordsInNewV) {
5593       for (int i = 0; i != 8; ++i) {
5594         int idx = MaskVals[i];
5595         if (idx < 0)
5596           continue;
5597         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5598         if ((idx != i) && idx < 4)
5599           pshufhw = false;
5600         if ((idx != i) && idx > 3)
5601           pshuflw = false;
5602       }
5603       V1 = NewV;
5604       V2Used = false;
5605       BestLoQuad = 0;
5606       BestHiQuad = 1;
5607     }
5608
5609     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5610     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5611     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5612       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5613       unsigned TargetMask = 0;
5614       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5615                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5616       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5617                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5618       V1 = NewV.getOperand(0);
5619       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5620     }
5621   }
5622
5623   // If we have SSSE3, and all words of the result are from 1 input vector,
5624   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5625   // is present, fall back to case 4.
5626   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5627     SmallVector<SDValue,16> pshufbMask;
5628
5629     // If we have elements from both input vectors, set the high bit of the
5630     // shuffle mask element to zero out elements that come from V2 in the V1
5631     // mask, and elements that come from V1 in the V2 mask, so that the two
5632     // results can be OR'd together.
5633     bool TwoInputs = V1Used && V2Used;
5634     for (unsigned i = 0; i != 8; ++i) {
5635       int EltIdx = MaskVals[i] * 2;
5636       if (TwoInputs && (EltIdx >= 16)) {
5637         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5638         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5639         continue;
5640       }
5641       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5642       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5643     }
5644     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5645     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5646                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5647                                  MVT::v16i8, &pshufbMask[0], 16));
5648     if (!TwoInputs)
5649       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5650
5651     // Calculate the shuffle mask for the second input, shuffle it, and
5652     // OR it with the first shuffled input.
5653     pshufbMask.clear();
5654     for (unsigned i = 0; i != 8; ++i) {
5655       int EltIdx = MaskVals[i] * 2;
5656       if (EltIdx < 16) {
5657         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5658         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5659         continue;
5660       }
5661       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5662       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5663     }
5664     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5665     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5666                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5667                                  MVT::v16i8, &pshufbMask[0], 16));
5668     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5669     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5670   }
5671
5672   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5673   // and update MaskVals with new element order.
5674   BitVector InOrder(8);
5675   if (BestLoQuad >= 0) {
5676     SmallVector<int, 8> MaskV;
5677     for (int i = 0; i != 4; ++i) {
5678       int idx = MaskVals[i];
5679       if (idx < 0) {
5680         MaskV.push_back(-1);
5681         InOrder.set(i);
5682       } else if ((idx / 4) == BestLoQuad) {
5683         MaskV.push_back(idx & 3);
5684         InOrder.set(i);
5685       } else {
5686         MaskV.push_back(-1);
5687       }
5688     }
5689     for (unsigned i = 4; i != 8; ++i)
5690       MaskV.push_back(i);
5691     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5692                                 &MaskV[0]);
5693
5694     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5695         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5696       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5697                                NewV.getOperand(0),
5698                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5699                                DAG);
5700   }
5701
5702   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5703   // and update MaskVals with the new element order.
5704   if (BestHiQuad >= 0) {
5705     SmallVector<int, 8> MaskV;
5706     for (unsigned i = 0; i != 4; ++i)
5707       MaskV.push_back(i);
5708     for (unsigned i = 4; i != 8; ++i) {
5709       int idx = MaskVals[i];
5710       if (idx < 0) {
5711         MaskV.push_back(-1);
5712         InOrder.set(i);
5713       } else if ((idx / 4) == BestHiQuad) {
5714         MaskV.push_back((idx & 3) + 4);
5715         InOrder.set(i);
5716       } else {
5717         MaskV.push_back(-1);
5718       }
5719     }
5720     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5721                                 &MaskV[0]);
5722
5723     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5724         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5725       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5726                               NewV.getOperand(0),
5727                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5728                               DAG);
5729   }
5730
5731   // In case BestHi & BestLo were both -1, which means each quadword has a word
5732   // from each of the four input quadwords, calculate the InOrder bitvector now
5733   // before falling through to the insert/extract cleanup.
5734   if (BestLoQuad == -1 && BestHiQuad == -1) {
5735     NewV = V1;
5736     for (int i = 0; i != 8; ++i)
5737       if (MaskVals[i] < 0 || MaskVals[i] == i)
5738         InOrder.set(i);
5739   }
5740
5741   // The other elements are put in the right place using pextrw and pinsrw.
5742   for (unsigned i = 0; i != 8; ++i) {
5743     if (InOrder[i])
5744       continue;
5745     int EltIdx = MaskVals[i];
5746     if (EltIdx < 0)
5747       continue;
5748     SDValue ExtOp = (EltIdx < 8)
5749     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5750                   DAG.getIntPtrConstant(EltIdx))
5751     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5752                   DAG.getIntPtrConstant(EltIdx - 8));
5753     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5754                        DAG.getIntPtrConstant(i));
5755   }
5756   return NewV;
5757 }
5758
5759 // v16i8 shuffles - Prefer shuffles in the following order:
5760 // 1. [ssse3] 1 x pshufb
5761 // 2. [ssse3] 2 x pshufb + 1 x por
5762 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5763 static
5764 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5765                                  SelectionDAG &DAG,
5766                                  const X86TargetLowering &TLI) {
5767   SDValue V1 = SVOp->getOperand(0);
5768   SDValue V2 = SVOp->getOperand(1);
5769   DebugLoc dl = SVOp->getDebugLoc();
5770   SmallVector<int, 16> MaskVals;
5771   SVOp->getMask(MaskVals);
5772
5773   // If we have SSSE3, case 1 is generated when all result bytes come from
5774   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5775   // present, fall back to case 3.
5776   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5777   bool V1Only = true;
5778   bool V2Only = true;
5779   for (unsigned i = 0; i < 16; ++i) {
5780     int EltIdx = MaskVals[i];
5781     if (EltIdx < 0)
5782       continue;
5783     if (EltIdx < 16)
5784       V2Only = false;
5785     else
5786       V1Only = false;
5787   }
5788
5789   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5790   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5791     SmallVector<SDValue,16> pshufbMask;
5792
5793     // If all result elements are from one input vector, then only translate
5794     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5795     //
5796     // Otherwise, we have elements from both input vectors, and must zero out
5797     // elements that come from V2 in the first mask, and V1 in the second mask
5798     // so that we can OR them together.
5799     bool TwoInputs = !(V1Only || V2Only);
5800     for (unsigned i = 0; i != 16; ++i) {
5801       int EltIdx = MaskVals[i];
5802       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5803         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5804         continue;
5805       }
5806       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5807     }
5808     // If all the elements are from V2, assign it to V1 and return after
5809     // building the first pshufb.
5810     if (V2Only)
5811       V1 = V2;
5812     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5813                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5814                                  MVT::v16i8, &pshufbMask[0], 16));
5815     if (!TwoInputs)
5816       return V1;
5817
5818     // Calculate the shuffle mask for the second input, shuffle it, and
5819     // OR it with the first shuffled input.
5820     pshufbMask.clear();
5821     for (unsigned i = 0; i != 16; ++i) {
5822       int EltIdx = MaskVals[i];
5823       if (EltIdx < 16) {
5824         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5825         continue;
5826       }
5827       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5828     }
5829     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5830                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5831                                  MVT::v16i8, &pshufbMask[0], 16));
5832     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5833   }
5834
5835   // No SSSE3 - Calculate in place words and then fix all out of place words
5836   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5837   // the 16 different words that comprise the two doublequadword input vectors.
5838   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5839   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5840   SDValue NewV = V2Only ? V2 : V1;
5841   for (int i = 0; i != 8; ++i) {
5842     int Elt0 = MaskVals[i*2];
5843     int Elt1 = MaskVals[i*2+1];
5844
5845     // This word of the result is all undef, skip it.
5846     if (Elt0 < 0 && Elt1 < 0)
5847       continue;
5848
5849     // This word of the result is already in the correct place, skip it.
5850     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5851       continue;
5852     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5853       continue;
5854
5855     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5856     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5857     SDValue InsElt;
5858
5859     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5860     // using a single extract together, load it and store it.
5861     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5862       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5863                            DAG.getIntPtrConstant(Elt1 / 2));
5864       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5865                         DAG.getIntPtrConstant(i));
5866       continue;
5867     }
5868
5869     // If Elt1 is defined, extract it from the appropriate source.  If the
5870     // source byte is not also odd, shift the extracted word left 8 bits
5871     // otherwise clear the bottom 8 bits if we need to do an or.
5872     if (Elt1 >= 0) {
5873       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5874                            DAG.getIntPtrConstant(Elt1 / 2));
5875       if ((Elt1 & 1) == 0)
5876         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5877                              DAG.getConstant(8,
5878                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5879       else if (Elt0 >= 0)
5880         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5881                              DAG.getConstant(0xFF00, MVT::i16));
5882     }
5883     // If Elt0 is defined, extract it from the appropriate source.  If the
5884     // source byte is not also even, shift the extracted word right 8 bits. If
5885     // Elt1 was also defined, OR the extracted values together before
5886     // inserting them in the result.
5887     if (Elt0 >= 0) {
5888       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5889                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5890       if ((Elt0 & 1) != 0)
5891         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5892                               DAG.getConstant(8,
5893                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5894       else if (Elt1 >= 0)
5895         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5896                              DAG.getConstant(0x00FF, MVT::i16));
5897       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5898                          : InsElt0;
5899     }
5900     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5901                        DAG.getIntPtrConstant(i));
5902   }
5903   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5904 }
5905
5906 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5907 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5908 /// done when every pair / quad of shuffle mask elements point to elements in
5909 /// the right sequence. e.g.
5910 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5911 static
5912 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5913                                  SelectionDAG &DAG, DebugLoc dl) {
5914   EVT VT = SVOp->getValueType(0);
5915   SDValue V1 = SVOp->getOperand(0);
5916   SDValue V2 = SVOp->getOperand(1);
5917   unsigned NumElems = VT.getVectorNumElements();
5918   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5919   EVT NewVT;
5920   switch (VT.getSimpleVT().SimpleTy) {
5921   default: assert(false && "Unexpected!");
5922   case MVT::v4f32: NewVT = MVT::v2f64; break;
5923   case MVT::v4i32: NewVT = MVT::v2i64; break;
5924   case MVT::v8i16: NewVT = MVT::v4i32; break;
5925   case MVT::v16i8: NewVT = MVT::v4i32; break;
5926   }
5927
5928   int Scale = NumElems / NewWidth;
5929   SmallVector<int, 8> MaskVec;
5930   for (unsigned i = 0; i < NumElems; i += Scale) {
5931     int StartIdx = -1;
5932     for (int j = 0; j < Scale; ++j) {
5933       int EltIdx = SVOp->getMaskElt(i+j);
5934       if (EltIdx < 0)
5935         continue;
5936       if (StartIdx == -1)
5937         StartIdx = EltIdx - (EltIdx % Scale);
5938       if (EltIdx != StartIdx + j)
5939         return SDValue();
5940     }
5941     if (StartIdx == -1)
5942       MaskVec.push_back(-1);
5943     else
5944       MaskVec.push_back(StartIdx / Scale);
5945   }
5946
5947   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5948   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5949   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5950 }
5951
5952 /// getVZextMovL - Return a zero-extending vector move low node.
5953 ///
5954 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5955                             SDValue SrcOp, SelectionDAG &DAG,
5956                             const X86Subtarget *Subtarget, DebugLoc dl) {
5957   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5958     LoadSDNode *LD = NULL;
5959     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5960       LD = dyn_cast<LoadSDNode>(SrcOp);
5961     if (!LD) {
5962       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5963       // instead.
5964       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5965       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5966           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5967           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5968           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5969         // PR2108
5970         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5971         return DAG.getNode(ISD::BITCAST, dl, VT,
5972                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5973                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5974                                                    OpVT,
5975                                                    SrcOp.getOperand(0)
5976                                                           .getOperand(0))));
5977       }
5978     }
5979   }
5980
5981   return DAG.getNode(ISD::BITCAST, dl, VT,
5982                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5983                                  DAG.getNode(ISD::BITCAST, dl,
5984                                              OpVT, SrcOp)));
5985 }
5986
5987 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5988 /// shuffle node referes to only one lane in the sources.
5989 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5990   EVT VT = SVOp->getValueType(0);
5991   int NumElems = VT.getVectorNumElements();
5992   int HalfSize = NumElems/2;
5993   SmallVector<int, 16> M;
5994   SVOp->getMask(M);
5995   bool MatchA = false, MatchB = false;
5996
5997   for (int l = 0; l < NumElems*2; l += HalfSize) {
5998     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5999       MatchA = true;
6000       break;
6001     }
6002   }
6003
6004   for (int l = 0; l < NumElems*2; l += HalfSize) {
6005     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6006       MatchB = true;
6007       break;
6008     }
6009   }
6010
6011   return MatchA && MatchB;
6012 }
6013
6014 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6015 /// which could not be matched by any known target speficic shuffle
6016 static SDValue
6017 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6018   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6019     // If each half of a vector shuffle node referes to only one lane in the
6020     // source vectors, extract each used 128-bit lane and shuffle them using
6021     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6022     // the work to the legalizer.
6023     DebugLoc dl = SVOp->getDebugLoc();
6024     EVT VT = SVOp->getValueType(0);
6025     int NumElems = VT.getVectorNumElements();
6026     int HalfSize = NumElems/2;
6027
6028     // Extract the reference for each half
6029     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6030     int FstVecOpNum = 0, SndVecOpNum = 0;
6031     for (int i = 0; i < HalfSize; ++i) {
6032       int Elt = SVOp->getMaskElt(i);
6033       if (SVOp->getMaskElt(i) < 0)
6034         continue;
6035       FstVecOpNum = Elt/NumElems;
6036       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6037       break;
6038     }
6039     for (int i = HalfSize; i < NumElems; ++i) {
6040       int Elt = SVOp->getMaskElt(i);
6041       if (SVOp->getMaskElt(i) < 0)
6042         continue;
6043       SndVecOpNum = Elt/NumElems;
6044       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6045       break;
6046     }
6047
6048     // Extract the subvectors
6049     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6050                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6051     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6052                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6053
6054     // Generate 128-bit shuffles
6055     SmallVector<int, 16> MaskV1, MaskV2;
6056     for (int i = 0; i < HalfSize; ++i) {
6057       int Elt = SVOp->getMaskElt(i);
6058       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6059     }
6060     for (int i = HalfSize; i < NumElems; ++i) {
6061       int Elt = SVOp->getMaskElt(i);
6062       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6063     }
6064
6065     EVT NVT = V1.getValueType();
6066     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6067     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6068
6069     // Concatenate the result back
6070     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6071                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6072     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6073                               DAG, dl);
6074   }
6075
6076   return SDValue();
6077 }
6078
6079 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6080 /// 4 elements, and match them with several different shuffle types.
6081 static SDValue
6082 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6083   SDValue V1 = SVOp->getOperand(0);
6084   SDValue V2 = SVOp->getOperand(1);
6085   DebugLoc dl = SVOp->getDebugLoc();
6086   EVT VT = SVOp->getValueType(0);
6087
6088   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6089
6090   SmallVector<std::pair<int, int>, 8> Locs;
6091   Locs.resize(4);
6092   SmallVector<int, 8> Mask1(4U, -1);
6093   SmallVector<int, 8> PermMask;
6094   SVOp->getMask(PermMask);
6095
6096   unsigned NumHi = 0;
6097   unsigned NumLo = 0;
6098   for (unsigned i = 0; i != 4; ++i) {
6099     int Idx = PermMask[i];
6100     if (Idx < 0) {
6101       Locs[i] = std::make_pair(-1, -1);
6102     } else {
6103       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6104       if (Idx < 4) {
6105         Locs[i] = std::make_pair(0, NumLo);
6106         Mask1[NumLo] = Idx;
6107         NumLo++;
6108       } else {
6109         Locs[i] = std::make_pair(1, NumHi);
6110         if (2+NumHi < 4)
6111           Mask1[2+NumHi] = Idx;
6112         NumHi++;
6113       }
6114     }
6115   }
6116
6117   if (NumLo <= 2 && NumHi <= 2) {
6118     // If no more than two elements come from either vector. This can be
6119     // implemented with two shuffles. First shuffle gather the elements.
6120     // The second shuffle, which takes the first shuffle as both of its
6121     // vector operands, put the elements into the right order.
6122     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6123
6124     SmallVector<int, 8> Mask2(4U, -1);
6125
6126     for (unsigned i = 0; i != 4; ++i) {
6127       if (Locs[i].first == -1)
6128         continue;
6129       else {
6130         unsigned Idx = (i < 2) ? 0 : 4;
6131         Idx += Locs[i].first * 2 + Locs[i].second;
6132         Mask2[i] = Idx;
6133       }
6134     }
6135
6136     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6137   } else if (NumLo == 3 || NumHi == 3) {
6138     // Otherwise, we must have three elements from one vector, call it X, and
6139     // one element from the other, call it Y.  First, use a shufps to build an
6140     // intermediate vector with the one element from Y and the element from X
6141     // that will be in the same half in the final destination (the indexes don't
6142     // matter). Then, use a shufps to build the final vector, taking the half
6143     // containing the element from Y from the intermediate, and the other half
6144     // from X.
6145     if (NumHi == 3) {
6146       // Normalize it so the 3 elements come from V1.
6147       CommuteVectorShuffleMask(PermMask, VT);
6148       std::swap(V1, V2);
6149     }
6150
6151     // Find the element from V2.
6152     unsigned HiIndex;
6153     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6154       int Val = PermMask[HiIndex];
6155       if (Val < 0)
6156         continue;
6157       if (Val >= 4)
6158         break;
6159     }
6160
6161     Mask1[0] = PermMask[HiIndex];
6162     Mask1[1] = -1;
6163     Mask1[2] = PermMask[HiIndex^1];
6164     Mask1[3] = -1;
6165     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6166
6167     if (HiIndex >= 2) {
6168       Mask1[0] = PermMask[0];
6169       Mask1[1] = PermMask[1];
6170       Mask1[2] = HiIndex & 1 ? 6 : 4;
6171       Mask1[3] = HiIndex & 1 ? 4 : 6;
6172       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6173     } else {
6174       Mask1[0] = HiIndex & 1 ? 2 : 0;
6175       Mask1[1] = HiIndex & 1 ? 0 : 2;
6176       Mask1[2] = PermMask[2];
6177       Mask1[3] = PermMask[3];
6178       if (Mask1[2] >= 0)
6179         Mask1[2] += 4;
6180       if (Mask1[3] >= 0)
6181         Mask1[3] += 4;
6182       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6183     }
6184   }
6185
6186   // Break it into (shuffle shuffle_hi, shuffle_lo).
6187   Locs.clear();
6188   Locs.resize(4);
6189   SmallVector<int,8> LoMask(4U, -1);
6190   SmallVector<int,8> HiMask(4U, -1);
6191
6192   SmallVector<int,8> *MaskPtr = &LoMask;
6193   unsigned MaskIdx = 0;
6194   unsigned LoIdx = 0;
6195   unsigned HiIdx = 2;
6196   for (unsigned i = 0; i != 4; ++i) {
6197     if (i == 2) {
6198       MaskPtr = &HiMask;
6199       MaskIdx = 1;
6200       LoIdx = 0;
6201       HiIdx = 2;
6202     }
6203     int Idx = PermMask[i];
6204     if (Idx < 0) {
6205       Locs[i] = std::make_pair(-1, -1);
6206     } else if (Idx < 4) {
6207       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6208       (*MaskPtr)[LoIdx] = Idx;
6209       LoIdx++;
6210     } else {
6211       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6212       (*MaskPtr)[HiIdx] = Idx;
6213       HiIdx++;
6214     }
6215   }
6216
6217   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6218   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6219   SmallVector<int, 8> MaskOps;
6220   for (unsigned i = 0; i != 4; ++i) {
6221     if (Locs[i].first == -1) {
6222       MaskOps.push_back(-1);
6223     } else {
6224       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6225       MaskOps.push_back(Idx);
6226     }
6227   }
6228   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6229 }
6230
6231 static bool MayFoldVectorLoad(SDValue V) {
6232   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6233     V = V.getOperand(0);
6234   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6235     V = V.getOperand(0);
6236   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6237       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6238     // BUILD_VECTOR (load), undef
6239     V = V.getOperand(0);
6240   if (MayFoldLoad(V))
6241     return true;
6242   return false;
6243 }
6244
6245 // FIXME: the version above should always be used. Since there's
6246 // a bug where several vector shuffles can't be folded because the
6247 // DAG is not updated during lowering and a node claims to have two
6248 // uses while it only has one, use this version, and let isel match
6249 // another instruction if the load really happens to have more than
6250 // one use. Remove this version after this bug get fixed.
6251 // rdar://8434668, PR8156
6252 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6253   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6254     V = V.getOperand(0);
6255   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6256     V = V.getOperand(0);
6257   if (ISD::isNormalLoad(V.getNode()))
6258     return true;
6259   return false;
6260 }
6261
6262 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6263 /// a vector extract, and if both can be later optimized into a single load.
6264 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6265 /// here because otherwise a target specific shuffle node is going to be
6266 /// emitted for this shuffle, and the optimization not done.
6267 /// FIXME: This is probably not the best approach, but fix the problem
6268 /// until the right path is decided.
6269 static
6270 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6271                                          const TargetLowering &TLI) {
6272   EVT VT = V.getValueType();
6273   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6274
6275   // Be sure that the vector shuffle is present in a pattern like this:
6276   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6277   if (!V.hasOneUse())
6278     return false;
6279
6280   SDNode *N = *V.getNode()->use_begin();
6281   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6282     return false;
6283
6284   SDValue EltNo = N->getOperand(1);
6285   if (!isa<ConstantSDNode>(EltNo))
6286     return false;
6287
6288   // If the bit convert changed the number of elements, it is unsafe
6289   // to examine the mask.
6290   bool HasShuffleIntoBitcast = false;
6291   if (V.getOpcode() == ISD::BITCAST) {
6292     EVT SrcVT = V.getOperand(0).getValueType();
6293     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6294       return false;
6295     V = V.getOperand(0);
6296     HasShuffleIntoBitcast = true;
6297   }
6298
6299   // Select the input vector, guarding against out of range extract vector.
6300   unsigned NumElems = VT.getVectorNumElements();
6301   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6302   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6303   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6304
6305   // Skip one more bit_convert if necessary
6306   if (V.getOpcode() == ISD::BITCAST)
6307     V = V.getOperand(0);
6308
6309   if (ISD::isNormalLoad(V.getNode())) {
6310     // Is the original load suitable?
6311     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6312
6313     // FIXME: avoid the multi-use bug that is preventing lots of
6314     // of foldings to be detected, this is still wrong of course, but
6315     // give the temporary desired behavior, and if it happens that
6316     // the load has real more uses, during isel it will not fold, and
6317     // will generate poor code.
6318     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6319       return false;
6320
6321     if (!HasShuffleIntoBitcast)
6322       return true;
6323
6324     // If there's a bitcast before the shuffle, check if the load type and
6325     // alignment is valid.
6326     unsigned Align = LN0->getAlignment();
6327     unsigned NewAlign =
6328       TLI.getTargetData()->getABITypeAlignment(
6329                                     VT.getTypeForEVT(*DAG.getContext()));
6330
6331     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6332       return false;
6333   }
6334
6335   return true;
6336 }
6337
6338 static
6339 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6340   EVT VT = Op.getValueType();
6341
6342   // Canonizalize to v2f64.
6343   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6344   return DAG.getNode(ISD::BITCAST, dl, VT,
6345                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6346                                           V1, DAG));
6347 }
6348
6349 static
6350 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6351                         bool HasXMMInt) {
6352   SDValue V1 = Op.getOperand(0);
6353   SDValue V2 = Op.getOperand(1);
6354   EVT VT = Op.getValueType();
6355
6356   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6357
6358   if (HasXMMInt && VT == MVT::v2f64)
6359     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6360
6361   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6362   return DAG.getNode(ISD::BITCAST, dl, VT,
6363                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6364                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6365                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6366 }
6367
6368 static
6369 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6370   SDValue V1 = Op.getOperand(0);
6371   SDValue V2 = Op.getOperand(1);
6372   EVT VT = Op.getValueType();
6373
6374   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6375          "unsupported shuffle type");
6376
6377   if (V2.getOpcode() == ISD::UNDEF)
6378     V2 = V1;
6379
6380   // v4i32 or v4f32
6381   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6382 }
6383
6384 static inline unsigned getSHUFPOpcode(EVT VT) {
6385   switch(VT.getSimpleVT().SimpleTy) {
6386   case MVT::v8i32: // Use fp unit for int unpack.
6387   case MVT::v8f32:
6388   case MVT::v4i32: // Use fp unit for int unpack.
6389   case MVT::v4f32: return X86ISD::SHUFPS;
6390   case MVT::v4i64: // Use fp unit for int unpack.
6391   case MVT::v4f64:
6392   case MVT::v2i64: // Use fp unit for int unpack.
6393   case MVT::v2f64: return X86ISD::SHUFPD;
6394   default:
6395     llvm_unreachable("Unknown type for shufp*");
6396   }
6397   return 0;
6398 }
6399
6400 static
6401 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6402   SDValue V1 = Op.getOperand(0);
6403   SDValue V2 = Op.getOperand(1);
6404   EVT VT = Op.getValueType();
6405   unsigned NumElems = VT.getVectorNumElements();
6406
6407   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6408   // operand of these instructions is only memory, so check if there's a
6409   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6410   // same masks.
6411   bool CanFoldLoad = false;
6412
6413   // Trivial case, when V2 comes from a load.
6414   if (MayFoldVectorLoad(V2))
6415     CanFoldLoad = true;
6416
6417   // When V1 is a load, it can be folded later into a store in isel, example:
6418   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6419   //    turns into:
6420   //  (MOVLPSmr addr:$src1, VR128:$src2)
6421   // So, recognize this potential and also use MOVLPS or MOVLPD
6422   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6423     CanFoldLoad = true;
6424
6425   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6426   if (CanFoldLoad) {
6427     if (HasXMMInt && NumElems == 2)
6428       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6429
6430     if (NumElems == 4)
6431       // If we don't care about the second element, procede to use movss.
6432       if (SVOp->getMaskElt(1) != -1)
6433         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6434   }
6435
6436   // movl and movlp will both match v2i64, but v2i64 is never matched by
6437   // movl earlier because we make it strict to avoid messing with the movlp load
6438   // folding logic (see the code above getMOVLP call). Match it here then,
6439   // this is horrible, but will stay like this until we move all shuffle
6440   // matching to x86 specific nodes. Note that for the 1st condition all
6441   // types are matched with movsd.
6442   if (HasXMMInt) {
6443     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6444     // as to remove this logic from here, as much as possible
6445     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6446       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6447     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6448   }
6449
6450   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6451
6452   // Invert the operand order and use SHUFPS to match it.
6453   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6454                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6455 }
6456
6457 static inline unsigned getUNPCKLOpcode(EVT VT) {
6458   switch(VT.getSimpleVT().SimpleTy) {
6459   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6460   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6461   case MVT::v4f32: return X86ISD::UNPCKLPS;
6462   case MVT::v2f64: return X86ISD::UNPCKLPD;
6463   case MVT::v8i32: // Use fp unit for int unpack.
6464   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6465   case MVT::v4i64: // Use fp unit for int unpack.
6466   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6467   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6468   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6469   default:
6470     llvm_unreachable("Unknown type for unpckl");
6471   }
6472   return 0;
6473 }
6474
6475 static inline unsigned getUNPCKHOpcode(EVT VT) {
6476   switch(VT.getSimpleVT().SimpleTy) {
6477   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6478   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6479   case MVT::v4f32: return X86ISD::UNPCKHPS;
6480   case MVT::v2f64: return X86ISD::UNPCKHPD;
6481   case MVT::v8i32: // Use fp unit for int unpack.
6482   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6483   case MVT::v4i64: // Use fp unit for int unpack.
6484   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6485   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6486   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6487   default:
6488     llvm_unreachable("Unknown type for unpckh");
6489   }
6490   return 0;
6491 }
6492
6493 static inline unsigned getVPERMILOpcode(EVT VT) {
6494   switch(VT.getSimpleVT().SimpleTy) {
6495   case MVT::v4i32:
6496   case MVT::v4f32: return X86ISD::VPERMILPS;
6497   case MVT::v2i64:
6498   case MVT::v2f64: return X86ISD::VPERMILPD;
6499   case MVT::v8i32:
6500   case MVT::v8f32: return X86ISD::VPERMILPSY;
6501   case MVT::v4i64:
6502   case MVT::v4f64: return X86ISD::VPERMILPDY;
6503   default:
6504     llvm_unreachable("Unknown type for vpermil");
6505   }
6506   return 0;
6507 }
6508
6509 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6510 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6511 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6512 static bool isVectorBroadcast(SDValue &Op) {
6513   EVT VT = Op.getValueType();
6514   bool Is256 = VT.getSizeInBits() == 256;
6515
6516   assert((VT.getSizeInBits() == 128 || Is256) &&
6517          "Unsupported type for vbroadcast node");
6518
6519   SDValue V = Op;
6520   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6521     V = V.getOperand(0);
6522
6523   if (Is256 && !(V.hasOneUse() &&
6524                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6525                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6526     return false;
6527
6528   if (Is256)
6529     V = V.getOperand(1);
6530
6531   if (!V.hasOneUse())
6532     return false;
6533
6534   // Check the source scalar_to_vector type. 256-bit broadcasts are
6535   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6536   // for 32-bit scalars.
6537   if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6538     return false;
6539
6540   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6541   if (ScalarSize != 32 && ScalarSize != 64)
6542     return false;
6543   if (!Is256 && ScalarSize == 64)
6544     return false;
6545
6546   V = V.getOperand(0);
6547   if (!MayFoldLoad(V))
6548     return false;
6549
6550   // Return the load node
6551   Op = V;
6552   return true;
6553 }
6554
6555 static
6556 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6557                                const TargetLowering &TLI,
6558                                const X86Subtarget *Subtarget) {
6559   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6560   EVT VT = Op.getValueType();
6561   DebugLoc dl = Op.getDebugLoc();
6562   SDValue V1 = Op.getOperand(0);
6563   SDValue V2 = Op.getOperand(1);
6564
6565   if (isZeroShuffle(SVOp))
6566     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6567
6568   // Handle splat operations
6569   if (SVOp->isSplat()) {
6570     unsigned NumElem = VT.getVectorNumElements();
6571     int Size = VT.getSizeInBits();
6572     // Special case, this is the only place now where it's allowed to return
6573     // a vector_shuffle operation without using a target specific node, because
6574     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6575     // this be moved to DAGCombine instead?
6576     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6577       return Op;
6578
6579     // Use vbroadcast whenever the splat comes from a foldable load
6580     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6581       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6582
6583     // Handle splats by matching through known shuffle masks
6584     if ((Size == 128 && NumElem <= 4) ||
6585         (Size == 256 && NumElem < 8))
6586       return SDValue();
6587
6588     // All remaning splats are promoted to target supported vector shuffles.
6589     return PromoteSplat(SVOp, DAG);
6590   }
6591
6592   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6593   // do it!
6594   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6595     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6596     if (NewOp.getNode())
6597       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6598   } else if ((VT == MVT::v4i32 ||
6599              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6600     // FIXME: Figure out a cleaner way to do this.
6601     // Try to make use of movq to zero out the top part.
6602     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6603       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6604       if (NewOp.getNode()) {
6605         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6606           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6607                               DAG, Subtarget, dl);
6608       }
6609     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6610       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6611       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6612         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6613                             DAG, Subtarget, dl);
6614     }
6615   }
6616   return SDValue();
6617 }
6618
6619 SDValue
6620 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6621   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6622   SDValue V1 = Op.getOperand(0);
6623   SDValue V2 = Op.getOperand(1);
6624   EVT VT = Op.getValueType();
6625   DebugLoc dl = Op.getDebugLoc();
6626   unsigned NumElems = VT.getVectorNumElements();
6627   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6628   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6629   bool V1IsSplat = false;
6630   bool V2IsSplat = false;
6631   bool HasXMMInt = Subtarget->hasXMMInt();
6632   MachineFunction &MF = DAG.getMachineFunction();
6633   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6634
6635   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6636
6637   // Vector shuffle lowering takes 3 steps:
6638   //
6639   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6640   //    narrowing and commutation of operands should be handled.
6641   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6642   //    shuffle nodes.
6643   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6644   //    so the shuffle can be broken into other shuffles and the legalizer can
6645   //    try the lowering again.
6646   //
6647   // The general idea is that no vector_shuffle operation should be left to
6648   // be matched during isel, all of them must be converted to a target specific
6649   // node here.
6650
6651   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6652   // narrowing and commutation of operands should be handled. The actual code
6653   // doesn't include all of those, work in progress...
6654   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6655   if (NewOp.getNode())
6656     return NewOp;
6657
6658   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6659   // unpckh_undef). Only use pshufd if speed is more important than size.
6660   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6661     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6662   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6663     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6664
6665   if (X86::isMOVDDUPMask(SVOp) &&
6666       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6667       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6668     return getMOVDDup(Op, dl, V1, DAG);
6669
6670   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6671     return getMOVHighToLow(Op, dl, DAG);
6672
6673   // Use to match splats
6674   if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6675       (VT == MVT::v2f64 || VT == MVT::v2i64))
6676     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6677
6678   if (X86::isPSHUFDMask(SVOp)) {
6679     // The actual implementation will match the mask in the if above and then
6680     // during isel it can match several different instructions, not only pshufd
6681     // as its name says, sad but true, emulate the behavior for now...
6682     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6683         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6684
6685     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6686
6687     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6688       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6689
6690     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6691                                 TargetMask, DAG);
6692   }
6693
6694   // Check if this can be converted into a logical shift.
6695   bool isLeft = false;
6696   unsigned ShAmt = 0;
6697   SDValue ShVal;
6698   bool isShift = getSubtarget()->hasXMMInt() &&
6699                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6700   if (isShift && ShVal.hasOneUse()) {
6701     // If the shifted value has multiple uses, it may be cheaper to use
6702     // v_set0 + movlhps or movhlps, etc.
6703     EVT EltVT = VT.getVectorElementType();
6704     ShAmt *= EltVT.getSizeInBits();
6705     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6706   }
6707
6708   if (X86::isMOVLMask(SVOp)) {
6709     if (V1IsUndef)
6710       return V2;
6711     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6712       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6713     if (!X86::isMOVLPMask(SVOp)) {
6714       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6715         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6716
6717       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6718         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6719     }
6720   }
6721
6722   // FIXME: fold these into legal mask.
6723   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6724     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6725
6726   if (X86::isMOVHLPSMask(SVOp))
6727     return getMOVHighToLow(Op, dl, DAG);
6728
6729   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6730     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6731
6732   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6733     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6734
6735   if (X86::isMOVLPMask(SVOp))
6736     return getMOVLP(Op, dl, DAG, HasXMMInt);
6737
6738   if (ShouldXformToMOVHLPS(SVOp) ||
6739       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6740     return CommuteVectorShuffle(SVOp, DAG);
6741
6742   if (isShift) {
6743     // No better options. Use a vshl / vsrl.
6744     EVT EltVT = VT.getVectorElementType();
6745     ShAmt *= EltVT.getSizeInBits();
6746     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6747   }
6748
6749   bool Commuted = false;
6750   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6751   // 1,1,1,1 -> v8i16 though.
6752   V1IsSplat = isSplatVector(V1.getNode());
6753   V2IsSplat = isSplatVector(V2.getNode());
6754
6755   // Canonicalize the splat or undef, if present, to be on the RHS.
6756   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6757     Op = CommuteVectorShuffle(SVOp, DAG);
6758     SVOp = cast<ShuffleVectorSDNode>(Op);
6759     V1 = SVOp->getOperand(0);
6760     V2 = SVOp->getOperand(1);
6761     std::swap(V1IsSplat, V2IsSplat);
6762     std::swap(V1IsUndef, V2IsUndef);
6763     Commuted = true;
6764   }
6765
6766   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6767     // Shuffling low element of v1 into undef, just return v1.
6768     if (V2IsUndef)
6769       return V1;
6770     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6771     // the instruction selector will not match, so get a canonical MOVL with
6772     // swapped operands to undo the commute.
6773     return getMOVL(DAG, dl, VT, V2, V1);
6774   }
6775
6776   if (X86::isUNPCKLMask(SVOp))
6777     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6778
6779   if (X86::isUNPCKHMask(SVOp))
6780     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6781
6782   if (V2IsSplat) {
6783     // Normalize mask so all entries that point to V2 points to its first
6784     // element then try to match unpck{h|l} again. If match, return a
6785     // new vector_shuffle with the corrected mask.
6786     SDValue NewMask = NormalizeMask(SVOp, DAG);
6787     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6788     if (NSVOp != SVOp) {
6789       if (X86::isUNPCKLMask(NSVOp, true)) {
6790         return NewMask;
6791       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6792         return NewMask;
6793       }
6794     }
6795   }
6796
6797   if (Commuted) {
6798     // Commute is back and try unpck* again.
6799     // FIXME: this seems wrong.
6800     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6801     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6802
6803     if (X86::isUNPCKLMask(NewSVOp))
6804       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6805
6806     if (X86::isUNPCKHMask(NewSVOp))
6807       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6808   }
6809
6810   // Normalize the node to match x86 shuffle ops if needed
6811   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6812     return CommuteVectorShuffle(SVOp, DAG);
6813
6814   // The checks below are all present in isShuffleMaskLegal, but they are
6815   // inlined here right now to enable us to directly emit target specific
6816   // nodes, and remove one by one until they don't return Op anymore.
6817   SmallVector<int, 16> M;
6818   SVOp->getMask(M);
6819
6820   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6821     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6822                                 X86::getShufflePALIGNRImmediate(SVOp),
6823                                 DAG);
6824
6825   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6826       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6827     if (VT == MVT::v2f64)
6828       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6829     if (VT == MVT::v2i64)
6830       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6831   }
6832
6833   if (isPSHUFHWMask(M, VT))
6834     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6835                                 X86::getShufflePSHUFHWImmediate(SVOp),
6836                                 DAG);
6837
6838   if (isPSHUFLWMask(M, VT))
6839     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6840                                 X86::getShufflePSHUFLWImmediate(SVOp),
6841                                 DAG);
6842
6843   if (isSHUFPMask(M, VT))
6844     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6845                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6846
6847   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6848     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6849   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6850     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6851
6852   //===--------------------------------------------------------------------===//
6853   // Generate target specific nodes for 128 or 256-bit shuffles only
6854   // supported in the AVX instruction set.
6855   //
6856
6857   // Handle VMOVDDUPY permutations
6858   if (isMOVDDUPYMask(SVOp, Subtarget))
6859     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6860
6861   // Handle VPERMILPS* permutations
6862   if (isVPERMILPSMask(M, VT, Subtarget))
6863     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6864                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6865
6866   // Handle VPERMILPD* permutations
6867   if (isVPERMILPDMask(M, VT, Subtarget))
6868     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6869                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6870
6871   // Handle VPERM2F128 permutations
6872   if (isVPERM2F128Mask(M, VT, Subtarget))
6873     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6874                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6875
6876   // Handle VSHUFPSY permutations
6877   if (isVSHUFPSYMask(M, VT, Subtarget))
6878     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6879                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6880
6881   // Handle VSHUFPDY permutations
6882   if (isVSHUFPDYMask(M, VT, Subtarget))
6883     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6884                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6885
6886   //===--------------------------------------------------------------------===//
6887   // Since no target specific shuffle was selected for this generic one,
6888   // lower it into other known shuffles. FIXME: this isn't true yet, but
6889   // this is the plan.
6890   //
6891
6892   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6893   if (VT == MVT::v8i16) {
6894     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6895     if (NewOp.getNode())
6896       return NewOp;
6897   }
6898
6899   if (VT == MVT::v16i8) {
6900     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6901     if (NewOp.getNode())
6902       return NewOp;
6903   }
6904
6905   // Handle all 128-bit wide vectors with 4 elements, and match them with
6906   // several different shuffle types.
6907   if (NumElems == 4 && VT.getSizeInBits() == 128)
6908     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6909
6910   // Handle general 256-bit shuffles
6911   if (VT.is256BitVector())
6912     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6913
6914   return SDValue();
6915 }
6916
6917 SDValue
6918 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6919                                                 SelectionDAG &DAG) const {
6920   EVT VT = Op.getValueType();
6921   DebugLoc dl = Op.getDebugLoc();
6922
6923   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6924     return SDValue();
6925
6926   if (VT.getSizeInBits() == 8) {
6927     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6928                                     Op.getOperand(0), Op.getOperand(1));
6929     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6930                                     DAG.getValueType(VT));
6931     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6932   } else if (VT.getSizeInBits() == 16) {
6933     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6934     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6935     if (Idx == 0)
6936       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6937                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6938                                      DAG.getNode(ISD::BITCAST, dl,
6939                                                  MVT::v4i32,
6940                                                  Op.getOperand(0)),
6941                                      Op.getOperand(1)));
6942     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6943                                     Op.getOperand(0), Op.getOperand(1));
6944     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6945                                     DAG.getValueType(VT));
6946     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6947   } else if (VT == MVT::f32) {
6948     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6949     // the result back to FR32 register. It's only worth matching if the
6950     // result has a single use which is a store or a bitcast to i32.  And in
6951     // the case of a store, it's not worth it if the index is a constant 0,
6952     // because a MOVSSmr can be used instead, which is smaller and faster.
6953     if (!Op.hasOneUse())
6954       return SDValue();
6955     SDNode *User = *Op.getNode()->use_begin();
6956     if ((User->getOpcode() != ISD::STORE ||
6957          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6958           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6959         (User->getOpcode() != ISD::BITCAST ||
6960          User->getValueType(0) != MVT::i32))
6961       return SDValue();
6962     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6963                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6964                                               Op.getOperand(0)),
6965                                               Op.getOperand(1));
6966     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6967   } else if (VT == MVT::i32 || VT == MVT::i64) {
6968     // ExtractPS/pextrq works with constant index.
6969     if (isa<ConstantSDNode>(Op.getOperand(1)))
6970       return Op;
6971   }
6972   return SDValue();
6973 }
6974
6975
6976 SDValue
6977 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6978                                            SelectionDAG &DAG) const {
6979   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6980     return SDValue();
6981
6982   SDValue Vec = Op.getOperand(0);
6983   EVT VecVT = Vec.getValueType();
6984
6985   // If this is a 256-bit vector result, first extract the 128-bit vector and
6986   // then extract the element from the 128-bit vector.
6987   if (VecVT.getSizeInBits() == 256) {
6988     DebugLoc dl = Op.getNode()->getDebugLoc();
6989     unsigned NumElems = VecVT.getVectorNumElements();
6990     SDValue Idx = Op.getOperand(1);
6991     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6992
6993     // Get the 128-bit vector.
6994     bool Upper = IdxVal >= NumElems/2;
6995     Vec = Extract128BitVector(Vec,
6996                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6997
6998     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6999                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7000   }
7001
7002   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7003
7004   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
7005     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7006     if (Res.getNode())
7007       return Res;
7008   }
7009
7010   EVT VT = Op.getValueType();
7011   DebugLoc dl = Op.getDebugLoc();
7012   // TODO: handle v16i8.
7013   if (VT.getSizeInBits() == 16) {
7014     SDValue Vec = Op.getOperand(0);
7015     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7016     if (Idx == 0)
7017       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7018                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7019                                      DAG.getNode(ISD::BITCAST, dl,
7020                                                  MVT::v4i32, Vec),
7021                                      Op.getOperand(1)));
7022     // Transform it so it match pextrw which produces a 32-bit result.
7023     EVT EltVT = MVT::i32;
7024     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7025                                     Op.getOperand(0), Op.getOperand(1));
7026     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7027                                     DAG.getValueType(VT));
7028     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7029   } else if (VT.getSizeInBits() == 32) {
7030     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7031     if (Idx == 0)
7032       return Op;
7033
7034     // SHUFPS the element to the lowest double word, then movss.
7035     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7036     EVT VVT = Op.getOperand(0).getValueType();
7037     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7038                                        DAG.getUNDEF(VVT), Mask);
7039     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7040                        DAG.getIntPtrConstant(0));
7041   } else if (VT.getSizeInBits() == 64) {
7042     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7043     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7044     //        to match extract_elt for f64.
7045     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7046     if (Idx == 0)
7047       return Op;
7048
7049     // UNPCKHPD the element to the lowest double word, then movsd.
7050     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7051     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7052     int Mask[2] = { 1, -1 };
7053     EVT VVT = Op.getOperand(0).getValueType();
7054     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7055                                        DAG.getUNDEF(VVT), Mask);
7056     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7057                        DAG.getIntPtrConstant(0));
7058   }
7059
7060   return SDValue();
7061 }
7062
7063 SDValue
7064 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7065                                                SelectionDAG &DAG) const {
7066   EVT VT = Op.getValueType();
7067   EVT EltVT = VT.getVectorElementType();
7068   DebugLoc dl = Op.getDebugLoc();
7069
7070   SDValue N0 = Op.getOperand(0);
7071   SDValue N1 = Op.getOperand(1);
7072   SDValue N2 = Op.getOperand(2);
7073
7074   if (VT.getSizeInBits() == 256)
7075     return SDValue();
7076
7077   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7078       isa<ConstantSDNode>(N2)) {
7079     unsigned Opc;
7080     if (VT == MVT::v8i16)
7081       Opc = X86ISD::PINSRW;
7082     else if (VT == MVT::v16i8)
7083       Opc = X86ISD::PINSRB;
7084     else
7085       Opc = X86ISD::PINSRB;
7086
7087     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7088     // argument.
7089     if (N1.getValueType() != MVT::i32)
7090       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7091     if (N2.getValueType() != MVT::i32)
7092       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7093     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7094   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7095     // Bits [7:6] of the constant are the source select.  This will always be
7096     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7097     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7098     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7099     // Bits [5:4] of the constant are the destination select.  This is the
7100     //  value of the incoming immediate.
7101     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7102     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7103     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7104     // Create this as a scalar to vector..
7105     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7106     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7107   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
7108              isa<ConstantSDNode>(N2)) {
7109     // PINSR* works with constant index.
7110     return Op;
7111   }
7112   return SDValue();
7113 }
7114
7115 SDValue
7116 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7117   EVT VT = Op.getValueType();
7118   EVT EltVT = VT.getVectorElementType();
7119
7120   DebugLoc dl = Op.getDebugLoc();
7121   SDValue N0 = Op.getOperand(0);
7122   SDValue N1 = Op.getOperand(1);
7123   SDValue N2 = Op.getOperand(2);
7124
7125   // If this is a 256-bit vector result, first extract the 128-bit vector,
7126   // insert the element into the extracted half and then place it back.
7127   if (VT.getSizeInBits() == 256) {
7128     if (!isa<ConstantSDNode>(N2))
7129       return SDValue();
7130
7131     // Get the desired 128-bit vector half.
7132     unsigned NumElems = VT.getVectorNumElements();
7133     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7134     bool Upper = IdxVal >= NumElems/2;
7135     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7136     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7137
7138     // Insert the element into the desired half.
7139     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7140                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7141
7142     // Insert the changed part back to the 256-bit vector
7143     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7144   }
7145
7146   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7147     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7148
7149   if (EltVT == MVT::i8)
7150     return SDValue();
7151
7152   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7153     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7154     // as its second argument.
7155     if (N1.getValueType() != MVT::i32)
7156       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7157     if (N2.getValueType() != MVT::i32)
7158       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7159     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7160   }
7161   return SDValue();
7162 }
7163
7164 SDValue
7165 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7166   LLVMContext *Context = DAG.getContext();
7167   DebugLoc dl = Op.getDebugLoc();
7168   EVT OpVT = Op.getValueType();
7169
7170   // If this is a 256-bit vector result, first insert into a 128-bit
7171   // vector and then insert into the 256-bit vector.
7172   if (OpVT.getSizeInBits() > 128) {
7173     // Insert into a 128-bit vector.
7174     EVT VT128 = EVT::getVectorVT(*Context,
7175                                  OpVT.getVectorElementType(),
7176                                  OpVT.getVectorNumElements() / 2);
7177
7178     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7179
7180     // Insert the 128-bit vector.
7181     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7182                               DAG.getConstant(0, MVT::i32),
7183                               DAG, dl);
7184   }
7185
7186   if (Op.getValueType() == MVT::v1i64 &&
7187       Op.getOperand(0).getValueType() == MVT::i64)
7188     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7189
7190   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7191   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7192          "Expected an SSE type!");
7193   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7194                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7195 }
7196
7197 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7198 // a simple subregister reference or explicit instructions to grab
7199 // upper bits of a vector.
7200 SDValue
7201 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7202   if (Subtarget->hasAVX()) {
7203     DebugLoc dl = Op.getNode()->getDebugLoc();
7204     SDValue Vec = Op.getNode()->getOperand(0);
7205     SDValue Idx = Op.getNode()->getOperand(1);
7206
7207     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7208         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7209         return Extract128BitVector(Vec, Idx, DAG, dl);
7210     }
7211   }
7212   return SDValue();
7213 }
7214
7215 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7216 // simple superregister reference or explicit instructions to insert
7217 // the upper bits of a vector.
7218 SDValue
7219 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7220   if (Subtarget->hasAVX()) {
7221     DebugLoc dl = Op.getNode()->getDebugLoc();
7222     SDValue Vec = Op.getNode()->getOperand(0);
7223     SDValue SubVec = Op.getNode()->getOperand(1);
7224     SDValue Idx = Op.getNode()->getOperand(2);
7225
7226     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7227         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7228       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7229     }
7230   }
7231   return SDValue();
7232 }
7233
7234 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7235 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7236 // one of the above mentioned nodes. It has to be wrapped because otherwise
7237 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7238 // be used to form addressing mode. These wrapped nodes will be selected
7239 // into MOV32ri.
7240 SDValue
7241 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7242   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7243
7244   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7245   // global base reg.
7246   unsigned char OpFlag = 0;
7247   unsigned WrapperKind = X86ISD::Wrapper;
7248   CodeModel::Model M = getTargetMachine().getCodeModel();
7249
7250   if (Subtarget->isPICStyleRIPRel() &&
7251       (M == CodeModel::Small || M == CodeModel::Kernel))
7252     WrapperKind = X86ISD::WrapperRIP;
7253   else if (Subtarget->isPICStyleGOT())
7254     OpFlag = X86II::MO_GOTOFF;
7255   else if (Subtarget->isPICStyleStubPIC())
7256     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7257
7258   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7259                                              CP->getAlignment(),
7260                                              CP->getOffset(), OpFlag);
7261   DebugLoc DL = CP->getDebugLoc();
7262   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7263   // With PIC, the address is actually $g + Offset.
7264   if (OpFlag) {
7265     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7266                          DAG.getNode(X86ISD::GlobalBaseReg,
7267                                      DebugLoc(), getPointerTy()),
7268                          Result);
7269   }
7270
7271   return Result;
7272 }
7273
7274 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7275   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7276
7277   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7278   // global base reg.
7279   unsigned char OpFlag = 0;
7280   unsigned WrapperKind = X86ISD::Wrapper;
7281   CodeModel::Model M = getTargetMachine().getCodeModel();
7282
7283   if (Subtarget->isPICStyleRIPRel() &&
7284       (M == CodeModel::Small || M == CodeModel::Kernel))
7285     WrapperKind = X86ISD::WrapperRIP;
7286   else if (Subtarget->isPICStyleGOT())
7287     OpFlag = X86II::MO_GOTOFF;
7288   else if (Subtarget->isPICStyleStubPIC())
7289     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7290
7291   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7292                                           OpFlag);
7293   DebugLoc DL = JT->getDebugLoc();
7294   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7295
7296   // With PIC, the address is actually $g + Offset.
7297   if (OpFlag)
7298     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7299                          DAG.getNode(X86ISD::GlobalBaseReg,
7300                                      DebugLoc(), getPointerTy()),
7301                          Result);
7302
7303   return Result;
7304 }
7305
7306 SDValue
7307 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7308   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7309
7310   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7311   // global base reg.
7312   unsigned char OpFlag = 0;
7313   unsigned WrapperKind = X86ISD::Wrapper;
7314   CodeModel::Model M = getTargetMachine().getCodeModel();
7315
7316   if (Subtarget->isPICStyleRIPRel() &&
7317       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7318     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7319       OpFlag = X86II::MO_GOTPCREL;
7320     WrapperKind = X86ISD::WrapperRIP;
7321   } else if (Subtarget->isPICStyleGOT()) {
7322     OpFlag = X86II::MO_GOT;
7323   } else if (Subtarget->isPICStyleStubPIC()) {
7324     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7325   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7326     OpFlag = X86II::MO_DARWIN_NONLAZY;
7327   }
7328
7329   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7330
7331   DebugLoc DL = Op.getDebugLoc();
7332   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7333
7334
7335   // With PIC, the address is actually $g + Offset.
7336   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7337       !Subtarget->is64Bit()) {
7338     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7339                          DAG.getNode(X86ISD::GlobalBaseReg,
7340                                      DebugLoc(), getPointerTy()),
7341                          Result);
7342   }
7343
7344   // For symbols that require a load from a stub to get the address, emit the
7345   // load.
7346   if (isGlobalStubReference(OpFlag))
7347     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7348                          MachinePointerInfo::getGOT(), false, false, false, 0);
7349
7350   return Result;
7351 }
7352
7353 SDValue
7354 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7355   // Create the TargetBlockAddressAddress node.
7356   unsigned char OpFlags =
7357     Subtarget->ClassifyBlockAddressReference();
7358   CodeModel::Model M = getTargetMachine().getCodeModel();
7359   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7360   DebugLoc dl = Op.getDebugLoc();
7361   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7362                                        /*isTarget=*/true, OpFlags);
7363
7364   if (Subtarget->isPICStyleRIPRel() &&
7365       (M == CodeModel::Small || M == CodeModel::Kernel))
7366     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7367   else
7368     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7369
7370   // With PIC, the address is actually $g + Offset.
7371   if (isGlobalRelativeToPICBase(OpFlags)) {
7372     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7373                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7374                          Result);
7375   }
7376
7377   return Result;
7378 }
7379
7380 SDValue
7381 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7382                                       int64_t Offset,
7383                                       SelectionDAG &DAG) const {
7384   // Create the TargetGlobalAddress node, folding in the constant
7385   // offset if it is legal.
7386   unsigned char OpFlags =
7387     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7388   CodeModel::Model M = getTargetMachine().getCodeModel();
7389   SDValue Result;
7390   if (OpFlags == X86II::MO_NO_FLAG &&
7391       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7392     // A direct static reference to a global.
7393     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7394     Offset = 0;
7395   } else {
7396     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7397   }
7398
7399   if (Subtarget->isPICStyleRIPRel() &&
7400       (M == CodeModel::Small || M == CodeModel::Kernel))
7401     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7402   else
7403     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7404
7405   // With PIC, the address is actually $g + Offset.
7406   if (isGlobalRelativeToPICBase(OpFlags)) {
7407     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7408                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7409                          Result);
7410   }
7411
7412   // For globals that require a load from a stub to get the address, emit the
7413   // load.
7414   if (isGlobalStubReference(OpFlags))
7415     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7416                          MachinePointerInfo::getGOT(), false, false, false, 0);
7417
7418   // If there was a non-zero offset that we didn't fold, create an explicit
7419   // addition for it.
7420   if (Offset != 0)
7421     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7422                          DAG.getConstant(Offset, getPointerTy()));
7423
7424   return Result;
7425 }
7426
7427 SDValue
7428 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7429   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7430   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7431   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7432 }
7433
7434 static SDValue
7435 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7436            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7437            unsigned char OperandFlags) {
7438   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7439   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7440   DebugLoc dl = GA->getDebugLoc();
7441   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7442                                            GA->getValueType(0),
7443                                            GA->getOffset(),
7444                                            OperandFlags);
7445   if (InFlag) {
7446     SDValue Ops[] = { Chain,  TGA, *InFlag };
7447     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7448   } else {
7449     SDValue Ops[]  = { Chain, TGA };
7450     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7451   }
7452
7453   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7454   MFI->setAdjustsStack(true);
7455
7456   SDValue Flag = Chain.getValue(1);
7457   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7458 }
7459
7460 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7461 static SDValue
7462 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7463                                 const EVT PtrVT) {
7464   SDValue InFlag;
7465   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7466   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7467                                      DAG.getNode(X86ISD::GlobalBaseReg,
7468                                                  DebugLoc(), PtrVT), InFlag);
7469   InFlag = Chain.getValue(1);
7470
7471   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7472 }
7473
7474 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7475 static SDValue
7476 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7477                                 const EVT PtrVT) {
7478   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7479                     X86::RAX, X86II::MO_TLSGD);
7480 }
7481
7482 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7483 // "local exec" model.
7484 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7485                                    const EVT PtrVT, TLSModel::Model model,
7486                                    bool is64Bit) {
7487   DebugLoc dl = GA->getDebugLoc();
7488
7489   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7490   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7491                                                          is64Bit ? 257 : 256));
7492
7493   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7494                                       DAG.getIntPtrConstant(0),
7495                                       MachinePointerInfo(Ptr),
7496                                       false, false, false, 0);
7497
7498   unsigned char OperandFlags = 0;
7499   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7500   // initialexec.
7501   unsigned WrapperKind = X86ISD::Wrapper;
7502   if (model == TLSModel::LocalExec) {
7503     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7504   } else if (is64Bit) {
7505     assert(model == TLSModel::InitialExec);
7506     OperandFlags = X86II::MO_GOTTPOFF;
7507     WrapperKind = X86ISD::WrapperRIP;
7508   } else {
7509     assert(model == TLSModel::InitialExec);
7510     OperandFlags = X86II::MO_INDNTPOFF;
7511   }
7512
7513   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7514   // exec)
7515   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7516                                            GA->getValueType(0),
7517                                            GA->getOffset(), OperandFlags);
7518   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7519
7520   if (model == TLSModel::InitialExec)
7521     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7522                          MachinePointerInfo::getGOT(), false, false, false, 0);
7523
7524   // The address of the thread local variable is the add of the thread
7525   // pointer with the offset of the variable.
7526   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7527 }
7528
7529 SDValue
7530 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7531
7532   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7533   const GlobalValue *GV = GA->getGlobal();
7534
7535   if (Subtarget->isTargetELF()) {
7536     // TODO: implement the "local dynamic" model
7537     // TODO: implement the "initial exec"model for pic executables
7538
7539     // If GV is an alias then use the aliasee for determining
7540     // thread-localness.
7541     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7542       GV = GA->resolveAliasedGlobal(false);
7543
7544     TLSModel::Model model
7545       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7546
7547     switch (model) {
7548       case TLSModel::GeneralDynamic:
7549       case TLSModel::LocalDynamic: // not implemented
7550         if (Subtarget->is64Bit())
7551           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7552         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7553
7554       case TLSModel::InitialExec:
7555       case TLSModel::LocalExec:
7556         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7557                                    Subtarget->is64Bit());
7558     }
7559   } else if (Subtarget->isTargetDarwin()) {
7560     // Darwin only has one model of TLS.  Lower to that.
7561     unsigned char OpFlag = 0;
7562     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7563                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7564
7565     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7566     // global base reg.
7567     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7568                   !Subtarget->is64Bit();
7569     if (PIC32)
7570       OpFlag = X86II::MO_TLVP_PIC_BASE;
7571     else
7572       OpFlag = X86II::MO_TLVP;
7573     DebugLoc DL = Op.getDebugLoc();
7574     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7575                                                 GA->getValueType(0),
7576                                                 GA->getOffset(), OpFlag);
7577     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7578
7579     // With PIC32, the address is actually $g + Offset.
7580     if (PIC32)
7581       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7582                            DAG.getNode(X86ISD::GlobalBaseReg,
7583                                        DebugLoc(), getPointerTy()),
7584                            Offset);
7585
7586     // Lowering the machine isd will make sure everything is in the right
7587     // location.
7588     SDValue Chain = DAG.getEntryNode();
7589     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7590     SDValue Args[] = { Chain, Offset };
7591     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7592
7593     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7594     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7595     MFI->setAdjustsStack(true);
7596
7597     // And our return value (tls address) is in the standard call return value
7598     // location.
7599     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7600     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7601                               Chain.getValue(1));
7602   }
7603
7604   assert(false &&
7605          "TLS not implemented for this target.");
7606
7607   llvm_unreachable("Unreachable");
7608   return SDValue();
7609 }
7610
7611
7612 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7613 /// take a 2 x i32 value to shift plus a shift amount.
7614 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7615   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7616   EVT VT = Op.getValueType();
7617   unsigned VTBits = VT.getSizeInBits();
7618   DebugLoc dl = Op.getDebugLoc();
7619   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7620   SDValue ShOpLo = Op.getOperand(0);
7621   SDValue ShOpHi = Op.getOperand(1);
7622   SDValue ShAmt  = Op.getOperand(2);
7623   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7624                                      DAG.getConstant(VTBits - 1, MVT::i8))
7625                        : DAG.getConstant(0, VT);
7626
7627   SDValue Tmp2, Tmp3;
7628   if (Op.getOpcode() == ISD::SHL_PARTS) {
7629     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7630     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7631   } else {
7632     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7633     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7634   }
7635
7636   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7637                                 DAG.getConstant(VTBits, MVT::i8));
7638   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7639                              AndNode, DAG.getConstant(0, MVT::i8));
7640
7641   SDValue Hi, Lo;
7642   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7643   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7644   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7645
7646   if (Op.getOpcode() == ISD::SHL_PARTS) {
7647     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7648     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7649   } else {
7650     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7651     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7652   }
7653
7654   SDValue Ops[2] = { Lo, Hi };
7655   return DAG.getMergeValues(Ops, 2, dl);
7656 }
7657
7658 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7659                                            SelectionDAG &DAG) const {
7660   EVT SrcVT = Op.getOperand(0).getValueType();
7661
7662   if (SrcVT.isVector())
7663     return SDValue();
7664
7665   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7666          "Unknown SINT_TO_FP to lower!");
7667
7668   // These are really Legal; return the operand so the caller accepts it as
7669   // Legal.
7670   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7671     return Op;
7672   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7673       Subtarget->is64Bit()) {
7674     return Op;
7675   }
7676
7677   DebugLoc dl = Op.getDebugLoc();
7678   unsigned Size = SrcVT.getSizeInBits()/8;
7679   MachineFunction &MF = DAG.getMachineFunction();
7680   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7681   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7682   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7683                                StackSlot,
7684                                MachinePointerInfo::getFixedStack(SSFI),
7685                                false, false, 0);
7686   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7687 }
7688
7689 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7690                                      SDValue StackSlot,
7691                                      SelectionDAG &DAG) const {
7692   // Build the FILD
7693   DebugLoc DL = Op.getDebugLoc();
7694   SDVTList Tys;
7695   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7696   if (useSSE)
7697     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7698   else
7699     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7700
7701   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7702
7703   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7704   MachineMemOperand *MMO;
7705   if (FI) {
7706     int SSFI = FI->getIndex();
7707     MMO =
7708       DAG.getMachineFunction()
7709       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7710                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7711   } else {
7712     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7713     StackSlot = StackSlot.getOperand(1);
7714   }
7715   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7716   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7717                                            X86ISD::FILD, DL,
7718                                            Tys, Ops, array_lengthof(Ops),
7719                                            SrcVT, MMO);
7720
7721   if (useSSE) {
7722     Chain = Result.getValue(1);
7723     SDValue InFlag = Result.getValue(2);
7724
7725     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7726     // shouldn't be necessary except that RFP cannot be live across
7727     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7728     MachineFunction &MF = DAG.getMachineFunction();
7729     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7730     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7731     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7732     Tys = DAG.getVTList(MVT::Other);
7733     SDValue Ops[] = {
7734       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7735     };
7736     MachineMemOperand *MMO =
7737       DAG.getMachineFunction()
7738       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7739                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7740
7741     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7742                                     Ops, array_lengthof(Ops),
7743                                     Op.getValueType(), MMO);
7744     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7745                          MachinePointerInfo::getFixedStack(SSFI),
7746                          false, false, false, 0);
7747   }
7748
7749   return Result;
7750 }
7751
7752 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7753 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7754                                                SelectionDAG &DAG) const {
7755   // This algorithm is not obvious. Here it is in C code, more or less:
7756   /*
7757     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7758       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7759       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7760
7761       // Copy ints to xmm registers.
7762       __m128i xh = _mm_cvtsi32_si128( hi );
7763       __m128i xl = _mm_cvtsi32_si128( lo );
7764
7765       // Combine into low half of a single xmm register.
7766       __m128i x = _mm_unpacklo_epi32( xh, xl );
7767       __m128d d;
7768       double sd;
7769
7770       // Merge in appropriate exponents to give the integer bits the right
7771       // magnitude.
7772       x = _mm_unpacklo_epi32( x, exp );
7773
7774       // Subtract away the biases to deal with the IEEE-754 double precision
7775       // implicit 1.
7776       d = _mm_sub_pd( (__m128d) x, bias );
7777
7778       // All conversions up to here are exact. The correctly rounded result is
7779       // calculated using the current rounding mode using the following
7780       // horizontal add.
7781       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7782       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7783                                 // store doesn't really need to be here (except
7784                                 // maybe to zero the other double)
7785       return sd;
7786     }
7787   */
7788
7789   DebugLoc dl = Op.getDebugLoc();
7790   LLVMContext *Context = DAG.getContext();
7791
7792   // Build some magic constants.
7793   std::vector<Constant*> CV0;
7794   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7795   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7796   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7797   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7798   Constant *C0 = ConstantVector::get(CV0);
7799   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7800
7801   std::vector<Constant*> CV1;
7802   CV1.push_back(
7803     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7804   CV1.push_back(
7805     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7806   Constant *C1 = ConstantVector::get(CV1);
7807   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7808
7809   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7810                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7811                                         Op.getOperand(0),
7812                                         DAG.getIntPtrConstant(1)));
7813   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7814                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7815                                         Op.getOperand(0),
7816                                         DAG.getIntPtrConstant(0)));
7817   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7818   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7819                               MachinePointerInfo::getConstantPool(),
7820                               false, false, false, 16);
7821   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7822   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7823   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7824                               MachinePointerInfo::getConstantPool(),
7825                               false, false, false, 16);
7826   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7827
7828   // Add the halves; easiest way is to swap them into another reg first.
7829   int ShufMask[2] = { 1, -1 };
7830   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7831                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7832   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7833   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7834                      DAG.getIntPtrConstant(0));
7835 }
7836
7837 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7838 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7839                                                SelectionDAG &DAG) const {
7840   DebugLoc dl = Op.getDebugLoc();
7841   // FP constant to bias correct the final result.
7842   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7843                                    MVT::f64);
7844
7845   // Load the 32-bit value into an XMM register.
7846   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7847                              Op.getOperand(0));
7848
7849   // Zero out the upper parts of the register.
7850   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7851                                      DAG);
7852
7853   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7854                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7855                      DAG.getIntPtrConstant(0));
7856
7857   // Or the load with the bias.
7858   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7859                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7860                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7861                                                    MVT::v2f64, Load)),
7862                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7863                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7864                                                    MVT::v2f64, Bias)));
7865   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7866                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7867                    DAG.getIntPtrConstant(0));
7868
7869   // Subtract the bias.
7870   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7871
7872   // Handle final rounding.
7873   EVT DestVT = Op.getValueType();
7874
7875   if (DestVT.bitsLT(MVT::f64)) {
7876     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7877                        DAG.getIntPtrConstant(0));
7878   } else if (DestVT.bitsGT(MVT::f64)) {
7879     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7880   }
7881
7882   // Handle final rounding.
7883   return Sub;
7884 }
7885
7886 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7887                                            SelectionDAG &DAG) const {
7888   SDValue N0 = Op.getOperand(0);
7889   DebugLoc dl = Op.getDebugLoc();
7890
7891   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7892   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7893   // the optimization here.
7894   if (DAG.SignBitIsZero(N0))
7895     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7896
7897   EVT SrcVT = N0.getValueType();
7898   EVT DstVT = Op.getValueType();
7899   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7900     return LowerUINT_TO_FP_i64(Op, DAG);
7901   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7902     return LowerUINT_TO_FP_i32(Op, DAG);
7903
7904   // Make a 64-bit buffer, and use it to build an FILD.
7905   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7906   if (SrcVT == MVT::i32) {
7907     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7908     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7909                                      getPointerTy(), StackSlot, WordOff);
7910     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7911                                   StackSlot, MachinePointerInfo(),
7912                                   false, false, 0);
7913     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7914                                   OffsetSlot, MachinePointerInfo(),
7915                                   false, false, 0);
7916     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7917     return Fild;
7918   }
7919
7920   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7921   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7922                                 StackSlot, MachinePointerInfo(),
7923                                false, false, 0);
7924   // For i64 source, we need to add the appropriate power of 2 if the input
7925   // was negative.  This is the same as the optimization in
7926   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7927   // we must be careful to do the computation in x87 extended precision, not
7928   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7929   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7930   MachineMemOperand *MMO =
7931     DAG.getMachineFunction()
7932     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7933                           MachineMemOperand::MOLoad, 8, 8);
7934
7935   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7936   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7937   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7938                                          MVT::i64, MMO);
7939
7940   APInt FF(32, 0x5F800000ULL);
7941
7942   // Check whether the sign bit is set.
7943   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7944                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7945                                  ISD::SETLT);
7946
7947   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7948   SDValue FudgePtr = DAG.getConstantPool(
7949                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7950                                          getPointerTy());
7951
7952   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7953   SDValue Zero = DAG.getIntPtrConstant(0);
7954   SDValue Four = DAG.getIntPtrConstant(4);
7955   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7956                                Zero, Four);
7957   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7958
7959   // Load the value out, extending it from f32 to f80.
7960   // FIXME: Avoid the extend by constructing the right constant pool?
7961   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7962                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7963                                  MVT::f32, false, false, 4);
7964   // Extend everything to 80 bits to force it to be done on x87.
7965   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7966   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7967 }
7968
7969 std::pair<SDValue,SDValue> X86TargetLowering::
7970 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7971   DebugLoc DL = Op.getDebugLoc();
7972
7973   EVT DstTy = Op.getValueType();
7974
7975   if (!IsSigned) {
7976     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7977     DstTy = MVT::i64;
7978   }
7979
7980   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7981          DstTy.getSimpleVT() >= MVT::i16 &&
7982          "Unknown FP_TO_SINT to lower!");
7983
7984   // These are really Legal.
7985   if (DstTy == MVT::i32 &&
7986       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7987     return std::make_pair(SDValue(), SDValue());
7988   if (Subtarget->is64Bit() &&
7989       DstTy == MVT::i64 &&
7990       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7991     return std::make_pair(SDValue(), SDValue());
7992
7993   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7994   // stack slot.
7995   MachineFunction &MF = DAG.getMachineFunction();
7996   unsigned MemSize = DstTy.getSizeInBits()/8;
7997   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7998   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7999
8000
8001
8002   unsigned Opc;
8003   switch (DstTy.getSimpleVT().SimpleTy) {
8004   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8005   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8006   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8007   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8008   }
8009
8010   SDValue Chain = DAG.getEntryNode();
8011   SDValue Value = Op.getOperand(0);
8012   EVT TheVT = Op.getOperand(0).getValueType();
8013   if (isScalarFPTypeInSSEReg(TheVT)) {
8014     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8015     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8016                          MachinePointerInfo::getFixedStack(SSFI),
8017                          false, false, 0);
8018     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8019     SDValue Ops[] = {
8020       Chain, StackSlot, DAG.getValueType(TheVT)
8021     };
8022
8023     MachineMemOperand *MMO =
8024       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8025                               MachineMemOperand::MOLoad, MemSize, MemSize);
8026     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8027                                     DstTy, MMO);
8028     Chain = Value.getValue(1);
8029     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8030     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8031   }
8032
8033   MachineMemOperand *MMO =
8034     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8035                             MachineMemOperand::MOStore, MemSize, MemSize);
8036
8037   // Build the FP_TO_INT*_IN_MEM
8038   SDValue Ops[] = { Chain, Value, StackSlot };
8039   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8040                                          Ops, 3, DstTy, MMO);
8041
8042   return std::make_pair(FIST, StackSlot);
8043 }
8044
8045 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8046                                            SelectionDAG &DAG) const {
8047   if (Op.getValueType().isVector())
8048     return SDValue();
8049
8050   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8051   SDValue FIST = Vals.first, StackSlot = Vals.second;
8052   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8053   if (FIST.getNode() == 0) return Op;
8054
8055   // Load the result.
8056   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8057                      FIST, StackSlot, MachinePointerInfo(),
8058                      false, false, false, 0);
8059 }
8060
8061 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8062                                            SelectionDAG &DAG) const {
8063   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8064   SDValue FIST = Vals.first, StackSlot = Vals.second;
8065   assert(FIST.getNode() && "Unexpected failure");
8066
8067   // Load the result.
8068   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8069                      FIST, StackSlot, MachinePointerInfo(),
8070                      false, false, false, 0);
8071 }
8072
8073 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8074                                      SelectionDAG &DAG) const {
8075   LLVMContext *Context = DAG.getContext();
8076   DebugLoc dl = Op.getDebugLoc();
8077   EVT VT = Op.getValueType();
8078   EVT EltVT = VT;
8079   if (VT.isVector())
8080     EltVT = VT.getVectorElementType();
8081   std::vector<Constant*> CV;
8082   if (EltVT == MVT::f64) {
8083     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8084     CV.push_back(C);
8085     CV.push_back(C);
8086   } else {
8087     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8088     CV.push_back(C);
8089     CV.push_back(C);
8090     CV.push_back(C);
8091     CV.push_back(C);
8092   }
8093   Constant *C = ConstantVector::get(CV);
8094   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8095   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8096                              MachinePointerInfo::getConstantPool(),
8097                              false, false, false, 16);
8098   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8099 }
8100
8101 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8102   LLVMContext *Context = DAG.getContext();
8103   DebugLoc dl = Op.getDebugLoc();
8104   EVT VT = Op.getValueType();
8105   EVT EltVT = VT;
8106   if (VT.isVector())
8107     EltVT = VT.getVectorElementType();
8108   std::vector<Constant*> CV;
8109   if (EltVT == MVT::f64) {
8110     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8111     CV.push_back(C);
8112     CV.push_back(C);
8113   } else {
8114     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8115     CV.push_back(C);
8116     CV.push_back(C);
8117     CV.push_back(C);
8118     CV.push_back(C);
8119   }
8120   Constant *C = ConstantVector::get(CV);
8121   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8122   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8123                              MachinePointerInfo::getConstantPool(),
8124                              false, false, false, 16);
8125   if (VT.isVector()) {
8126     return DAG.getNode(ISD::BITCAST, dl, VT,
8127                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8128                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8129                                 Op.getOperand(0)),
8130                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8131   } else {
8132     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8133   }
8134 }
8135
8136 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8137   LLVMContext *Context = DAG.getContext();
8138   SDValue Op0 = Op.getOperand(0);
8139   SDValue Op1 = Op.getOperand(1);
8140   DebugLoc dl = Op.getDebugLoc();
8141   EVT VT = Op.getValueType();
8142   EVT SrcVT = Op1.getValueType();
8143
8144   // If second operand is smaller, extend it first.
8145   if (SrcVT.bitsLT(VT)) {
8146     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8147     SrcVT = VT;
8148   }
8149   // And if it is bigger, shrink it first.
8150   if (SrcVT.bitsGT(VT)) {
8151     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8152     SrcVT = VT;
8153   }
8154
8155   // At this point the operands and the result should have the same
8156   // type, and that won't be f80 since that is not custom lowered.
8157
8158   // First get the sign bit of second operand.
8159   std::vector<Constant*> CV;
8160   if (SrcVT == MVT::f64) {
8161     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8162     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8163   } else {
8164     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8165     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8166     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8167     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8168   }
8169   Constant *C = ConstantVector::get(CV);
8170   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8171   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8172                               MachinePointerInfo::getConstantPool(),
8173                               false, false, false, 16);
8174   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8175
8176   // Shift sign bit right or left if the two operands have different types.
8177   if (SrcVT.bitsGT(VT)) {
8178     // Op0 is MVT::f32, Op1 is MVT::f64.
8179     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8180     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8181                           DAG.getConstant(32, MVT::i32));
8182     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8183     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8184                           DAG.getIntPtrConstant(0));
8185   }
8186
8187   // Clear first operand sign bit.
8188   CV.clear();
8189   if (VT == MVT::f64) {
8190     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8191     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8192   } else {
8193     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8194     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8195     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8196     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8197   }
8198   C = ConstantVector::get(CV);
8199   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8200   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8201                               MachinePointerInfo::getConstantPool(),
8202                               false, false, false, 16);
8203   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8204
8205   // Or the value with the sign bit.
8206   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8207 }
8208
8209 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8210   SDValue N0 = Op.getOperand(0);
8211   DebugLoc dl = Op.getDebugLoc();
8212   EVT VT = Op.getValueType();
8213
8214   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8215   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8216                                   DAG.getConstant(1, VT));
8217   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8218 }
8219
8220 /// Emit nodes that will be selected as "test Op0,Op0", or something
8221 /// equivalent.
8222 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8223                                     SelectionDAG &DAG) const {
8224   DebugLoc dl = Op.getDebugLoc();
8225
8226   // CF and OF aren't always set the way we want. Determine which
8227   // of these we need.
8228   bool NeedCF = false;
8229   bool NeedOF = false;
8230   switch (X86CC) {
8231   default: break;
8232   case X86::COND_A: case X86::COND_AE:
8233   case X86::COND_B: case X86::COND_BE:
8234     NeedCF = true;
8235     break;
8236   case X86::COND_G: case X86::COND_GE:
8237   case X86::COND_L: case X86::COND_LE:
8238   case X86::COND_O: case X86::COND_NO:
8239     NeedOF = true;
8240     break;
8241   }
8242
8243   // See if we can use the EFLAGS value from the operand instead of
8244   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8245   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8246   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8247     // Emit a CMP with 0, which is the TEST pattern.
8248     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8249                        DAG.getConstant(0, Op.getValueType()));
8250
8251   unsigned Opcode = 0;
8252   unsigned NumOperands = 0;
8253   switch (Op.getNode()->getOpcode()) {
8254   case ISD::ADD:
8255     // Due to an isel shortcoming, be conservative if this add is likely to be
8256     // selected as part of a load-modify-store instruction. When the root node
8257     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8258     // uses of other nodes in the match, such as the ADD in this case. This
8259     // leads to the ADD being left around and reselected, with the result being
8260     // two adds in the output.  Alas, even if none our users are stores, that
8261     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8262     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8263     // climbing the DAG back to the root, and it doesn't seem to be worth the
8264     // effort.
8265     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8266            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8267       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8268         goto default_case;
8269
8270     if (ConstantSDNode *C =
8271         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8272       // An add of one will be selected as an INC.
8273       if (C->getAPIntValue() == 1) {
8274         Opcode = X86ISD::INC;
8275         NumOperands = 1;
8276         break;
8277       }
8278
8279       // An add of negative one (subtract of one) will be selected as a DEC.
8280       if (C->getAPIntValue().isAllOnesValue()) {
8281         Opcode = X86ISD::DEC;
8282         NumOperands = 1;
8283         break;
8284       }
8285     }
8286
8287     // Otherwise use a regular EFLAGS-setting add.
8288     Opcode = X86ISD::ADD;
8289     NumOperands = 2;
8290     break;
8291   case ISD::AND: {
8292     // If the primary and result isn't used, don't bother using X86ISD::AND,
8293     // because a TEST instruction will be better.
8294     bool NonFlagUse = false;
8295     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8296            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8297       SDNode *User = *UI;
8298       unsigned UOpNo = UI.getOperandNo();
8299       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8300         // Look pass truncate.
8301         UOpNo = User->use_begin().getOperandNo();
8302         User = *User->use_begin();
8303       }
8304
8305       if (User->getOpcode() != ISD::BRCOND &&
8306           User->getOpcode() != ISD::SETCC &&
8307           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8308         NonFlagUse = true;
8309         break;
8310       }
8311     }
8312
8313     if (!NonFlagUse)
8314       break;
8315   }
8316     // FALL THROUGH
8317   case ISD::SUB:
8318   case ISD::OR:
8319   case ISD::XOR:
8320     // Due to the ISEL shortcoming noted above, be conservative if this op is
8321     // likely to be selected as part of a load-modify-store instruction.
8322     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8323            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8324       if (UI->getOpcode() == ISD::STORE)
8325         goto default_case;
8326
8327     // Otherwise use a regular EFLAGS-setting instruction.
8328     switch (Op.getNode()->getOpcode()) {
8329     default: llvm_unreachable("unexpected operator!");
8330     case ISD::SUB: Opcode = X86ISD::SUB; break;
8331     case ISD::OR:  Opcode = X86ISD::OR;  break;
8332     case ISD::XOR: Opcode = X86ISD::XOR; break;
8333     case ISD::AND: Opcode = X86ISD::AND; break;
8334     }
8335
8336     NumOperands = 2;
8337     break;
8338   case X86ISD::ADD:
8339   case X86ISD::SUB:
8340   case X86ISD::INC:
8341   case X86ISD::DEC:
8342   case X86ISD::OR:
8343   case X86ISD::XOR:
8344   case X86ISD::AND:
8345     return SDValue(Op.getNode(), 1);
8346   default:
8347   default_case:
8348     break;
8349   }
8350
8351   if (Opcode == 0)
8352     // Emit a CMP with 0, which is the TEST pattern.
8353     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8354                        DAG.getConstant(0, Op.getValueType()));
8355
8356   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8357   SmallVector<SDValue, 4> Ops;
8358   for (unsigned i = 0; i != NumOperands; ++i)
8359     Ops.push_back(Op.getOperand(i));
8360
8361   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8362   DAG.ReplaceAllUsesWith(Op, New);
8363   return SDValue(New.getNode(), 1);
8364 }
8365
8366 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8367 /// equivalent.
8368 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8369                                    SelectionDAG &DAG) const {
8370   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8371     if (C->getAPIntValue() == 0)
8372       return EmitTest(Op0, X86CC, DAG);
8373
8374   DebugLoc dl = Op0.getDebugLoc();
8375   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8376 }
8377
8378 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8379 /// if it's possible.
8380 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8381                                      DebugLoc dl, SelectionDAG &DAG) const {
8382   SDValue Op0 = And.getOperand(0);
8383   SDValue Op1 = And.getOperand(1);
8384   if (Op0.getOpcode() == ISD::TRUNCATE)
8385     Op0 = Op0.getOperand(0);
8386   if (Op1.getOpcode() == ISD::TRUNCATE)
8387     Op1 = Op1.getOperand(0);
8388
8389   SDValue LHS, RHS;
8390   if (Op1.getOpcode() == ISD::SHL)
8391     std::swap(Op0, Op1);
8392   if (Op0.getOpcode() == ISD::SHL) {
8393     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8394       if (And00C->getZExtValue() == 1) {
8395         // If we looked past a truncate, check that it's only truncating away
8396         // known zeros.
8397         unsigned BitWidth = Op0.getValueSizeInBits();
8398         unsigned AndBitWidth = And.getValueSizeInBits();
8399         if (BitWidth > AndBitWidth) {
8400           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8401           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8402           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8403             return SDValue();
8404         }
8405         LHS = Op1;
8406         RHS = Op0.getOperand(1);
8407       }
8408   } else if (Op1.getOpcode() == ISD::Constant) {
8409     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8410     SDValue AndLHS = Op0;
8411     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8412       LHS = AndLHS.getOperand(0);
8413       RHS = AndLHS.getOperand(1);
8414     }
8415   }
8416
8417   if (LHS.getNode()) {
8418     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8419     // instruction.  Since the shift amount is in-range-or-undefined, we know
8420     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8421     // the encoding for the i16 version is larger than the i32 version.
8422     // Also promote i16 to i32 for performance / code size reason.
8423     if (LHS.getValueType() == MVT::i8 ||
8424         LHS.getValueType() == MVT::i16)
8425       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8426
8427     // If the operand types disagree, extend the shift amount to match.  Since
8428     // BT ignores high bits (like shifts) we can use anyextend.
8429     if (LHS.getValueType() != RHS.getValueType())
8430       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8431
8432     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8433     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8434     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8435                        DAG.getConstant(Cond, MVT::i8), BT);
8436   }
8437
8438   return SDValue();
8439 }
8440
8441 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8442
8443   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8444
8445   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8446   SDValue Op0 = Op.getOperand(0);
8447   SDValue Op1 = Op.getOperand(1);
8448   DebugLoc dl = Op.getDebugLoc();
8449   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8450
8451   // Optimize to BT if possible.
8452   // Lower (X & (1 << N)) == 0 to BT(X, N).
8453   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8454   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8455   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8456       Op1.getOpcode() == ISD::Constant &&
8457       cast<ConstantSDNode>(Op1)->isNullValue() &&
8458       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8459     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8460     if (NewSetCC.getNode())
8461       return NewSetCC;
8462   }
8463
8464   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8465   // these.
8466   if (Op1.getOpcode() == ISD::Constant &&
8467       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8468        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8469       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8470
8471     // If the input is a setcc, then reuse the input setcc or use a new one with
8472     // the inverted condition.
8473     if (Op0.getOpcode() == X86ISD::SETCC) {
8474       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8475       bool Invert = (CC == ISD::SETNE) ^
8476         cast<ConstantSDNode>(Op1)->isNullValue();
8477       if (!Invert) return Op0;
8478
8479       CCode = X86::GetOppositeBranchCondition(CCode);
8480       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8481                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8482     }
8483   }
8484
8485   bool isFP = Op1.getValueType().isFloatingPoint();
8486   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8487   if (X86CC == X86::COND_INVALID)
8488     return SDValue();
8489
8490   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8491   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8492                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8493 }
8494
8495 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8496 // ones, and then concatenate the result back.
8497 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8498   EVT VT = Op.getValueType();
8499
8500   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8501          "Unsupported value type for operation");
8502
8503   int NumElems = VT.getVectorNumElements();
8504   DebugLoc dl = Op.getDebugLoc();
8505   SDValue CC = Op.getOperand(2);
8506   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8507   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8508
8509   // Extract the LHS vectors
8510   SDValue LHS = Op.getOperand(0);
8511   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8512   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8513
8514   // Extract the RHS vectors
8515   SDValue RHS = Op.getOperand(1);
8516   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8517   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8518
8519   // Issue the operation on the smaller types and concatenate the result back
8520   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8521   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8522   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8523                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8524                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8525 }
8526
8527
8528 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8529   SDValue Cond;
8530   SDValue Op0 = Op.getOperand(0);
8531   SDValue Op1 = Op.getOperand(1);
8532   SDValue CC = Op.getOperand(2);
8533   EVT VT = Op.getValueType();
8534   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8535   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8536   DebugLoc dl = Op.getDebugLoc();
8537
8538   if (isFP) {
8539     unsigned SSECC = 8;
8540     EVT EltVT = Op0.getValueType().getVectorElementType();
8541     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8542
8543     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8544     bool Swap = false;
8545
8546     // SSE Condition code mapping:
8547     //  0 - EQ
8548     //  1 - LT
8549     //  2 - LE
8550     //  3 - UNORD
8551     //  4 - NEQ
8552     //  5 - NLT
8553     //  6 - NLE
8554     //  7 - ORD
8555     switch (SetCCOpcode) {
8556     default: break;
8557     case ISD::SETOEQ:
8558     case ISD::SETEQ:  SSECC = 0; break;
8559     case ISD::SETOGT:
8560     case ISD::SETGT: Swap = true; // Fallthrough
8561     case ISD::SETLT:
8562     case ISD::SETOLT: SSECC = 1; break;
8563     case ISD::SETOGE:
8564     case ISD::SETGE: Swap = true; // Fallthrough
8565     case ISD::SETLE:
8566     case ISD::SETOLE: SSECC = 2; break;
8567     case ISD::SETUO:  SSECC = 3; break;
8568     case ISD::SETUNE:
8569     case ISD::SETNE:  SSECC = 4; break;
8570     case ISD::SETULE: Swap = true;
8571     case ISD::SETUGE: SSECC = 5; break;
8572     case ISD::SETULT: Swap = true;
8573     case ISD::SETUGT: SSECC = 6; break;
8574     case ISD::SETO:   SSECC = 7; break;
8575     }
8576     if (Swap)
8577       std::swap(Op0, Op1);
8578
8579     // In the two special cases we can't handle, emit two comparisons.
8580     if (SSECC == 8) {
8581       if (SetCCOpcode == ISD::SETUEQ) {
8582         SDValue UNORD, EQ;
8583         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8584         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8585         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8586       } else if (SetCCOpcode == ISD::SETONE) {
8587         SDValue ORD, NEQ;
8588         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8589         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8590         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8591       }
8592       llvm_unreachable("Illegal FP comparison");
8593     }
8594     // Handle all other FP comparisons here.
8595     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8596   }
8597
8598   // Break 256-bit integer vector compare into smaller ones.
8599   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8600     return Lower256IntVSETCC(Op, DAG);
8601
8602   // We are handling one of the integer comparisons here.  Since SSE only has
8603   // GT and EQ comparisons for integer, swapping operands and multiple
8604   // operations may be required for some comparisons.
8605   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8606   bool Swap = false, Invert = false, FlipSigns = false;
8607
8608   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8609   default: break;
8610   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8611   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8612   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8613   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8614   }
8615
8616   switch (SetCCOpcode) {
8617   default: break;
8618   case ISD::SETNE:  Invert = true;
8619   case ISD::SETEQ:  Opc = EQOpc; break;
8620   case ISD::SETLT:  Swap = true;
8621   case ISD::SETGT:  Opc = GTOpc; break;
8622   case ISD::SETGE:  Swap = true;
8623   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8624   case ISD::SETULT: Swap = true;
8625   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8626   case ISD::SETUGE: Swap = true;
8627   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8628   }
8629   if (Swap)
8630     std::swap(Op0, Op1);
8631
8632   // Check that the operation in question is available (most are plain SSE2,
8633   // but PCMPGTQ and PCMPEQQ have different requirements).
8634   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8635     return SDValue();
8636   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8637     return SDValue();
8638
8639   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8640   // bits of the inputs before performing those operations.
8641   if (FlipSigns) {
8642     EVT EltVT = VT.getVectorElementType();
8643     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8644                                       EltVT);
8645     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8646     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8647                                     SignBits.size());
8648     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8649     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8650   }
8651
8652   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8653
8654   // If the logical-not of the result is required, perform that now.
8655   if (Invert)
8656     Result = DAG.getNOT(dl, Result, VT);
8657
8658   return Result;
8659 }
8660
8661 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8662 static bool isX86LogicalCmp(SDValue Op) {
8663   unsigned Opc = Op.getNode()->getOpcode();
8664   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8665     return true;
8666   if (Op.getResNo() == 1 &&
8667       (Opc == X86ISD::ADD ||
8668        Opc == X86ISD::SUB ||
8669        Opc == X86ISD::ADC ||
8670        Opc == X86ISD::SBB ||
8671        Opc == X86ISD::SMUL ||
8672        Opc == X86ISD::UMUL ||
8673        Opc == X86ISD::INC ||
8674        Opc == X86ISD::DEC ||
8675        Opc == X86ISD::OR ||
8676        Opc == X86ISD::XOR ||
8677        Opc == X86ISD::AND))
8678     return true;
8679
8680   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8681     return true;
8682
8683   return false;
8684 }
8685
8686 static bool isZero(SDValue V) {
8687   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8688   return C && C->isNullValue();
8689 }
8690
8691 static bool isAllOnes(SDValue V) {
8692   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8693   return C && C->isAllOnesValue();
8694 }
8695
8696 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8697   bool addTest = true;
8698   SDValue Cond  = Op.getOperand(0);
8699   SDValue Op1 = Op.getOperand(1);
8700   SDValue Op2 = Op.getOperand(2);
8701   DebugLoc DL = Op.getDebugLoc();
8702   SDValue CC;
8703
8704   if (Cond.getOpcode() == ISD::SETCC) {
8705     SDValue NewCond = LowerSETCC(Cond, DAG);
8706     if (NewCond.getNode())
8707       Cond = NewCond;
8708   }
8709
8710   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8711   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8712   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8713   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8714   if (Cond.getOpcode() == X86ISD::SETCC &&
8715       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8716       isZero(Cond.getOperand(1).getOperand(1))) {
8717     SDValue Cmp = Cond.getOperand(1);
8718
8719     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8720
8721     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8722         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8723       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8724
8725       SDValue CmpOp0 = Cmp.getOperand(0);
8726       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8727                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8728
8729       SDValue Res =   // Res = 0 or -1.
8730         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8731                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8732
8733       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8734         Res = DAG.getNOT(DL, Res, Res.getValueType());
8735
8736       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8737       if (N2C == 0 || !N2C->isNullValue())
8738         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8739       return Res;
8740     }
8741   }
8742
8743   // Look past (and (setcc_carry (cmp ...)), 1).
8744   if (Cond.getOpcode() == ISD::AND &&
8745       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8746     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8747     if (C && C->getAPIntValue() == 1)
8748       Cond = Cond.getOperand(0);
8749   }
8750
8751   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8752   // setting operand in place of the X86ISD::SETCC.
8753   unsigned CondOpcode = Cond.getOpcode();
8754   if (CondOpcode == X86ISD::SETCC ||
8755       CondOpcode == X86ISD::SETCC_CARRY) {
8756     CC = Cond.getOperand(0);
8757
8758     SDValue Cmp = Cond.getOperand(1);
8759     unsigned Opc = Cmp.getOpcode();
8760     EVT VT = Op.getValueType();
8761
8762     bool IllegalFPCMov = false;
8763     if (VT.isFloatingPoint() && !VT.isVector() &&
8764         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8765       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8766
8767     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8768         Opc == X86ISD::BT) { // FIXME
8769       Cond = Cmp;
8770       addTest = false;
8771     }
8772   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8773              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8774              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8775               Cond.getOperand(0).getValueType() != MVT::i8)) {
8776     SDValue LHS = Cond.getOperand(0);
8777     SDValue RHS = Cond.getOperand(1);
8778     unsigned X86Opcode;
8779     unsigned X86Cond;
8780     SDVTList VTs;
8781     switch (CondOpcode) {
8782     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8783     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8784     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8785     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8786     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8787     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8788     default: llvm_unreachable("unexpected overflowing operator");
8789     }
8790     if (CondOpcode == ISD::UMULO)
8791       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8792                           MVT::i32);
8793     else
8794       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8795
8796     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8797
8798     if (CondOpcode == ISD::UMULO)
8799       Cond = X86Op.getValue(2);
8800     else
8801       Cond = X86Op.getValue(1);
8802
8803     CC = DAG.getConstant(X86Cond, MVT::i8);
8804     addTest = false;
8805   }
8806
8807   if (addTest) {
8808     // Look pass the truncate.
8809     if (Cond.getOpcode() == ISD::TRUNCATE)
8810       Cond = Cond.getOperand(0);
8811
8812     // We know the result of AND is compared against zero. Try to match
8813     // it to BT.
8814     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8815       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8816       if (NewSetCC.getNode()) {
8817         CC = NewSetCC.getOperand(0);
8818         Cond = NewSetCC.getOperand(1);
8819         addTest = false;
8820       }
8821     }
8822   }
8823
8824   if (addTest) {
8825     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8826     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8827   }
8828
8829   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8830   // a <  b ?  0 : -1 -> RES = setcc_carry
8831   // a >= b ? -1 :  0 -> RES = setcc_carry
8832   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8833   if (Cond.getOpcode() == X86ISD::CMP) {
8834     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8835
8836     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8837         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8838       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8839                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8840       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8841         return DAG.getNOT(DL, Res, Res.getValueType());
8842       return Res;
8843     }
8844   }
8845
8846   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8847   // condition is true.
8848   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8849   SDValue Ops[] = { Op2, Op1, CC, Cond };
8850   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8851 }
8852
8853 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8854 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8855 // from the AND / OR.
8856 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8857   Opc = Op.getOpcode();
8858   if (Opc != ISD::OR && Opc != ISD::AND)
8859     return false;
8860   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8861           Op.getOperand(0).hasOneUse() &&
8862           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8863           Op.getOperand(1).hasOneUse());
8864 }
8865
8866 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8867 // 1 and that the SETCC node has a single use.
8868 static bool isXor1OfSetCC(SDValue Op) {
8869   if (Op.getOpcode() != ISD::XOR)
8870     return false;
8871   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8872   if (N1C && N1C->getAPIntValue() == 1) {
8873     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8874       Op.getOperand(0).hasOneUse();
8875   }
8876   return false;
8877 }
8878
8879 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8880   bool addTest = true;
8881   SDValue Chain = Op.getOperand(0);
8882   SDValue Cond  = Op.getOperand(1);
8883   SDValue Dest  = Op.getOperand(2);
8884   DebugLoc dl = Op.getDebugLoc();
8885   SDValue CC;
8886   bool Inverted = false;
8887
8888   if (Cond.getOpcode() == ISD::SETCC) {
8889     // Check for setcc([su]{add,sub,mul}o == 0).
8890     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8891         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8892         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8893         Cond.getOperand(0).getResNo() == 1 &&
8894         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8895          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8896          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8897          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8898          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8899          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8900       Inverted = true;
8901       Cond = Cond.getOperand(0);
8902     } else {
8903       SDValue NewCond = LowerSETCC(Cond, DAG);
8904       if (NewCond.getNode())
8905         Cond = NewCond;
8906     }
8907   }
8908 #if 0
8909   // FIXME: LowerXALUO doesn't handle these!!
8910   else if (Cond.getOpcode() == X86ISD::ADD  ||
8911            Cond.getOpcode() == X86ISD::SUB  ||
8912            Cond.getOpcode() == X86ISD::SMUL ||
8913            Cond.getOpcode() == X86ISD::UMUL)
8914     Cond = LowerXALUO(Cond, DAG);
8915 #endif
8916
8917   // Look pass (and (setcc_carry (cmp ...)), 1).
8918   if (Cond.getOpcode() == ISD::AND &&
8919       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8920     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8921     if (C && C->getAPIntValue() == 1)
8922       Cond = Cond.getOperand(0);
8923   }
8924
8925   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8926   // setting operand in place of the X86ISD::SETCC.
8927   unsigned CondOpcode = Cond.getOpcode();
8928   if (CondOpcode == X86ISD::SETCC ||
8929       CondOpcode == X86ISD::SETCC_CARRY) {
8930     CC = Cond.getOperand(0);
8931
8932     SDValue Cmp = Cond.getOperand(1);
8933     unsigned Opc = Cmp.getOpcode();
8934     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8935     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8936       Cond = Cmp;
8937       addTest = false;
8938     } else {
8939       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8940       default: break;
8941       case X86::COND_O:
8942       case X86::COND_B:
8943         // These can only come from an arithmetic instruction with overflow,
8944         // e.g. SADDO, UADDO.
8945         Cond = Cond.getNode()->getOperand(1);
8946         addTest = false;
8947         break;
8948       }
8949     }
8950   }
8951   CondOpcode = Cond.getOpcode();
8952   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8953       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8954       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8955        Cond.getOperand(0).getValueType() != MVT::i8)) {
8956     SDValue LHS = Cond.getOperand(0);
8957     SDValue RHS = Cond.getOperand(1);
8958     unsigned X86Opcode;
8959     unsigned X86Cond;
8960     SDVTList VTs;
8961     switch (CondOpcode) {
8962     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8963     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8964     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8965     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8966     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8967     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8968     default: llvm_unreachable("unexpected overflowing operator");
8969     }
8970     if (Inverted)
8971       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8972     if (CondOpcode == ISD::UMULO)
8973       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8974                           MVT::i32);
8975     else
8976       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8977
8978     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8979
8980     if (CondOpcode == ISD::UMULO)
8981       Cond = X86Op.getValue(2);
8982     else
8983       Cond = X86Op.getValue(1);
8984
8985     CC = DAG.getConstant(X86Cond, MVT::i8);
8986     addTest = false;
8987   } else {
8988     unsigned CondOpc;
8989     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8990       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8991       if (CondOpc == ISD::OR) {
8992         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8993         // two branches instead of an explicit OR instruction with a
8994         // separate test.
8995         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8996             isX86LogicalCmp(Cmp)) {
8997           CC = Cond.getOperand(0).getOperand(0);
8998           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8999                               Chain, Dest, CC, Cmp);
9000           CC = Cond.getOperand(1).getOperand(0);
9001           Cond = Cmp;
9002           addTest = false;
9003         }
9004       } else { // ISD::AND
9005         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9006         // two branches instead of an explicit AND instruction with a
9007         // separate test. However, we only do this if this block doesn't
9008         // have a fall-through edge, because this requires an explicit
9009         // jmp when the condition is false.
9010         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9011             isX86LogicalCmp(Cmp) &&
9012             Op.getNode()->hasOneUse()) {
9013           X86::CondCode CCode =
9014             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9015           CCode = X86::GetOppositeBranchCondition(CCode);
9016           CC = DAG.getConstant(CCode, MVT::i8);
9017           SDNode *User = *Op.getNode()->use_begin();
9018           // Look for an unconditional branch following this conditional branch.
9019           // We need this because we need to reverse the successors in order
9020           // to implement FCMP_OEQ.
9021           if (User->getOpcode() == ISD::BR) {
9022             SDValue FalseBB = User->getOperand(1);
9023             SDNode *NewBR =
9024               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9025             assert(NewBR == User);
9026             (void)NewBR;
9027             Dest = FalseBB;
9028
9029             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9030                                 Chain, Dest, CC, Cmp);
9031             X86::CondCode CCode =
9032               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9033             CCode = X86::GetOppositeBranchCondition(CCode);
9034             CC = DAG.getConstant(CCode, MVT::i8);
9035             Cond = Cmp;
9036             addTest = false;
9037           }
9038         }
9039       }
9040     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9041       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9042       // It should be transformed during dag combiner except when the condition
9043       // is set by a arithmetics with overflow node.
9044       X86::CondCode CCode =
9045         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9046       CCode = X86::GetOppositeBranchCondition(CCode);
9047       CC = DAG.getConstant(CCode, MVT::i8);
9048       Cond = Cond.getOperand(0).getOperand(1);
9049       addTest = false;
9050     } else if (Cond.getOpcode() == ISD::SETCC &&
9051                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9052       // For FCMP_OEQ, we can emit
9053       // two branches instead of an explicit AND instruction with a
9054       // separate test. However, we only do this if this block doesn't
9055       // have a fall-through edge, because this requires an explicit
9056       // jmp when the condition is false.
9057       if (Op.getNode()->hasOneUse()) {
9058         SDNode *User = *Op.getNode()->use_begin();
9059         // Look for an unconditional branch following this conditional branch.
9060         // We need this because we need to reverse the successors in order
9061         // to implement FCMP_OEQ.
9062         if (User->getOpcode() == ISD::BR) {
9063           SDValue FalseBB = User->getOperand(1);
9064           SDNode *NewBR =
9065             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9066           assert(NewBR == User);
9067           (void)NewBR;
9068           Dest = FalseBB;
9069
9070           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9071                                     Cond.getOperand(0), Cond.getOperand(1));
9072           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9073           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9074                               Chain, Dest, CC, Cmp);
9075           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9076           Cond = Cmp;
9077           addTest = false;
9078         }
9079       }
9080     } else if (Cond.getOpcode() == ISD::SETCC &&
9081                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9082       // For FCMP_UNE, we can emit
9083       // two branches instead of an explicit AND instruction with a
9084       // separate test. However, we only do this if this block doesn't
9085       // have a fall-through edge, because this requires an explicit
9086       // jmp when the condition is false.
9087       if (Op.getNode()->hasOneUse()) {
9088         SDNode *User = *Op.getNode()->use_begin();
9089         // Look for an unconditional branch following this conditional branch.
9090         // We need this because we need to reverse the successors in order
9091         // to implement FCMP_UNE.
9092         if (User->getOpcode() == ISD::BR) {
9093           SDValue FalseBB = User->getOperand(1);
9094           SDNode *NewBR =
9095             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9096           assert(NewBR == User);
9097           (void)NewBR;
9098
9099           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9100                                     Cond.getOperand(0), Cond.getOperand(1));
9101           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9102           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9103                               Chain, Dest, CC, Cmp);
9104           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9105           Cond = Cmp;
9106           addTest = false;
9107           Dest = FalseBB;
9108         }
9109       }
9110     }
9111   }
9112
9113   if (addTest) {
9114     // Look pass the truncate.
9115     if (Cond.getOpcode() == ISD::TRUNCATE)
9116       Cond = Cond.getOperand(0);
9117
9118     // We know the result of AND is compared against zero. Try to match
9119     // it to BT.
9120     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9121       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9122       if (NewSetCC.getNode()) {
9123         CC = NewSetCC.getOperand(0);
9124         Cond = NewSetCC.getOperand(1);
9125         addTest = false;
9126       }
9127     }
9128   }
9129
9130   if (addTest) {
9131     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9132     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9133   }
9134   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9135                      Chain, Dest, CC, Cond);
9136 }
9137
9138
9139 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9140 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9141 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9142 // that the guard pages used by the OS virtual memory manager are allocated in
9143 // correct sequence.
9144 SDValue
9145 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9146                                            SelectionDAG &DAG) const {
9147   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9148           EnableSegmentedStacks) &&
9149          "This should be used only on Windows targets or when segmented stacks "
9150          "are being used");
9151   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9152   DebugLoc dl = Op.getDebugLoc();
9153
9154   // Get the inputs.
9155   SDValue Chain = Op.getOperand(0);
9156   SDValue Size  = Op.getOperand(1);
9157   // FIXME: Ensure alignment here
9158
9159   bool Is64Bit = Subtarget->is64Bit();
9160   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9161
9162   if (EnableSegmentedStacks) {
9163     MachineFunction &MF = DAG.getMachineFunction();
9164     MachineRegisterInfo &MRI = MF.getRegInfo();
9165
9166     if (Is64Bit) {
9167       // The 64 bit implementation of segmented stacks needs to clobber both r10
9168       // r11. This makes it impossible to use it along with nested parameters.
9169       const Function *F = MF.getFunction();
9170
9171       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9172            I != E; I++)
9173         if (I->hasNestAttr())
9174           report_fatal_error("Cannot use segmented stacks with functions that "
9175                              "have nested arguments.");
9176     }
9177
9178     const TargetRegisterClass *AddrRegClass =
9179       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9180     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9181     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9182     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9183                                 DAG.getRegister(Vreg, SPTy));
9184     SDValue Ops1[2] = { Value, Chain };
9185     return DAG.getMergeValues(Ops1, 2, dl);
9186   } else {
9187     SDValue Flag;
9188     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9189
9190     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9191     Flag = Chain.getValue(1);
9192     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9193
9194     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9195     Flag = Chain.getValue(1);
9196
9197     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9198
9199     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9200     return DAG.getMergeValues(Ops1, 2, dl);
9201   }
9202 }
9203
9204 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9205   MachineFunction &MF = DAG.getMachineFunction();
9206   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9207
9208   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9209   DebugLoc DL = Op.getDebugLoc();
9210
9211   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9212     // vastart just stores the address of the VarArgsFrameIndex slot into the
9213     // memory location argument.
9214     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9215                                    getPointerTy());
9216     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9217                         MachinePointerInfo(SV), false, false, 0);
9218   }
9219
9220   // __va_list_tag:
9221   //   gp_offset         (0 - 6 * 8)
9222   //   fp_offset         (48 - 48 + 8 * 16)
9223   //   overflow_arg_area (point to parameters coming in memory).
9224   //   reg_save_area
9225   SmallVector<SDValue, 8> MemOps;
9226   SDValue FIN = Op.getOperand(1);
9227   // Store gp_offset
9228   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9229                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9230                                                MVT::i32),
9231                                FIN, MachinePointerInfo(SV), false, false, 0);
9232   MemOps.push_back(Store);
9233
9234   // Store fp_offset
9235   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9236                     FIN, DAG.getIntPtrConstant(4));
9237   Store = DAG.getStore(Op.getOperand(0), DL,
9238                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9239                                        MVT::i32),
9240                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9241   MemOps.push_back(Store);
9242
9243   // Store ptr to overflow_arg_area
9244   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9245                     FIN, DAG.getIntPtrConstant(4));
9246   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9247                                     getPointerTy());
9248   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9249                        MachinePointerInfo(SV, 8),
9250                        false, false, 0);
9251   MemOps.push_back(Store);
9252
9253   // Store ptr to reg_save_area.
9254   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9255                     FIN, DAG.getIntPtrConstant(8));
9256   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9257                                     getPointerTy());
9258   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9259                        MachinePointerInfo(SV, 16), false, false, 0);
9260   MemOps.push_back(Store);
9261   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9262                      &MemOps[0], MemOps.size());
9263 }
9264
9265 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9266   assert(Subtarget->is64Bit() &&
9267          "LowerVAARG only handles 64-bit va_arg!");
9268   assert((Subtarget->isTargetLinux() ||
9269           Subtarget->isTargetDarwin()) &&
9270           "Unhandled target in LowerVAARG");
9271   assert(Op.getNode()->getNumOperands() == 4);
9272   SDValue Chain = Op.getOperand(0);
9273   SDValue SrcPtr = Op.getOperand(1);
9274   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9275   unsigned Align = Op.getConstantOperandVal(3);
9276   DebugLoc dl = Op.getDebugLoc();
9277
9278   EVT ArgVT = Op.getNode()->getValueType(0);
9279   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9280   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9281   uint8_t ArgMode;
9282
9283   // Decide which area this value should be read from.
9284   // TODO: Implement the AMD64 ABI in its entirety. This simple
9285   // selection mechanism works only for the basic types.
9286   if (ArgVT == MVT::f80) {
9287     llvm_unreachable("va_arg for f80 not yet implemented");
9288   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9289     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9290   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9291     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9292   } else {
9293     llvm_unreachable("Unhandled argument type in LowerVAARG");
9294   }
9295
9296   if (ArgMode == 2) {
9297     // Sanity Check: Make sure using fp_offset makes sense.
9298     assert(!UseSoftFloat &&
9299            !(DAG.getMachineFunction()
9300                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9301            Subtarget->hasXMM());
9302   }
9303
9304   // Insert VAARG_64 node into the DAG
9305   // VAARG_64 returns two values: Variable Argument Address, Chain
9306   SmallVector<SDValue, 11> InstOps;
9307   InstOps.push_back(Chain);
9308   InstOps.push_back(SrcPtr);
9309   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9310   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9311   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9312   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9313   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9314                                           VTs, &InstOps[0], InstOps.size(),
9315                                           MVT::i64,
9316                                           MachinePointerInfo(SV),
9317                                           /*Align=*/0,
9318                                           /*Volatile=*/false,
9319                                           /*ReadMem=*/true,
9320                                           /*WriteMem=*/true);
9321   Chain = VAARG.getValue(1);
9322
9323   // Load the next argument and return it
9324   return DAG.getLoad(ArgVT, dl,
9325                      Chain,
9326                      VAARG,
9327                      MachinePointerInfo(),
9328                      false, false, false, 0);
9329 }
9330
9331 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9332   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9333   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9334   SDValue Chain = Op.getOperand(0);
9335   SDValue DstPtr = Op.getOperand(1);
9336   SDValue SrcPtr = Op.getOperand(2);
9337   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9338   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9339   DebugLoc DL = Op.getDebugLoc();
9340
9341   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9342                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9343                        false,
9344                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9345 }
9346
9347 SDValue
9348 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9349   DebugLoc dl = Op.getDebugLoc();
9350   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9351   switch (IntNo) {
9352   default: return SDValue();    // Don't custom lower most intrinsics.
9353   // Comparison intrinsics.
9354   case Intrinsic::x86_sse_comieq_ss:
9355   case Intrinsic::x86_sse_comilt_ss:
9356   case Intrinsic::x86_sse_comile_ss:
9357   case Intrinsic::x86_sse_comigt_ss:
9358   case Intrinsic::x86_sse_comige_ss:
9359   case Intrinsic::x86_sse_comineq_ss:
9360   case Intrinsic::x86_sse_ucomieq_ss:
9361   case Intrinsic::x86_sse_ucomilt_ss:
9362   case Intrinsic::x86_sse_ucomile_ss:
9363   case Intrinsic::x86_sse_ucomigt_ss:
9364   case Intrinsic::x86_sse_ucomige_ss:
9365   case Intrinsic::x86_sse_ucomineq_ss:
9366   case Intrinsic::x86_sse2_comieq_sd:
9367   case Intrinsic::x86_sse2_comilt_sd:
9368   case Intrinsic::x86_sse2_comile_sd:
9369   case Intrinsic::x86_sse2_comigt_sd:
9370   case Intrinsic::x86_sse2_comige_sd:
9371   case Intrinsic::x86_sse2_comineq_sd:
9372   case Intrinsic::x86_sse2_ucomieq_sd:
9373   case Intrinsic::x86_sse2_ucomilt_sd:
9374   case Intrinsic::x86_sse2_ucomile_sd:
9375   case Intrinsic::x86_sse2_ucomigt_sd:
9376   case Intrinsic::x86_sse2_ucomige_sd:
9377   case Intrinsic::x86_sse2_ucomineq_sd: {
9378     unsigned Opc = 0;
9379     ISD::CondCode CC = ISD::SETCC_INVALID;
9380     switch (IntNo) {
9381     default: break;
9382     case Intrinsic::x86_sse_comieq_ss:
9383     case Intrinsic::x86_sse2_comieq_sd:
9384       Opc = X86ISD::COMI;
9385       CC = ISD::SETEQ;
9386       break;
9387     case Intrinsic::x86_sse_comilt_ss:
9388     case Intrinsic::x86_sse2_comilt_sd:
9389       Opc = X86ISD::COMI;
9390       CC = ISD::SETLT;
9391       break;
9392     case Intrinsic::x86_sse_comile_ss:
9393     case Intrinsic::x86_sse2_comile_sd:
9394       Opc = X86ISD::COMI;
9395       CC = ISD::SETLE;
9396       break;
9397     case Intrinsic::x86_sse_comigt_ss:
9398     case Intrinsic::x86_sse2_comigt_sd:
9399       Opc = X86ISD::COMI;
9400       CC = ISD::SETGT;
9401       break;
9402     case Intrinsic::x86_sse_comige_ss:
9403     case Intrinsic::x86_sse2_comige_sd:
9404       Opc = X86ISD::COMI;
9405       CC = ISD::SETGE;
9406       break;
9407     case Intrinsic::x86_sse_comineq_ss:
9408     case Intrinsic::x86_sse2_comineq_sd:
9409       Opc = X86ISD::COMI;
9410       CC = ISD::SETNE;
9411       break;
9412     case Intrinsic::x86_sse_ucomieq_ss:
9413     case Intrinsic::x86_sse2_ucomieq_sd:
9414       Opc = X86ISD::UCOMI;
9415       CC = ISD::SETEQ;
9416       break;
9417     case Intrinsic::x86_sse_ucomilt_ss:
9418     case Intrinsic::x86_sse2_ucomilt_sd:
9419       Opc = X86ISD::UCOMI;
9420       CC = ISD::SETLT;
9421       break;
9422     case Intrinsic::x86_sse_ucomile_ss:
9423     case Intrinsic::x86_sse2_ucomile_sd:
9424       Opc = X86ISD::UCOMI;
9425       CC = ISD::SETLE;
9426       break;
9427     case Intrinsic::x86_sse_ucomigt_ss:
9428     case Intrinsic::x86_sse2_ucomigt_sd:
9429       Opc = X86ISD::UCOMI;
9430       CC = ISD::SETGT;
9431       break;
9432     case Intrinsic::x86_sse_ucomige_ss:
9433     case Intrinsic::x86_sse2_ucomige_sd:
9434       Opc = X86ISD::UCOMI;
9435       CC = ISD::SETGE;
9436       break;
9437     case Intrinsic::x86_sse_ucomineq_ss:
9438     case Intrinsic::x86_sse2_ucomineq_sd:
9439       Opc = X86ISD::UCOMI;
9440       CC = ISD::SETNE;
9441       break;
9442     }
9443
9444     SDValue LHS = Op.getOperand(1);
9445     SDValue RHS = Op.getOperand(2);
9446     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9447     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9448     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9449     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9450                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9451     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9452   }
9453   // Arithmetic intrinsics.
9454   case Intrinsic::x86_sse3_hadd_ps:
9455   case Intrinsic::x86_sse3_hadd_pd:
9456   case Intrinsic::x86_avx_hadd_ps_256:
9457   case Intrinsic::x86_avx_hadd_pd_256:
9458     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9459                        Op.getOperand(1), Op.getOperand(2));
9460   case Intrinsic::x86_sse3_hsub_ps:
9461   case Intrinsic::x86_sse3_hsub_pd:
9462   case Intrinsic::x86_avx_hsub_ps_256:
9463   case Intrinsic::x86_avx_hsub_pd_256:
9464     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9465                        Op.getOperand(1), Op.getOperand(2));
9466   // ptest and testp intrinsics. The intrinsic these come from are designed to
9467   // return an integer value, not just an instruction so lower it to the ptest
9468   // or testp pattern and a setcc for the result.
9469   case Intrinsic::x86_sse41_ptestz:
9470   case Intrinsic::x86_sse41_ptestc:
9471   case Intrinsic::x86_sse41_ptestnzc:
9472   case Intrinsic::x86_avx_ptestz_256:
9473   case Intrinsic::x86_avx_ptestc_256:
9474   case Intrinsic::x86_avx_ptestnzc_256:
9475   case Intrinsic::x86_avx_vtestz_ps:
9476   case Intrinsic::x86_avx_vtestc_ps:
9477   case Intrinsic::x86_avx_vtestnzc_ps:
9478   case Intrinsic::x86_avx_vtestz_pd:
9479   case Intrinsic::x86_avx_vtestc_pd:
9480   case Intrinsic::x86_avx_vtestnzc_pd:
9481   case Intrinsic::x86_avx_vtestz_ps_256:
9482   case Intrinsic::x86_avx_vtestc_ps_256:
9483   case Intrinsic::x86_avx_vtestnzc_ps_256:
9484   case Intrinsic::x86_avx_vtestz_pd_256:
9485   case Intrinsic::x86_avx_vtestc_pd_256:
9486   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9487     bool IsTestPacked = false;
9488     unsigned X86CC = 0;
9489     switch (IntNo) {
9490     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9491     case Intrinsic::x86_avx_vtestz_ps:
9492     case Intrinsic::x86_avx_vtestz_pd:
9493     case Intrinsic::x86_avx_vtestz_ps_256:
9494     case Intrinsic::x86_avx_vtestz_pd_256:
9495       IsTestPacked = true; // Fallthrough
9496     case Intrinsic::x86_sse41_ptestz:
9497     case Intrinsic::x86_avx_ptestz_256:
9498       // ZF = 1
9499       X86CC = X86::COND_E;
9500       break;
9501     case Intrinsic::x86_avx_vtestc_ps:
9502     case Intrinsic::x86_avx_vtestc_pd:
9503     case Intrinsic::x86_avx_vtestc_ps_256:
9504     case Intrinsic::x86_avx_vtestc_pd_256:
9505       IsTestPacked = true; // Fallthrough
9506     case Intrinsic::x86_sse41_ptestc:
9507     case Intrinsic::x86_avx_ptestc_256:
9508       // CF = 1
9509       X86CC = X86::COND_B;
9510       break;
9511     case Intrinsic::x86_avx_vtestnzc_ps:
9512     case Intrinsic::x86_avx_vtestnzc_pd:
9513     case Intrinsic::x86_avx_vtestnzc_ps_256:
9514     case Intrinsic::x86_avx_vtestnzc_pd_256:
9515       IsTestPacked = true; // Fallthrough
9516     case Intrinsic::x86_sse41_ptestnzc:
9517     case Intrinsic::x86_avx_ptestnzc_256:
9518       // ZF and CF = 0
9519       X86CC = X86::COND_A;
9520       break;
9521     }
9522
9523     SDValue LHS = Op.getOperand(1);
9524     SDValue RHS = Op.getOperand(2);
9525     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9526     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9527     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9528     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9529     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9530   }
9531
9532   // Fix vector shift instructions where the last operand is a non-immediate
9533   // i32 value.
9534   case Intrinsic::x86_avx2_pslli_w:
9535   case Intrinsic::x86_avx2_pslli_d:
9536   case Intrinsic::x86_avx2_pslli_q:
9537   case Intrinsic::x86_avx2_psrli_w:
9538   case Intrinsic::x86_avx2_psrli_d:
9539   case Intrinsic::x86_avx2_psrli_q:
9540   case Intrinsic::x86_avx2_psrai_w:
9541   case Intrinsic::x86_avx2_psrai_d:
9542   case Intrinsic::x86_sse2_pslli_w:
9543   case Intrinsic::x86_sse2_pslli_d:
9544   case Intrinsic::x86_sse2_pslli_q:
9545   case Intrinsic::x86_sse2_psrli_w:
9546   case Intrinsic::x86_sse2_psrli_d:
9547   case Intrinsic::x86_sse2_psrli_q:
9548   case Intrinsic::x86_sse2_psrai_w:
9549   case Intrinsic::x86_sse2_psrai_d:
9550   case Intrinsic::x86_mmx_pslli_w:
9551   case Intrinsic::x86_mmx_pslli_d:
9552   case Intrinsic::x86_mmx_pslli_q:
9553   case Intrinsic::x86_mmx_psrli_w:
9554   case Intrinsic::x86_mmx_psrli_d:
9555   case Intrinsic::x86_mmx_psrli_q:
9556   case Intrinsic::x86_mmx_psrai_w:
9557   case Intrinsic::x86_mmx_psrai_d: {
9558     SDValue ShAmt = Op.getOperand(2);
9559     if (isa<ConstantSDNode>(ShAmt))
9560       return SDValue();
9561
9562     unsigned NewIntNo = 0;
9563     EVT ShAmtVT = MVT::v4i32;
9564     switch (IntNo) {
9565     case Intrinsic::x86_sse2_pslli_w:
9566       NewIntNo = Intrinsic::x86_sse2_psll_w;
9567       break;
9568     case Intrinsic::x86_sse2_pslli_d:
9569       NewIntNo = Intrinsic::x86_sse2_psll_d;
9570       break;
9571     case Intrinsic::x86_sse2_pslli_q:
9572       NewIntNo = Intrinsic::x86_sse2_psll_q;
9573       break;
9574     case Intrinsic::x86_sse2_psrli_w:
9575       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9576       break;
9577     case Intrinsic::x86_sse2_psrli_d:
9578       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9579       break;
9580     case Intrinsic::x86_sse2_psrli_q:
9581       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9582       break;
9583     case Intrinsic::x86_sse2_psrai_w:
9584       NewIntNo = Intrinsic::x86_sse2_psra_w;
9585       break;
9586     case Intrinsic::x86_sse2_psrai_d:
9587       NewIntNo = Intrinsic::x86_sse2_psra_d;
9588       break;
9589     case Intrinsic::x86_avx2_pslli_w:
9590       NewIntNo = Intrinsic::x86_avx2_psll_w;
9591       break;
9592     case Intrinsic::x86_avx2_pslli_d:
9593       NewIntNo = Intrinsic::x86_avx2_psll_d;
9594       break;
9595     case Intrinsic::x86_avx2_pslli_q:
9596       NewIntNo = Intrinsic::x86_avx2_psll_q;
9597       break;
9598     case Intrinsic::x86_avx2_psrli_w:
9599       NewIntNo = Intrinsic::x86_avx2_psrl_w;
9600       break;
9601     case Intrinsic::x86_avx2_psrli_d:
9602       NewIntNo = Intrinsic::x86_avx2_psrl_d;
9603       break;
9604     case Intrinsic::x86_avx2_psrli_q:
9605       NewIntNo = Intrinsic::x86_avx2_psrl_q;
9606       break;
9607     case Intrinsic::x86_avx2_psrai_w:
9608       NewIntNo = Intrinsic::x86_avx2_psra_w;
9609       break;
9610     case Intrinsic::x86_avx2_psrai_d:
9611       NewIntNo = Intrinsic::x86_avx2_psra_d;
9612       break;
9613     default: {
9614       ShAmtVT = MVT::v2i32;
9615       switch (IntNo) {
9616       case Intrinsic::x86_mmx_pslli_w:
9617         NewIntNo = Intrinsic::x86_mmx_psll_w;
9618         break;
9619       case Intrinsic::x86_mmx_pslli_d:
9620         NewIntNo = Intrinsic::x86_mmx_psll_d;
9621         break;
9622       case Intrinsic::x86_mmx_pslli_q:
9623         NewIntNo = Intrinsic::x86_mmx_psll_q;
9624         break;
9625       case Intrinsic::x86_mmx_psrli_w:
9626         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9627         break;
9628       case Intrinsic::x86_mmx_psrli_d:
9629         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9630         break;
9631       case Intrinsic::x86_mmx_psrli_q:
9632         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9633         break;
9634       case Intrinsic::x86_mmx_psrai_w:
9635         NewIntNo = Intrinsic::x86_mmx_psra_w;
9636         break;
9637       case Intrinsic::x86_mmx_psrai_d:
9638         NewIntNo = Intrinsic::x86_mmx_psra_d;
9639         break;
9640       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9641       }
9642       break;
9643     }
9644     }
9645
9646     // The vector shift intrinsics with scalars uses 32b shift amounts but
9647     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9648     // to be zero.
9649     SDValue ShOps[4];
9650     ShOps[0] = ShAmt;
9651     ShOps[1] = DAG.getConstant(0, MVT::i32);
9652     if (ShAmtVT == MVT::v4i32) {
9653       ShOps[2] = DAG.getUNDEF(MVT::i32);
9654       ShOps[3] = DAG.getUNDEF(MVT::i32);
9655       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9656     } else {
9657       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9658 // FIXME this must be lowered to get rid of the invalid type.
9659     }
9660
9661     EVT VT = Op.getValueType();
9662     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9663     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9664                        DAG.getConstant(NewIntNo, MVT::i32),
9665                        Op.getOperand(1), ShAmt);
9666   }
9667   }
9668 }
9669
9670 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9671                                            SelectionDAG &DAG) const {
9672   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9673   MFI->setReturnAddressIsTaken(true);
9674
9675   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9676   DebugLoc dl = Op.getDebugLoc();
9677
9678   if (Depth > 0) {
9679     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9680     SDValue Offset =
9681       DAG.getConstant(TD->getPointerSize(),
9682                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9683     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9684                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9685                                    FrameAddr, Offset),
9686                        MachinePointerInfo(), false, false, false, 0);
9687   }
9688
9689   // Just load the return address.
9690   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9691   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9692                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9693 }
9694
9695 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9696   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9697   MFI->setFrameAddressIsTaken(true);
9698
9699   EVT VT = Op.getValueType();
9700   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9701   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9702   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9703   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9704   while (Depth--)
9705     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9706                             MachinePointerInfo(),
9707                             false, false, false, 0);
9708   return FrameAddr;
9709 }
9710
9711 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9712                                                      SelectionDAG &DAG) const {
9713   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9714 }
9715
9716 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9717   MachineFunction &MF = DAG.getMachineFunction();
9718   SDValue Chain     = Op.getOperand(0);
9719   SDValue Offset    = Op.getOperand(1);
9720   SDValue Handler   = Op.getOperand(2);
9721   DebugLoc dl       = Op.getDebugLoc();
9722
9723   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9724                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9725                                      getPointerTy());
9726   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9727
9728   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9729                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9730   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9731   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9732                        false, false, 0);
9733   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9734   MF.getRegInfo().addLiveOut(StoreAddrReg);
9735
9736   return DAG.getNode(X86ISD::EH_RETURN, dl,
9737                      MVT::Other,
9738                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9739 }
9740
9741 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9742                                                   SelectionDAG &DAG) const {
9743   return Op.getOperand(0);
9744 }
9745
9746 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9747                                                 SelectionDAG &DAG) const {
9748   SDValue Root = Op.getOperand(0);
9749   SDValue Trmp = Op.getOperand(1); // trampoline
9750   SDValue FPtr = Op.getOperand(2); // nested function
9751   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9752   DebugLoc dl  = Op.getDebugLoc();
9753
9754   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9755
9756   if (Subtarget->is64Bit()) {
9757     SDValue OutChains[6];
9758
9759     // Large code-model.
9760     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9761     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9762
9763     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9764     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9765
9766     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9767
9768     // Load the pointer to the nested function into R11.
9769     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9770     SDValue Addr = Trmp;
9771     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9772                                 Addr, MachinePointerInfo(TrmpAddr),
9773                                 false, false, 0);
9774
9775     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9776                        DAG.getConstant(2, MVT::i64));
9777     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9778                                 MachinePointerInfo(TrmpAddr, 2),
9779                                 false, false, 2);
9780
9781     // Load the 'nest' parameter value into R10.
9782     // R10 is specified in X86CallingConv.td
9783     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9784     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9785                        DAG.getConstant(10, MVT::i64));
9786     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9787                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9788                                 false, false, 0);
9789
9790     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9791                        DAG.getConstant(12, MVT::i64));
9792     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9793                                 MachinePointerInfo(TrmpAddr, 12),
9794                                 false, false, 2);
9795
9796     // Jump to the nested function.
9797     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9798     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9799                        DAG.getConstant(20, MVT::i64));
9800     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9801                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9802                                 false, false, 0);
9803
9804     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9805     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9806                        DAG.getConstant(22, MVT::i64));
9807     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9808                                 MachinePointerInfo(TrmpAddr, 22),
9809                                 false, false, 0);
9810
9811     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9812   } else {
9813     const Function *Func =
9814       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9815     CallingConv::ID CC = Func->getCallingConv();
9816     unsigned NestReg;
9817
9818     switch (CC) {
9819     default:
9820       llvm_unreachable("Unsupported calling convention");
9821     case CallingConv::C:
9822     case CallingConv::X86_StdCall: {
9823       // Pass 'nest' parameter in ECX.
9824       // Must be kept in sync with X86CallingConv.td
9825       NestReg = X86::ECX;
9826
9827       // Check that ECX wasn't needed by an 'inreg' parameter.
9828       FunctionType *FTy = Func->getFunctionType();
9829       const AttrListPtr &Attrs = Func->getAttributes();
9830
9831       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9832         unsigned InRegCount = 0;
9833         unsigned Idx = 1;
9834
9835         for (FunctionType::param_iterator I = FTy->param_begin(),
9836              E = FTy->param_end(); I != E; ++I, ++Idx)
9837           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9838             // FIXME: should only count parameters that are lowered to integers.
9839             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9840
9841         if (InRegCount > 2) {
9842           report_fatal_error("Nest register in use - reduce number of inreg"
9843                              " parameters!");
9844         }
9845       }
9846       break;
9847     }
9848     case CallingConv::X86_FastCall:
9849     case CallingConv::X86_ThisCall:
9850     case CallingConv::Fast:
9851       // Pass 'nest' parameter in EAX.
9852       // Must be kept in sync with X86CallingConv.td
9853       NestReg = X86::EAX;
9854       break;
9855     }
9856
9857     SDValue OutChains[4];
9858     SDValue Addr, Disp;
9859
9860     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9861                        DAG.getConstant(10, MVT::i32));
9862     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9863
9864     // This is storing the opcode for MOV32ri.
9865     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9866     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9867     OutChains[0] = DAG.getStore(Root, dl,
9868                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9869                                 Trmp, MachinePointerInfo(TrmpAddr),
9870                                 false, false, 0);
9871
9872     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9873                        DAG.getConstant(1, MVT::i32));
9874     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9875                                 MachinePointerInfo(TrmpAddr, 1),
9876                                 false, false, 1);
9877
9878     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9879     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9880                        DAG.getConstant(5, MVT::i32));
9881     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9882                                 MachinePointerInfo(TrmpAddr, 5),
9883                                 false, false, 1);
9884
9885     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9886                        DAG.getConstant(6, MVT::i32));
9887     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9888                                 MachinePointerInfo(TrmpAddr, 6),
9889                                 false, false, 1);
9890
9891     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9892   }
9893 }
9894
9895 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9896                                             SelectionDAG &DAG) const {
9897   /*
9898    The rounding mode is in bits 11:10 of FPSR, and has the following
9899    settings:
9900      00 Round to nearest
9901      01 Round to -inf
9902      10 Round to +inf
9903      11 Round to 0
9904
9905   FLT_ROUNDS, on the other hand, expects the following:
9906     -1 Undefined
9907      0 Round to 0
9908      1 Round to nearest
9909      2 Round to +inf
9910      3 Round to -inf
9911
9912   To perform the conversion, we do:
9913     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9914   */
9915
9916   MachineFunction &MF = DAG.getMachineFunction();
9917   const TargetMachine &TM = MF.getTarget();
9918   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9919   unsigned StackAlignment = TFI.getStackAlignment();
9920   EVT VT = Op.getValueType();
9921   DebugLoc DL = Op.getDebugLoc();
9922
9923   // Save FP Control Word to stack slot
9924   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9925   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9926
9927
9928   MachineMemOperand *MMO =
9929    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9930                            MachineMemOperand::MOStore, 2, 2);
9931
9932   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9933   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9934                                           DAG.getVTList(MVT::Other),
9935                                           Ops, 2, MVT::i16, MMO);
9936
9937   // Load FP Control Word from stack slot
9938   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9939                             MachinePointerInfo(), false, false, false, 0);
9940
9941   // Transform as necessary
9942   SDValue CWD1 =
9943     DAG.getNode(ISD::SRL, DL, MVT::i16,
9944                 DAG.getNode(ISD::AND, DL, MVT::i16,
9945                             CWD, DAG.getConstant(0x800, MVT::i16)),
9946                 DAG.getConstant(11, MVT::i8));
9947   SDValue CWD2 =
9948     DAG.getNode(ISD::SRL, DL, MVT::i16,
9949                 DAG.getNode(ISD::AND, DL, MVT::i16,
9950                             CWD, DAG.getConstant(0x400, MVT::i16)),
9951                 DAG.getConstant(9, MVT::i8));
9952
9953   SDValue RetVal =
9954     DAG.getNode(ISD::AND, DL, MVT::i16,
9955                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9956                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9957                             DAG.getConstant(1, MVT::i16)),
9958                 DAG.getConstant(3, MVT::i16));
9959
9960
9961   return DAG.getNode((VT.getSizeInBits() < 16 ?
9962                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9963 }
9964
9965 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9966   EVT VT = Op.getValueType();
9967   EVT OpVT = VT;
9968   unsigned NumBits = VT.getSizeInBits();
9969   DebugLoc dl = Op.getDebugLoc();
9970
9971   Op = Op.getOperand(0);
9972   if (VT == MVT::i8) {
9973     // Zero extend to i32 since there is not an i8 bsr.
9974     OpVT = MVT::i32;
9975     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9976   }
9977
9978   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9979   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9980   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9981
9982   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9983   SDValue Ops[] = {
9984     Op,
9985     DAG.getConstant(NumBits+NumBits-1, OpVT),
9986     DAG.getConstant(X86::COND_E, MVT::i8),
9987     Op.getValue(1)
9988   };
9989   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9990
9991   // Finally xor with NumBits-1.
9992   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9993
9994   if (VT == MVT::i8)
9995     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9996   return Op;
9997 }
9998
9999 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10000   EVT VT = Op.getValueType();
10001   EVT OpVT = VT;
10002   unsigned NumBits = VT.getSizeInBits();
10003   DebugLoc dl = Op.getDebugLoc();
10004
10005   Op = Op.getOperand(0);
10006   if (VT == MVT::i8) {
10007     OpVT = MVT::i32;
10008     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10009   }
10010
10011   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10012   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10013   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10014
10015   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10016   SDValue Ops[] = {
10017     Op,
10018     DAG.getConstant(NumBits, OpVT),
10019     DAG.getConstant(X86::COND_E, MVT::i8),
10020     Op.getValue(1)
10021   };
10022   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10023
10024   if (VT == MVT::i8)
10025     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10026   return Op;
10027 }
10028
10029 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10030 // ones, and then concatenate the result back.
10031 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10032   EVT VT = Op.getValueType();
10033
10034   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10035          "Unsupported value type for operation");
10036
10037   int NumElems = VT.getVectorNumElements();
10038   DebugLoc dl = Op.getDebugLoc();
10039   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10040   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10041
10042   // Extract the LHS vectors
10043   SDValue LHS = Op.getOperand(0);
10044   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10045   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10046
10047   // Extract the RHS vectors
10048   SDValue RHS = Op.getOperand(1);
10049   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10050   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10051
10052   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10053   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10054
10055   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10056                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10057                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10058 }
10059
10060 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10061   assert(Op.getValueType().getSizeInBits() == 256 &&
10062          Op.getValueType().isInteger() &&
10063          "Only handle AVX 256-bit vector integer operation");
10064   return Lower256IntArith(Op, DAG);
10065 }
10066
10067 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10068   assert(Op.getValueType().getSizeInBits() == 256 &&
10069          Op.getValueType().isInteger() &&
10070          "Only handle AVX 256-bit vector integer operation");
10071   return Lower256IntArith(Op, DAG);
10072 }
10073
10074 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10075   EVT VT = Op.getValueType();
10076
10077   // Decompose 256-bit ops into smaller 128-bit ops.
10078   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10079     return Lower256IntArith(Op, DAG);
10080
10081   DebugLoc dl = Op.getDebugLoc();
10082
10083   SDValue A = Op.getOperand(0);
10084   SDValue B = Op.getOperand(1);
10085
10086   if (VT == MVT::v4i64) {
10087     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10088
10089     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10090     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10091     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10092     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10093     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10094     //
10095     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10096     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10097     //  return AloBlo + AloBhi + AhiBlo;
10098
10099     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10100                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10101                          A, DAG.getConstant(32, MVT::i32));
10102     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10103                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10104                          B, DAG.getConstant(32, MVT::i32));
10105     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10106                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10107                          A, B);
10108     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10109                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10110                          A, Bhi);
10111     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10112                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10113                          Ahi, B);
10114     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10115                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10116                          AloBhi, DAG.getConstant(32, MVT::i32));
10117     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10118                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10119                          AhiBlo, DAG.getConstant(32, MVT::i32));
10120     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10121     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10122     return Res;
10123   }
10124
10125   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10126
10127   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10128   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10129   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10130   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10131   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10132   //
10133   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10134   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10135   //  return AloBlo + AloBhi + AhiBlo;
10136
10137   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10138                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10139                        A, DAG.getConstant(32, MVT::i32));
10140   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10141                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10142                        B, DAG.getConstant(32, MVT::i32));
10143   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10144                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10145                        A, B);
10146   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10147                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10148                        A, Bhi);
10149   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10150                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10151                        Ahi, B);
10152   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10153                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10154                        AloBhi, DAG.getConstant(32, MVT::i32));
10155   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10156                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10157                        AhiBlo, DAG.getConstant(32, MVT::i32));
10158   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10159   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10160   return Res;
10161 }
10162
10163 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10164
10165   EVT VT = Op.getValueType();
10166   DebugLoc dl = Op.getDebugLoc();
10167   SDValue R = Op.getOperand(0);
10168   SDValue Amt = Op.getOperand(1);
10169   LLVMContext *Context = DAG.getContext();
10170
10171   if (!Subtarget->hasXMMInt())
10172     return SDValue();
10173
10174   // Optimize shl/srl/sra with constant shift amount.
10175   if (isSplatVector(Amt.getNode())) {
10176     SDValue SclrAmt = Amt->getOperand(0);
10177     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10178       uint64_t ShiftAmt = C->getZExtValue();
10179
10180       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10181         // Make a large shift.
10182         SDValue SHL =
10183           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10184                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10185                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10186         // Zero out the rightmost bits.
10187         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10188                                                        MVT::i8));
10189         return DAG.getNode(ISD::AND, dl, VT, SHL,
10190                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10191       }
10192
10193       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10194        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10195                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10196                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10197
10198       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10199        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10200                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10201                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10202
10203       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10204        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10205                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10206                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10207
10208       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10209         // Make a large shift.
10210         SDValue SRL =
10211           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10212                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10213                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10214         // Zero out the leftmost bits.
10215         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10216                                                        MVT::i8));
10217         return DAG.getNode(ISD::AND, dl, VT, SRL,
10218                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10219       }
10220
10221       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10222        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10223                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10224                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10225
10226       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10227        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10228                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10229                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10230
10231       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10232        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10233                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10234                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10235
10236       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10237        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10238                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10239                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10240
10241       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10242        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10243                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10244                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10245
10246       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10247         if (ShiftAmt == 7) {
10248           // R s>> 7  ===  R s< 0
10249           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10250           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10251         }
10252
10253         // R s>> a === ((R u>> a) ^ m) - m
10254         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10255         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10256                                                        MVT::i8));
10257         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10258         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10259         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10260         return Res;
10261       }
10262
10263       if (Subtarget->hasAVX2()) {
10264         if (VT == MVT::v4i64 && Op.getOpcode() == ISD::SHL)
10265          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10266                        DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10267                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10268
10269         if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SHL)
10270          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10271                        DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
10272                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10273
10274         if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SHL)
10275          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10276                        DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10277                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10278
10279         if (VT == MVT::v4i64 && Op.getOpcode() == ISD::SRL)
10280          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10281                        DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10282                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10283
10284         if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SRL)
10285          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10286                        DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
10287                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10288
10289         if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SRL)
10290          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10291                        DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10292                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10293
10294         if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SRA)
10295          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10296                        DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
10297                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10298
10299         if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SRA)
10300          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10301                        DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
10302                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10303         }
10304     }
10305   }
10306
10307   // Lower SHL with variable shift amount.
10308   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10309     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10310                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10311                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10312
10313     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10314
10315     std::vector<Constant*> CV(4, CI);
10316     Constant *C = ConstantVector::get(CV);
10317     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10318     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10319                                  MachinePointerInfo::getConstantPool(),
10320                                  false, false, false, 16);
10321
10322     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10323     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10324     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10325     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10326   }
10327   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10328     // a = a << 5;
10329     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10330                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10331                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10332
10333     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10334     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10335
10336     std::vector<Constant*> CVM1(16, CM1);
10337     std::vector<Constant*> CVM2(16, CM2);
10338     Constant *C = ConstantVector::get(CVM1);
10339     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10340     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10341                             MachinePointerInfo::getConstantPool(),
10342                             false, false, false, 16);
10343
10344     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10345     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10346     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10347                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10348                     DAG.getConstant(4, MVT::i32));
10349     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10350     // a += a
10351     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10352
10353     C = ConstantVector::get(CVM2);
10354     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10355     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10356                     MachinePointerInfo::getConstantPool(),
10357                     false, false, false, 16);
10358
10359     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10360     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10361     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10362                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10363                     DAG.getConstant(2, MVT::i32));
10364     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10365     // a += a
10366     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10367
10368     // return pblendv(r, r+r, a);
10369     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10370                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10371     return R;
10372   }
10373
10374   // Decompose 256-bit shifts into smaller 128-bit shifts.
10375   if (VT.getSizeInBits() == 256) {
10376     int NumElems = VT.getVectorNumElements();
10377     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10378     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10379
10380     // Extract the two vectors
10381     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10382     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10383                                      DAG, dl);
10384
10385     // Recreate the shift amount vectors
10386     SDValue Amt1, Amt2;
10387     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10388       // Constant shift amount
10389       SmallVector<SDValue, 4> Amt1Csts;
10390       SmallVector<SDValue, 4> Amt2Csts;
10391       for (int i = 0; i < NumElems/2; ++i)
10392         Amt1Csts.push_back(Amt->getOperand(i));
10393       for (int i = NumElems/2; i < NumElems; ++i)
10394         Amt2Csts.push_back(Amt->getOperand(i));
10395
10396       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10397                                  &Amt1Csts[0], NumElems/2);
10398       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10399                                  &Amt2Csts[0], NumElems/2);
10400     } else {
10401       // Variable shift amount
10402       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10403       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10404                                  DAG, dl);
10405     }
10406
10407     // Issue new vector shifts for the smaller types
10408     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10409     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10410
10411     // Concatenate the result back
10412     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10413   }
10414
10415   return SDValue();
10416 }
10417
10418 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10419   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10420   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10421   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10422   // has only one use.
10423   SDNode *N = Op.getNode();
10424   SDValue LHS = N->getOperand(0);
10425   SDValue RHS = N->getOperand(1);
10426   unsigned BaseOp = 0;
10427   unsigned Cond = 0;
10428   DebugLoc DL = Op.getDebugLoc();
10429   switch (Op.getOpcode()) {
10430   default: llvm_unreachable("Unknown ovf instruction!");
10431   case ISD::SADDO:
10432     // A subtract of one will be selected as a INC. Note that INC doesn't
10433     // set CF, so we can't do this for UADDO.
10434     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10435       if (C->isOne()) {
10436         BaseOp = X86ISD::INC;
10437         Cond = X86::COND_O;
10438         break;
10439       }
10440     BaseOp = X86ISD::ADD;
10441     Cond = X86::COND_O;
10442     break;
10443   case ISD::UADDO:
10444     BaseOp = X86ISD::ADD;
10445     Cond = X86::COND_B;
10446     break;
10447   case ISD::SSUBO:
10448     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10449     // set CF, so we can't do this for USUBO.
10450     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10451       if (C->isOne()) {
10452         BaseOp = X86ISD::DEC;
10453         Cond = X86::COND_O;
10454         break;
10455       }
10456     BaseOp = X86ISD::SUB;
10457     Cond = X86::COND_O;
10458     break;
10459   case ISD::USUBO:
10460     BaseOp = X86ISD::SUB;
10461     Cond = X86::COND_B;
10462     break;
10463   case ISD::SMULO:
10464     BaseOp = X86ISD::SMUL;
10465     Cond = X86::COND_O;
10466     break;
10467   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10468     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10469                                  MVT::i32);
10470     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10471
10472     SDValue SetCC =
10473       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10474                   DAG.getConstant(X86::COND_O, MVT::i32),
10475                   SDValue(Sum.getNode(), 2));
10476
10477     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10478   }
10479   }
10480
10481   // Also sets EFLAGS.
10482   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10483   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10484
10485   SDValue SetCC =
10486     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10487                 DAG.getConstant(Cond, MVT::i32),
10488                 SDValue(Sum.getNode(), 1));
10489
10490   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10491 }
10492
10493 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10494   DebugLoc dl = Op.getDebugLoc();
10495   SDNode* Node = Op.getNode();
10496   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10497   EVT VT = Node->getValueType(0);
10498   if (Subtarget->hasXMMInt() && VT.isVector()) {
10499     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10500                         ExtraVT.getScalarType().getSizeInBits();
10501     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10502
10503     unsigned SHLIntrinsicsID = 0;
10504     unsigned SRAIntrinsicsID = 0;
10505     switch (VT.getSimpleVT().SimpleTy) {
10506       default:
10507         return SDValue();
10508       case MVT::v4i32: {
10509         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10510         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10511         break;
10512       }
10513       case MVT::v8i16: {
10514         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10515         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10516         break;
10517       }
10518     }
10519
10520     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10521                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10522                          Node->getOperand(0), ShAmt);
10523
10524     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10525                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10526                        Tmp1, ShAmt);
10527   }
10528
10529   return SDValue();
10530 }
10531
10532
10533 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10534   DebugLoc dl = Op.getDebugLoc();
10535
10536   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10537   // There isn't any reason to disable it if the target processor supports it.
10538   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10539     SDValue Chain = Op.getOperand(0);
10540     SDValue Zero = DAG.getConstant(0, MVT::i32);
10541     SDValue Ops[] = {
10542       DAG.getRegister(X86::ESP, MVT::i32), // Base
10543       DAG.getTargetConstant(1, MVT::i8),   // Scale
10544       DAG.getRegister(0, MVT::i32),        // Index
10545       DAG.getTargetConstant(0, MVT::i32),  // Disp
10546       DAG.getRegister(0, MVT::i32),        // Segment.
10547       Zero,
10548       Chain
10549     };
10550     SDNode *Res =
10551       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10552                           array_lengthof(Ops));
10553     return SDValue(Res, 0);
10554   }
10555
10556   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10557   if (!isDev)
10558     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10559
10560   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10561   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10562   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10563   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10564
10565   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10566   if (!Op1 && !Op2 && !Op3 && Op4)
10567     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10568
10569   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10570   if (Op1 && !Op2 && !Op3 && !Op4)
10571     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10572
10573   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10574   //           (MFENCE)>;
10575   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10576 }
10577
10578 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10579                                              SelectionDAG &DAG) const {
10580   DebugLoc dl = Op.getDebugLoc();
10581   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10582     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10583   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10584     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10585
10586   // The only fence that needs an instruction is a sequentially-consistent
10587   // cross-thread fence.
10588   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10589     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10590     // no-sse2). There isn't any reason to disable it if the target processor
10591     // supports it.
10592     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10593       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10594
10595     SDValue Chain = Op.getOperand(0);
10596     SDValue Zero = DAG.getConstant(0, MVT::i32);
10597     SDValue Ops[] = {
10598       DAG.getRegister(X86::ESP, MVT::i32), // Base
10599       DAG.getTargetConstant(1, MVT::i8),   // Scale
10600       DAG.getRegister(0, MVT::i32),        // Index
10601       DAG.getTargetConstant(0, MVT::i32),  // Disp
10602       DAG.getRegister(0, MVT::i32),        // Segment.
10603       Zero,
10604       Chain
10605     };
10606     SDNode *Res =
10607       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10608                          array_lengthof(Ops));
10609     return SDValue(Res, 0);
10610   }
10611
10612   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10613   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10614 }
10615
10616
10617 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10618   EVT T = Op.getValueType();
10619   DebugLoc DL = Op.getDebugLoc();
10620   unsigned Reg = 0;
10621   unsigned size = 0;
10622   switch(T.getSimpleVT().SimpleTy) {
10623   default:
10624     assert(false && "Invalid value type!");
10625   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10626   case MVT::i16: Reg = X86::AX;  size = 2; break;
10627   case MVT::i32: Reg = X86::EAX; size = 4; break;
10628   case MVT::i64:
10629     assert(Subtarget->is64Bit() && "Node not type legal!");
10630     Reg = X86::RAX; size = 8;
10631     break;
10632   }
10633   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10634                                     Op.getOperand(2), SDValue());
10635   SDValue Ops[] = { cpIn.getValue(0),
10636                     Op.getOperand(1),
10637                     Op.getOperand(3),
10638                     DAG.getTargetConstant(size, MVT::i8),
10639                     cpIn.getValue(1) };
10640   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10641   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10642   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10643                                            Ops, 5, T, MMO);
10644   SDValue cpOut =
10645     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10646   return cpOut;
10647 }
10648
10649 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10650                                                  SelectionDAG &DAG) const {
10651   assert(Subtarget->is64Bit() && "Result not type legalized?");
10652   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10653   SDValue TheChain = Op.getOperand(0);
10654   DebugLoc dl = Op.getDebugLoc();
10655   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10656   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10657   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10658                                    rax.getValue(2));
10659   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10660                             DAG.getConstant(32, MVT::i8));
10661   SDValue Ops[] = {
10662     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10663     rdx.getValue(1)
10664   };
10665   return DAG.getMergeValues(Ops, 2, dl);
10666 }
10667
10668 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10669                                             SelectionDAG &DAG) const {
10670   EVT SrcVT = Op.getOperand(0).getValueType();
10671   EVT DstVT = Op.getValueType();
10672   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10673          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10674   assert((DstVT == MVT::i64 ||
10675           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10676          "Unexpected custom BITCAST");
10677   // i64 <=> MMX conversions are Legal.
10678   if (SrcVT==MVT::i64 && DstVT.isVector())
10679     return Op;
10680   if (DstVT==MVT::i64 && SrcVT.isVector())
10681     return Op;
10682   // MMX <=> MMX conversions are Legal.
10683   if (SrcVT.isVector() && DstVT.isVector())
10684     return Op;
10685   // All other conversions need to be expanded.
10686   return SDValue();
10687 }
10688
10689 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10690   SDNode *Node = Op.getNode();
10691   DebugLoc dl = Node->getDebugLoc();
10692   EVT T = Node->getValueType(0);
10693   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10694                               DAG.getConstant(0, T), Node->getOperand(2));
10695   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10696                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10697                        Node->getOperand(0),
10698                        Node->getOperand(1), negOp,
10699                        cast<AtomicSDNode>(Node)->getSrcValue(),
10700                        cast<AtomicSDNode>(Node)->getAlignment(),
10701                        cast<AtomicSDNode>(Node)->getOrdering(),
10702                        cast<AtomicSDNode>(Node)->getSynchScope());
10703 }
10704
10705 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10706   SDNode *Node = Op.getNode();
10707   DebugLoc dl = Node->getDebugLoc();
10708   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10709
10710   // Convert seq_cst store -> xchg
10711   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10712   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10713   //        (The only way to get a 16-byte store is cmpxchg16b)
10714   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10715   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10716       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10717     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10718                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10719                                  Node->getOperand(0),
10720                                  Node->getOperand(1), Node->getOperand(2),
10721                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10722                                  cast<AtomicSDNode>(Node)->getOrdering(),
10723                                  cast<AtomicSDNode>(Node)->getSynchScope());
10724     return Swap.getValue(1);
10725   }
10726   // Other atomic stores have a simple pattern.
10727   return Op;
10728 }
10729
10730 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10731   EVT VT = Op.getNode()->getValueType(0);
10732
10733   // Let legalize expand this if it isn't a legal type yet.
10734   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10735     return SDValue();
10736
10737   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10738
10739   unsigned Opc;
10740   bool ExtraOp = false;
10741   switch (Op.getOpcode()) {
10742   default: assert(0 && "Invalid code");
10743   case ISD::ADDC: Opc = X86ISD::ADD; break;
10744   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10745   case ISD::SUBC: Opc = X86ISD::SUB; break;
10746   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10747   }
10748
10749   if (!ExtraOp)
10750     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10751                        Op.getOperand(1));
10752   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10753                      Op.getOperand(1), Op.getOperand(2));
10754 }
10755
10756 /// LowerOperation - Provide custom lowering hooks for some operations.
10757 ///
10758 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10759   switch (Op.getOpcode()) {
10760   default: llvm_unreachable("Should not custom lower this!");
10761   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10762   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10763   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10764   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10765   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10766   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10767   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10768   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10769   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10770   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10771   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10772   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10773   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10774   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10775   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10776   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10777   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10778   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10779   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10780   case ISD::SHL_PARTS:
10781   case ISD::SRA_PARTS:
10782   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10783   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10784   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10785   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10786   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10787   case ISD::FABS:               return LowerFABS(Op, DAG);
10788   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10789   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10790   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10791   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10792   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10793   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10794   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10795   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10796   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10797   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10798   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10799   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10800   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10801   case ISD::FRAME_TO_ARGS_OFFSET:
10802                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10803   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10804   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10805   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10806   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10807   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10808   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10809   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10810   case ISD::MUL:                return LowerMUL(Op, DAG);
10811   case ISD::SRA:
10812   case ISD::SRL:
10813   case ISD::SHL:                return LowerShift(Op, DAG);
10814   case ISD::SADDO:
10815   case ISD::UADDO:
10816   case ISD::SSUBO:
10817   case ISD::USUBO:
10818   case ISD::SMULO:
10819   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10820   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10821   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10822   case ISD::ADDC:
10823   case ISD::ADDE:
10824   case ISD::SUBC:
10825   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10826   case ISD::ADD:                return LowerADD(Op, DAG);
10827   case ISD::SUB:                return LowerSUB(Op, DAG);
10828   }
10829 }
10830
10831 static void ReplaceATOMIC_LOAD(SDNode *Node,
10832                                   SmallVectorImpl<SDValue> &Results,
10833                                   SelectionDAG &DAG) {
10834   DebugLoc dl = Node->getDebugLoc();
10835   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10836
10837   // Convert wide load -> cmpxchg8b/cmpxchg16b
10838   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10839   //        (The only way to get a 16-byte load is cmpxchg16b)
10840   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10841   SDValue Zero = DAG.getConstant(0, VT);
10842   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10843                                Node->getOperand(0),
10844                                Node->getOperand(1), Zero, Zero,
10845                                cast<AtomicSDNode>(Node)->getMemOperand(),
10846                                cast<AtomicSDNode>(Node)->getOrdering(),
10847                                cast<AtomicSDNode>(Node)->getSynchScope());
10848   Results.push_back(Swap.getValue(0));
10849   Results.push_back(Swap.getValue(1));
10850 }
10851
10852 void X86TargetLowering::
10853 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10854                         SelectionDAG &DAG, unsigned NewOp) const {
10855   DebugLoc dl = Node->getDebugLoc();
10856   assert (Node->getValueType(0) == MVT::i64 &&
10857           "Only know how to expand i64 atomics");
10858
10859   SDValue Chain = Node->getOperand(0);
10860   SDValue In1 = Node->getOperand(1);
10861   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10862                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10863   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10864                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10865   SDValue Ops[] = { Chain, In1, In2L, In2H };
10866   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10867   SDValue Result =
10868     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10869                             cast<MemSDNode>(Node)->getMemOperand());
10870   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10871   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10872   Results.push_back(Result.getValue(2));
10873 }
10874
10875 /// ReplaceNodeResults - Replace a node with an illegal result type
10876 /// with a new node built out of custom code.
10877 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10878                                            SmallVectorImpl<SDValue>&Results,
10879                                            SelectionDAG &DAG) const {
10880   DebugLoc dl = N->getDebugLoc();
10881   switch (N->getOpcode()) {
10882   default:
10883     assert(false && "Do not know how to custom type legalize this operation!");
10884     return;
10885   case ISD::SIGN_EXTEND_INREG:
10886   case ISD::ADDC:
10887   case ISD::ADDE:
10888   case ISD::SUBC:
10889   case ISD::SUBE:
10890     // We don't want to expand or promote these.
10891     return;
10892   case ISD::FP_TO_SINT: {
10893     std::pair<SDValue,SDValue> Vals =
10894         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10895     SDValue FIST = Vals.first, StackSlot = Vals.second;
10896     if (FIST.getNode() != 0) {
10897       EVT VT = N->getValueType(0);
10898       // Return a load from the stack slot.
10899       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10900                                     MachinePointerInfo(), 
10901                                     false, false, false, 0));
10902     }
10903     return;
10904   }
10905   case ISD::READCYCLECOUNTER: {
10906     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10907     SDValue TheChain = N->getOperand(0);
10908     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10909     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10910                                      rd.getValue(1));
10911     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10912                                      eax.getValue(2));
10913     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10914     SDValue Ops[] = { eax, edx };
10915     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10916     Results.push_back(edx.getValue(1));
10917     return;
10918   }
10919   case ISD::ATOMIC_CMP_SWAP: {
10920     EVT T = N->getValueType(0);
10921     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10922     bool Regs64bit = T == MVT::i128;
10923     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10924     SDValue cpInL, cpInH;
10925     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10926                         DAG.getConstant(0, HalfT));
10927     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10928                         DAG.getConstant(1, HalfT));
10929     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10930                              Regs64bit ? X86::RAX : X86::EAX,
10931                              cpInL, SDValue());
10932     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10933                              Regs64bit ? X86::RDX : X86::EDX,
10934                              cpInH, cpInL.getValue(1));
10935     SDValue swapInL, swapInH;
10936     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10937                           DAG.getConstant(0, HalfT));
10938     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10939                           DAG.getConstant(1, HalfT));
10940     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10941                                Regs64bit ? X86::RBX : X86::EBX,
10942                                swapInL, cpInH.getValue(1));
10943     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10944                                Regs64bit ? X86::RCX : X86::ECX, 
10945                                swapInH, swapInL.getValue(1));
10946     SDValue Ops[] = { swapInH.getValue(0),
10947                       N->getOperand(1),
10948                       swapInH.getValue(1) };
10949     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10950     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10951     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10952                                   X86ISD::LCMPXCHG8_DAG;
10953     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10954                                              Ops, 3, T, MMO);
10955     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10956                                         Regs64bit ? X86::RAX : X86::EAX,
10957                                         HalfT, Result.getValue(1));
10958     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10959                                         Regs64bit ? X86::RDX : X86::EDX,
10960                                         HalfT, cpOutL.getValue(2));
10961     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10962     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10963     Results.push_back(cpOutH.getValue(1));
10964     return;
10965   }
10966   case ISD::ATOMIC_LOAD_ADD:
10967     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10968     return;
10969   case ISD::ATOMIC_LOAD_AND:
10970     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10971     return;
10972   case ISD::ATOMIC_LOAD_NAND:
10973     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10974     return;
10975   case ISD::ATOMIC_LOAD_OR:
10976     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10977     return;
10978   case ISD::ATOMIC_LOAD_SUB:
10979     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10980     return;
10981   case ISD::ATOMIC_LOAD_XOR:
10982     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10983     return;
10984   case ISD::ATOMIC_SWAP:
10985     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10986     return;
10987   case ISD::ATOMIC_LOAD:
10988     ReplaceATOMIC_LOAD(N, Results, DAG);
10989   }
10990 }
10991
10992 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10993   switch (Opcode) {
10994   default: return NULL;
10995   case X86ISD::BSF:                return "X86ISD::BSF";
10996   case X86ISD::BSR:                return "X86ISD::BSR";
10997   case X86ISD::SHLD:               return "X86ISD::SHLD";
10998   case X86ISD::SHRD:               return "X86ISD::SHRD";
10999   case X86ISD::FAND:               return "X86ISD::FAND";
11000   case X86ISD::FOR:                return "X86ISD::FOR";
11001   case X86ISD::FXOR:               return "X86ISD::FXOR";
11002   case X86ISD::FSRL:               return "X86ISD::FSRL";
11003   case X86ISD::FILD:               return "X86ISD::FILD";
11004   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11005   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11006   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11007   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11008   case X86ISD::FLD:                return "X86ISD::FLD";
11009   case X86ISD::FST:                return "X86ISD::FST";
11010   case X86ISD::CALL:               return "X86ISD::CALL";
11011   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11012   case X86ISD::BT:                 return "X86ISD::BT";
11013   case X86ISD::CMP:                return "X86ISD::CMP";
11014   case X86ISD::COMI:               return "X86ISD::COMI";
11015   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11016   case X86ISD::SETCC:              return "X86ISD::SETCC";
11017   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11018   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11019   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11020   case X86ISD::CMOV:               return "X86ISD::CMOV";
11021   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11022   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11023   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11024   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11025   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11026   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11027   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11028   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11029   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11030   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11031   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11032   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11033   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11034   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11035   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
11036   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
11037   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
11038   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11039   case X86ISD::FHADD:              return "X86ISD::FHADD";
11040   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11041   case X86ISD::FMAX:               return "X86ISD::FMAX";
11042   case X86ISD::FMIN:               return "X86ISD::FMIN";
11043   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11044   case X86ISD::FRCP:               return "X86ISD::FRCP";
11045   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11046   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11047   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11048   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11049   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11050   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11051   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11052   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11053   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11054   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11055   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11056   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11057   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11058   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11059   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11060   case X86ISD::VSHL:               return "X86ISD::VSHL";
11061   case X86ISD::VSRL:               return "X86ISD::VSRL";
11062   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
11063   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
11064   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
11065   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
11066   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
11067   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
11068   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
11069   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
11070   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
11071   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
11072   case X86ISD::ADD:                return "X86ISD::ADD";
11073   case X86ISD::SUB:                return "X86ISD::SUB";
11074   case X86ISD::ADC:                return "X86ISD::ADC";
11075   case X86ISD::SBB:                return "X86ISD::SBB";
11076   case X86ISD::SMUL:               return "X86ISD::SMUL";
11077   case X86ISD::UMUL:               return "X86ISD::UMUL";
11078   case X86ISD::INC:                return "X86ISD::INC";
11079   case X86ISD::DEC:                return "X86ISD::DEC";
11080   case X86ISD::OR:                 return "X86ISD::OR";
11081   case X86ISD::XOR:                return "X86ISD::XOR";
11082   case X86ISD::AND:                return "X86ISD::AND";
11083   case X86ISD::ANDN:               return "X86ISD::ANDN";
11084   case X86ISD::BLSI:               return "X86ISD::BLSI";
11085   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11086   case X86ISD::BLSR:               return "X86ISD::BLSR";
11087   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11088   case X86ISD::PTEST:              return "X86ISD::PTEST";
11089   case X86ISD::TESTP:              return "X86ISD::TESTP";
11090   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11091   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11092   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11093   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
11094   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11095   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
11096   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
11097   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
11098   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11099   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11100   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11101   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
11102   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11103   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11104   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11105   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11106   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11107   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
11108   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
11109   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11110   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11111   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
11112   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
11113   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
11114   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
11115   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
11116   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
11117   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
11118   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
11119   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
11120   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
11121   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
11122   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
11123   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
11124   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11125   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
11126   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
11127   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
11128   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
11129   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
11130   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11131   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11132   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11133   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11134   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11135   }
11136 }
11137
11138 // isLegalAddressingMode - Return true if the addressing mode represented
11139 // by AM is legal for this target, for a load/store of the specified type.
11140 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11141                                               Type *Ty) const {
11142   // X86 supports extremely general addressing modes.
11143   CodeModel::Model M = getTargetMachine().getCodeModel();
11144   Reloc::Model R = getTargetMachine().getRelocationModel();
11145
11146   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11147   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11148     return false;
11149
11150   if (AM.BaseGV) {
11151     unsigned GVFlags =
11152       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11153
11154     // If a reference to this global requires an extra load, we can't fold it.
11155     if (isGlobalStubReference(GVFlags))
11156       return false;
11157
11158     // If BaseGV requires a register for the PIC base, we cannot also have a
11159     // BaseReg specified.
11160     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11161       return false;
11162
11163     // If lower 4G is not available, then we must use rip-relative addressing.
11164     if ((M != CodeModel::Small || R != Reloc::Static) &&
11165         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11166       return false;
11167   }
11168
11169   switch (AM.Scale) {
11170   case 0:
11171   case 1:
11172   case 2:
11173   case 4:
11174   case 8:
11175     // These scales always work.
11176     break;
11177   case 3:
11178   case 5:
11179   case 9:
11180     // These scales are formed with basereg+scalereg.  Only accept if there is
11181     // no basereg yet.
11182     if (AM.HasBaseReg)
11183       return false;
11184     break;
11185   default:  // Other stuff never works.
11186     return false;
11187   }
11188
11189   return true;
11190 }
11191
11192
11193 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11194   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11195     return false;
11196   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11197   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11198   if (NumBits1 <= NumBits2)
11199     return false;
11200   return true;
11201 }
11202
11203 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11204   if (!VT1.isInteger() || !VT2.isInteger())
11205     return false;
11206   unsigned NumBits1 = VT1.getSizeInBits();
11207   unsigned NumBits2 = VT2.getSizeInBits();
11208   if (NumBits1 <= NumBits2)
11209     return false;
11210   return true;
11211 }
11212
11213 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11214   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11215   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11216 }
11217
11218 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11219   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11220   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11221 }
11222
11223 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11224   // i16 instructions are longer (0x66 prefix) and potentially slower.
11225   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11226 }
11227
11228 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11229 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11230 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11231 /// are assumed to be legal.
11232 bool
11233 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11234                                       EVT VT) const {
11235   // Very little shuffling can be done for 64-bit vectors right now.
11236   if (VT.getSizeInBits() == 64)
11237     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
11238
11239   // FIXME: pshufb, blends, shifts.
11240   return (VT.getVectorNumElements() == 2 ||
11241           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11242           isMOVLMask(M, VT) ||
11243           isSHUFPMask(M, VT) ||
11244           isPSHUFDMask(M, VT) ||
11245           isPSHUFHWMask(M, VT) ||
11246           isPSHUFLWMask(M, VT) ||
11247           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
11248           isUNPCKLMask(M, VT) ||
11249           isUNPCKHMask(M, VT) ||
11250           isUNPCKL_v_undef_Mask(M, VT) ||
11251           isUNPCKH_v_undef_Mask(M, VT));
11252 }
11253
11254 bool
11255 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11256                                           EVT VT) const {
11257   unsigned NumElts = VT.getVectorNumElements();
11258   // FIXME: This collection of masks seems suspect.
11259   if (NumElts == 2)
11260     return true;
11261   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11262     return (isMOVLMask(Mask, VT)  ||
11263             isCommutedMOVLMask(Mask, VT, true) ||
11264             isSHUFPMask(Mask, VT) ||
11265             isCommutedSHUFPMask(Mask, VT));
11266   }
11267   return false;
11268 }
11269
11270 //===----------------------------------------------------------------------===//
11271 //                           X86 Scheduler Hooks
11272 //===----------------------------------------------------------------------===//
11273
11274 // private utility function
11275 MachineBasicBlock *
11276 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11277                                                        MachineBasicBlock *MBB,
11278                                                        unsigned regOpc,
11279                                                        unsigned immOpc,
11280                                                        unsigned LoadOpc,
11281                                                        unsigned CXchgOpc,
11282                                                        unsigned notOpc,
11283                                                        unsigned EAXreg,
11284                                                        TargetRegisterClass *RC,
11285                                                        bool invSrc) const {
11286   // For the atomic bitwise operator, we generate
11287   //   thisMBB:
11288   //   newMBB:
11289   //     ld  t1 = [bitinstr.addr]
11290   //     op  t2 = t1, [bitinstr.val]
11291   //     mov EAX = t1
11292   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11293   //     bz  newMBB
11294   //     fallthrough -->nextMBB
11295   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11296   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11297   MachineFunction::iterator MBBIter = MBB;
11298   ++MBBIter;
11299
11300   /// First build the CFG
11301   MachineFunction *F = MBB->getParent();
11302   MachineBasicBlock *thisMBB = MBB;
11303   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11304   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11305   F->insert(MBBIter, newMBB);
11306   F->insert(MBBIter, nextMBB);
11307
11308   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11309   nextMBB->splice(nextMBB->begin(), thisMBB,
11310                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11311                   thisMBB->end());
11312   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11313
11314   // Update thisMBB to fall through to newMBB
11315   thisMBB->addSuccessor(newMBB);
11316
11317   // newMBB jumps to itself and fall through to nextMBB
11318   newMBB->addSuccessor(nextMBB);
11319   newMBB->addSuccessor(newMBB);
11320
11321   // Insert instructions into newMBB based on incoming instruction
11322   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11323          "unexpected number of operands");
11324   DebugLoc dl = bInstr->getDebugLoc();
11325   MachineOperand& destOper = bInstr->getOperand(0);
11326   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11327   int numArgs = bInstr->getNumOperands() - 1;
11328   for (int i=0; i < numArgs; ++i)
11329     argOpers[i] = &bInstr->getOperand(i+1);
11330
11331   // x86 address has 4 operands: base, index, scale, and displacement
11332   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11333   int valArgIndx = lastAddrIndx + 1;
11334
11335   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11336   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11337   for (int i=0; i <= lastAddrIndx; ++i)
11338     (*MIB).addOperand(*argOpers[i]);
11339
11340   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11341   if (invSrc) {
11342     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11343   }
11344   else
11345     tt = t1;
11346
11347   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11348   assert((argOpers[valArgIndx]->isReg() ||
11349           argOpers[valArgIndx]->isImm()) &&
11350          "invalid operand");
11351   if (argOpers[valArgIndx]->isReg())
11352     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11353   else
11354     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11355   MIB.addReg(tt);
11356   (*MIB).addOperand(*argOpers[valArgIndx]);
11357
11358   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11359   MIB.addReg(t1);
11360
11361   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11362   for (int i=0; i <= lastAddrIndx; ++i)
11363     (*MIB).addOperand(*argOpers[i]);
11364   MIB.addReg(t2);
11365   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11366   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11367                     bInstr->memoperands_end());
11368
11369   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11370   MIB.addReg(EAXreg);
11371
11372   // insert branch
11373   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11374
11375   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11376   return nextMBB;
11377 }
11378
11379 // private utility function:  64 bit atomics on 32 bit host.
11380 MachineBasicBlock *
11381 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11382                                                        MachineBasicBlock *MBB,
11383                                                        unsigned regOpcL,
11384                                                        unsigned regOpcH,
11385                                                        unsigned immOpcL,
11386                                                        unsigned immOpcH,
11387                                                        bool invSrc) const {
11388   // For the atomic bitwise operator, we generate
11389   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11390   //     ld t1,t2 = [bitinstr.addr]
11391   //   newMBB:
11392   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11393   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11394   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11395   //     mov ECX, EBX <- t5, t6
11396   //     mov EAX, EDX <- t1, t2
11397   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11398   //     mov t3, t4 <- EAX, EDX
11399   //     bz  newMBB
11400   //     result in out1, out2
11401   //     fallthrough -->nextMBB
11402
11403   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11404   const unsigned LoadOpc = X86::MOV32rm;
11405   const unsigned NotOpc = X86::NOT32r;
11406   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11407   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11408   MachineFunction::iterator MBBIter = MBB;
11409   ++MBBIter;
11410
11411   /// First build the CFG
11412   MachineFunction *F = MBB->getParent();
11413   MachineBasicBlock *thisMBB = MBB;
11414   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11415   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11416   F->insert(MBBIter, newMBB);
11417   F->insert(MBBIter, nextMBB);
11418
11419   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11420   nextMBB->splice(nextMBB->begin(), thisMBB,
11421                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11422                   thisMBB->end());
11423   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11424
11425   // Update thisMBB to fall through to newMBB
11426   thisMBB->addSuccessor(newMBB);
11427
11428   // newMBB jumps to itself and fall through to nextMBB
11429   newMBB->addSuccessor(nextMBB);
11430   newMBB->addSuccessor(newMBB);
11431
11432   DebugLoc dl = bInstr->getDebugLoc();
11433   // Insert instructions into newMBB based on incoming instruction
11434   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11435   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11436          "unexpected number of operands");
11437   MachineOperand& dest1Oper = bInstr->getOperand(0);
11438   MachineOperand& dest2Oper = bInstr->getOperand(1);
11439   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11440   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11441     argOpers[i] = &bInstr->getOperand(i+2);
11442
11443     // We use some of the operands multiple times, so conservatively just
11444     // clear any kill flags that might be present.
11445     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11446       argOpers[i]->setIsKill(false);
11447   }
11448
11449   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11450   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11451
11452   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11453   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11454   for (int i=0; i <= lastAddrIndx; ++i)
11455     (*MIB).addOperand(*argOpers[i]);
11456   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11457   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11458   // add 4 to displacement.
11459   for (int i=0; i <= lastAddrIndx-2; ++i)
11460     (*MIB).addOperand(*argOpers[i]);
11461   MachineOperand newOp3 = *(argOpers[3]);
11462   if (newOp3.isImm())
11463     newOp3.setImm(newOp3.getImm()+4);
11464   else
11465     newOp3.setOffset(newOp3.getOffset()+4);
11466   (*MIB).addOperand(newOp3);
11467   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11468
11469   // t3/4 are defined later, at the bottom of the loop
11470   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11471   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11472   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11473     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11474   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11475     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11476
11477   // The subsequent operations should be using the destination registers of
11478   //the PHI instructions.
11479   if (invSrc) {
11480     t1 = F->getRegInfo().createVirtualRegister(RC);
11481     t2 = F->getRegInfo().createVirtualRegister(RC);
11482     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11483     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11484   } else {
11485     t1 = dest1Oper.getReg();
11486     t2 = dest2Oper.getReg();
11487   }
11488
11489   int valArgIndx = lastAddrIndx + 1;
11490   assert((argOpers[valArgIndx]->isReg() ||
11491           argOpers[valArgIndx]->isImm()) &&
11492          "invalid operand");
11493   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11494   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11495   if (argOpers[valArgIndx]->isReg())
11496     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11497   else
11498     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11499   if (regOpcL != X86::MOV32rr)
11500     MIB.addReg(t1);
11501   (*MIB).addOperand(*argOpers[valArgIndx]);
11502   assert(argOpers[valArgIndx + 1]->isReg() ==
11503          argOpers[valArgIndx]->isReg());
11504   assert(argOpers[valArgIndx + 1]->isImm() ==
11505          argOpers[valArgIndx]->isImm());
11506   if (argOpers[valArgIndx + 1]->isReg())
11507     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11508   else
11509     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11510   if (regOpcH != X86::MOV32rr)
11511     MIB.addReg(t2);
11512   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11513
11514   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11515   MIB.addReg(t1);
11516   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11517   MIB.addReg(t2);
11518
11519   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11520   MIB.addReg(t5);
11521   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11522   MIB.addReg(t6);
11523
11524   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11525   for (int i=0; i <= lastAddrIndx; ++i)
11526     (*MIB).addOperand(*argOpers[i]);
11527
11528   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11529   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11530                     bInstr->memoperands_end());
11531
11532   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11533   MIB.addReg(X86::EAX);
11534   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11535   MIB.addReg(X86::EDX);
11536
11537   // insert branch
11538   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11539
11540   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11541   return nextMBB;
11542 }
11543
11544 // private utility function
11545 MachineBasicBlock *
11546 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11547                                                       MachineBasicBlock *MBB,
11548                                                       unsigned cmovOpc) const {
11549   // For the atomic min/max operator, we generate
11550   //   thisMBB:
11551   //   newMBB:
11552   //     ld t1 = [min/max.addr]
11553   //     mov t2 = [min/max.val]
11554   //     cmp  t1, t2
11555   //     cmov[cond] t2 = t1
11556   //     mov EAX = t1
11557   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11558   //     bz   newMBB
11559   //     fallthrough -->nextMBB
11560   //
11561   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11562   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11563   MachineFunction::iterator MBBIter = MBB;
11564   ++MBBIter;
11565
11566   /// First build the CFG
11567   MachineFunction *F = MBB->getParent();
11568   MachineBasicBlock *thisMBB = MBB;
11569   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11570   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11571   F->insert(MBBIter, newMBB);
11572   F->insert(MBBIter, nextMBB);
11573
11574   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11575   nextMBB->splice(nextMBB->begin(), thisMBB,
11576                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11577                   thisMBB->end());
11578   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11579
11580   // Update thisMBB to fall through to newMBB
11581   thisMBB->addSuccessor(newMBB);
11582
11583   // newMBB jumps to newMBB and fall through to nextMBB
11584   newMBB->addSuccessor(nextMBB);
11585   newMBB->addSuccessor(newMBB);
11586
11587   DebugLoc dl = mInstr->getDebugLoc();
11588   // Insert instructions into newMBB based on incoming instruction
11589   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11590          "unexpected number of operands");
11591   MachineOperand& destOper = mInstr->getOperand(0);
11592   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11593   int numArgs = mInstr->getNumOperands() - 1;
11594   for (int i=0; i < numArgs; ++i)
11595     argOpers[i] = &mInstr->getOperand(i+1);
11596
11597   // x86 address has 4 operands: base, index, scale, and displacement
11598   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11599   int valArgIndx = lastAddrIndx + 1;
11600
11601   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11602   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11603   for (int i=0; i <= lastAddrIndx; ++i)
11604     (*MIB).addOperand(*argOpers[i]);
11605
11606   // We only support register and immediate values
11607   assert((argOpers[valArgIndx]->isReg() ||
11608           argOpers[valArgIndx]->isImm()) &&
11609          "invalid operand");
11610
11611   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11612   if (argOpers[valArgIndx]->isReg())
11613     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11614   else
11615     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11616   (*MIB).addOperand(*argOpers[valArgIndx]);
11617
11618   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11619   MIB.addReg(t1);
11620
11621   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11622   MIB.addReg(t1);
11623   MIB.addReg(t2);
11624
11625   // Generate movc
11626   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11627   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11628   MIB.addReg(t2);
11629   MIB.addReg(t1);
11630
11631   // Cmp and exchange if none has modified the memory location
11632   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11633   for (int i=0; i <= lastAddrIndx; ++i)
11634     (*MIB).addOperand(*argOpers[i]);
11635   MIB.addReg(t3);
11636   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11637   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11638                     mInstr->memoperands_end());
11639
11640   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11641   MIB.addReg(X86::EAX);
11642
11643   // insert branch
11644   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11645
11646   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11647   return nextMBB;
11648 }
11649
11650 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11651 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11652 // in the .td file.
11653 MachineBasicBlock *
11654 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11655                             unsigned numArgs, bool memArg) const {
11656   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11657          "Target must have SSE4.2 or AVX features enabled");
11658
11659   DebugLoc dl = MI->getDebugLoc();
11660   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11661   unsigned Opc;
11662   if (!Subtarget->hasAVX()) {
11663     if (memArg)
11664       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11665     else
11666       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11667   } else {
11668     if (memArg)
11669       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11670     else
11671       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11672   }
11673
11674   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11675   for (unsigned i = 0; i < numArgs; ++i) {
11676     MachineOperand &Op = MI->getOperand(i+1);
11677     if (!(Op.isReg() && Op.isImplicit()))
11678       MIB.addOperand(Op);
11679   }
11680   BuildMI(*BB, MI, dl,
11681     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11682              MI->getOperand(0).getReg())
11683     .addReg(X86::XMM0);
11684
11685   MI->eraseFromParent();
11686   return BB;
11687 }
11688
11689 MachineBasicBlock *
11690 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11691   DebugLoc dl = MI->getDebugLoc();
11692   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11693
11694   // Address into RAX/EAX, other two args into ECX, EDX.
11695   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11696   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11697   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11698   for (int i = 0; i < X86::AddrNumOperands; ++i)
11699     MIB.addOperand(MI->getOperand(i));
11700
11701   unsigned ValOps = X86::AddrNumOperands;
11702   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11703     .addReg(MI->getOperand(ValOps).getReg());
11704   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11705     .addReg(MI->getOperand(ValOps+1).getReg());
11706
11707   // The instruction doesn't actually take any operands though.
11708   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11709
11710   MI->eraseFromParent(); // The pseudo is gone now.
11711   return BB;
11712 }
11713
11714 MachineBasicBlock *
11715 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11716   DebugLoc dl = MI->getDebugLoc();
11717   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11718
11719   // First arg in ECX, the second in EAX.
11720   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11721     .addReg(MI->getOperand(0).getReg());
11722   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11723     .addReg(MI->getOperand(1).getReg());
11724
11725   // The instruction doesn't actually take any operands though.
11726   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11727
11728   MI->eraseFromParent(); // The pseudo is gone now.
11729   return BB;
11730 }
11731
11732 MachineBasicBlock *
11733 X86TargetLowering::EmitVAARG64WithCustomInserter(
11734                    MachineInstr *MI,
11735                    MachineBasicBlock *MBB) const {
11736   // Emit va_arg instruction on X86-64.
11737
11738   // Operands to this pseudo-instruction:
11739   // 0  ) Output        : destination address (reg)
11740   // 1-5) Input         : va_list address (addr, i64mem)
11741   // 6  ) ArgSize       : Size (in bytes) of vararg type
11742   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11743   // 8  ) Align         : Alignment of type
11744   // 9  ) EFLAGS (implicit-def)
11745
11746   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11747   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11748
11749   unsigned DestReg = MI->getOperand(0).getReg();
11750   MachineOperand &Base = MI->getOperand(1);
11751   MachineOperand &Scale = MI->getOperand(2);
11752   MachineOperand &Index = MI->getOperand(3);
11753   MachineOperand &Disp = MI->getOperand(4);
11754   MachineOperand &Segment = MI->getOperand(5);
11755   unsigned ArgSize = MI->getOperand(6).getImm();
11756   unsigned ArgMode = MI->getOperand(7).getImm();
11757   unsigned Align = MI->getOperand(8).getImm();
11758
11759   // Memory Reference
11760   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11761   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11762   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11763
11764   // Machine Information
11765   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11766   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11767   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11768   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11769   DebugLoc DL = MI->getDebugLoc();
11770
11771   // struct va_list {
11772   //   i32   gp_offset
11773   //   i32   fp_offset
11774   //   i64   overflow_area (address)
11775   //   i64   reg_save_area (address)
11776   // }
11777   // sizeof(va_list) = 24
11778   // alignment(va_list) = 8
11779
11780   unsigned TotalNumIntRegs = 6;
11781   unsigned TotalNumXMMRegs = 8;
11782   bool UseGPOffset = (ArgMode == 1);
11783   bool UseFPOffset = (ArgMode == 2);
11784   unsigned MaxOffset = TotalNumIntRegs * 8 +
11785                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11786
11787   /* Align ArgSize to a multiple of 8 */
11788   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11789   bool NeedsAlign = (Align > 8);
11790
11791   MachineBasicBlock *thisMBB = MBB;
11792   MachineBasicBlock *overflowMBB;
11793   MachineBasicBlock *offsetMBB;
11794   MachineBasicBlock *endMBB;
11795
11796   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11797   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11798   unsigned OffsetReg = 0;
11799
11800   if (!UseGPOffset && !UseFPOffset) {
11801     // If we only pull from the overflow region, we don't create a branch.
11802     // We don't need to alter control flow.
11803     OffsetDestReg = 0; // unused
11804     OverflowDestReg = DestReg;
11805
11806     offsetMBB = NULL;
11807     overflowMBB = thisMBB;
11808     endMBB = thisMBB;
11809   } else {
11810     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11811     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11812     // If not, pull from overflow_area. (branch to overflowMBB)
11813     //
11814     //       thisMBB
11815     //         |     .
11816     //         |        .
11817     //     offsetMBB   overflowMBB
11818     //         |        .
11819     //         |     .
11820     //        endMBB
11821
11822     // Registers for the PHI in endMBB
11823     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11824     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11825
11826     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11827     MachineFunction *MF = MBB->getParent();
11828     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11829     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11830     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11831
11832     MachineFunction::iterator MBBIter = MBB;
11833     ++MBBIter;
11834
11835     // Insert the new basic blocks
11836     MF->insert(MBBIter, offsetMBB);
11837     MF->insert(MBBIter, overflowMBB);
11838     MF->insert(MBBIter, endMBB);
11839
11840     // Transfer the remainder of MBB and its successor edges to endMBB.
11841     endMBB->splice(endMBB->begin(), thisMBB,
11842                     llvm::next(MachineBasicBlock::iterator(MI)),
11843                     thisMBB->end());
11844     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11845
11846     // Make offsetMBB and overflowMBB successors of thisMBB
11847     thisMBB->addSuccessor(offsetMBB);
11848     thisMBB->addSuccessor(overflowMBB);
11849
11850     // endMBB is a successor of both offsetMBB and overflowMBB
11851     offsetMBB->addSuccessor(endMBB);
11852     overflowMBB->addSuccessor(endMBB);
11853
11854     // Load the offset value into a register
11855     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11856     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11857       .addOperand(Base)
11858       .addOperand(Scale)
11859       .addOperand(Index)
11860       .addDisp(Disp, UseFPOffset ? 4 : 0)
11861       .addOperand(Segment)
11862       .setMemRefs(MMOBegin, MMOEnd);
11863
11864     // Check if there is enough room left to pull this argument.
11865     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11866       .addReg(OffsetReg)
11867       .addImm(MaxOffset + 8 - ArgSizeA8);
11868
11869     // Branch to "overflowMBB" if offset >= max
11870     // Fall through to "offsetMBB" otherwise
11871     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11872       .addMBB(overflowMBB);
11873   }
11874
11875   // In offsetMBB, emit code to use the reg_save_area.
11876   if (offsetMBB) {
11877     assert(OffsetReg != 0);
11878
11879     // Read the reg_save_area address.
11880     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11881     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11882       .addOperand(Base)
11883       .addOperand(Scale)
11884       .addOperand(Index)
11885       .addDisp(Disp, 16)
11886       .addOperand(Segment)
11887       .setMemRefs(MMOBegin, MMOEnd);
11888
11889     // Zero-extend the offset
11890     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11891       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11892         .addImm(0)
11893         .addReg(OffsetReg)
11894         .addImm(X86::sub_32bit);
11895
11896     // Add the offset to the reg_save_area to get the final address.
11897     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11898       .addReg(OffsetReg64)
11899       .addReg(RegSaveReg);
11900
11901     // Compute the offset for the next argument
11902     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11903     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11904       .addReg(OffsetReg)
11905       .addImm(UseFPOffset ? 16 : 8);
11906
11907     // Store it back into the va_list.
11908     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11909       .addOperand(Base)
11910       .addOperand(Scale)
11911       .addOperand(Index)
11912       .addDisp(Disp, UseFPOffset ? 4 : 0)
11913       .addOperand(Segment)
11914       .addReg(NextOffsetReg)
11915       .setMemRefs(MMOBegin, MMOEnd);
11916
11917     // Jump to endMBB
11918     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11919       .addMBB(endMBB);
11920   }
11921
11922   //
11923   // Emit code to use overflow area
11924   //
11925
11926   // Load the overflow_area address into a register.
11927   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11928   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11929     .addOperand(Base)
11930     .addOperand(Scale)
11931     .addOperand(Index)
11932     .addDisp(Disp, 8)
11933     .addOperand(Segment)
11934     .setMemRefs(MMOBegin, MMOEnd);
11935
11936   // If we need to align it, do so. Otherwise, just copy the address
11937   // to OverflowDestReg.
11938   if (NeedsAlign) {
11939     // Align the overflow address
11940     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11941     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11942
11943     // aligned_addr = (addr + (align-1)) & ~(align-1)
11944     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11945       .addReg(OverflowAddrReg)
11946       .addImm(Align-1);
11947
11948     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11949       .addReg(TmpReg)
11950       .addImm(~(uint64_t)(Align-1));
11951   } else {
11952     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11953       .addReg(OverflowAddrReg);
11954   }
11955
11956   // Compute the next overflow address after this argument.
11957   // (the overflow address should be kept 8-byte aligned)
11958   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11959   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11960     .addReg(OverflowDestReg)
11961     .addImm(ArgSizeA8);
11962
11963   // Store the new overflow address.
11964   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11965     .addOperand(Base)
11966     .addOperand(Scale)
11967     .addOperand(Index)
11968     .addDisp(Disp, 8)
11969     .addOperand(Segment)
11970     .addReg(NextAddrReg)
11971     .setMemRefs(MMOBegin, MMOEnd);
11972
11973   // If we branched, emit the PHI to the front of endMBB.
11974   if (offsetMBB) {
11975     BuildMI(*endMBB, endMBB->begin(), DL,
11976             TII->get(X86::PHI), DestReg)
11977       .addReg(OffsetDestReg).addMBB(offsetMBB)
11978       .addReg(OverflowDestReg).addMBB(overflowMBB);
11979   }
11980
11981   // Erase the pseudo instruction
11982   MI->eraseFromParent();
11983
11984   return endMBB;
11985 }
11986
11987 MachineBasicBlock *
11988 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11989                                                  MachineInstr *MI,
11990                                                  MachineBasicBlock *MBB) const {
11991   // Emit code to save XMM registers to the stack. The ABI says that the
11992   // number of registers to save is given in %al, so it's theoretically
11993   // possible to do an indirect jump trick to avoid saving all of them,
11994   // however this code takes a simpler approach and just executes all
11995   // of the stores if %al is non-zero. It's less code, and it's probably
11996   // easier on the hardware branch predictor, and stores aren't all that
11997   // expensive anyway.
11998
11999   // Create the new basic blocks. One block contains all the XMM stores,
12000   // and one block is the final destination regardless of whether any
12001   // stores were performed.
12002   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12003   MachineFunction *F = MBB->getParent();
12004   MachineFunction::iterator MBBIter = MBB;
12005   ++MBBIter;
12006   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12007   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12008   F->insert(MBBIter, XMMSaveMBB);
12009   F->insert(MBBIter, EndMBB);
12010
12011   // Transfer the remainder of MBB and its successor edges to EndMBB.
12012   EndMBB->splice(EndMBB->begin(), MBB,
12013                  llvm::next(MachineBasicBlock::iterator(MI)),
12014                  MBB->end());
12015   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12016
12017   // The original block will now fall through to the XMM save block.
12018   MBB->addSuccessor(XMMSaveMBB);
12019   // The XMMSaveMBB will fall through to the end block.
12020   XMMSaveMBB->addSuccessor(EndMBB);
12021
12022   // Now add the instructions.
12023   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12024   DebugLoc DL = MI->getDebugLoc();
12025
12026   unsigned CountReg = MI->getOperand(0).getReg();
12027   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12028   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12029
12030   if (!Subtarget->isTargetWin64()) {
12031     // If %al is 0, branch around the XMM save block.
12032     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12033     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12034     MBB->addSuccessor(EndMBB);
12035   }
12036
12037   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12038   // In the XMM save block, save all the XMM argument registers.
12039   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12040     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12041     MachineMemOperand *MMO =
12042       F->getMachineMemOperand(
12043           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12044         MachineMemOperand::MOStore,
12045         /*Size=*/16, /*Align=*/16);
12046     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12047       .addFrameIndex(RegSaveFrameIndex)
12048       .addImm(/*Scale=*/1)
12049       .addReg(/*IndexReg=*/0)
12050       .addImm(/*Disp=*/Offset)
12051       .addReg(/*Segment=*/0)
12052       .addReg(MI->getOperand(i).getReg())
12053       .addMemOperand(MMO);
12054   }
12055
12056   MI->eraseFromParent();   // The pseudo instruction is gone now.
12057
12058   return EndMBB;
12059 }
12060
12061 MachineBasicBlock *
12062 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12063                                      MachineBasicBlock *BB) const {
12064   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12065   DebugLoc DL = MI->getDebugLoc();
12066
12067   // To "insert" a SELECT_CC instruction, we actually have to insert the
12068   // diamond control-flow pattern.  The incoming instruction knows the
12069   // destination vreg to set, the condition code register to branch on, the
12070   // true/false values to select between, and a branch opcode to use.
12071   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12072   MachineFunction::iterator It = BB;
12073   ++It;
12074
12075   //  thisMBB:
12076   //  ...
12077   //   TrueVal = ...
12078   //   cmpTY ccX, r1, r2
12079   //   bCC copy1MBB
12080   //   fallthrough --> copy0MBB
12081   MachineBasicBlock *thisMBB = BB;
12082   MachineFunction *F = BB->getParent();
12083   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12084   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12085   F->insert(It, copy0MBB);
12086   F->insert(It, sinkMBB);
12087
12088   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12089   // live into the sink and copy blocks.
12090   if (!MI->killsRegister(X86::EFLAGS)) {
12091     copy0MBB->addLiveIn(X86::EFLAGS);
12092     sinkMBB->addLiveIn(X86::EFLAGS);
12093   }
12094
12095   // Transfer the remainder of BB and its successor edges to sinkMBB.
12096   sinkMBB->splice(sinkMBB->begin(), BB,
12097                   llvm::next(MachineBasicBlock::iterator(MI)),
12098                   BB->end());
12099   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12100
12101   // Add the true and fallthrough blocks as its successors.
12102   BB->addSuccessor(copy0MBB);
12103   BB->addSuccessor(sinkMBB);
12104
12105   // Create the conditional branch instruction.
12106   unsigned Opc =
12107     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12108   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12109
12110   //  copy0MBB:
12111   //   %FalseValue = ...
12112   //   # fallthrough to sinkMBB
12113   copy0MBB->addSuccessor(sinkMBB);
12114
12115   //  sinkMBB:
12116   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12117   //  ...
12118   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12119           TII->get(X86::PHI), MI->getOperand(0).getReg())
12120     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12121     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12122
12123   MI->eraseFromParent();   // The pseudo instruction is gone now.
12124   return sinkMBB;
12125 }
12126
12127 MachineBasicBlock *
12128 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12129                                         bool Is64Bit) const {
12130   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12131   DebugLoc DL = MI->getDebugLoc();
12132   MachineFunction *MF = BB->getParent();
12133   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12134
12135   assert(EnableSegmentedStacks);
12136
12137   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12138   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12139
12140   // BB:
12141   //  ... [Till the alloca]
12142   // If stacklet is not large enough, jump to mallocMBB
12143   //
12144   // bumpMBB:
12145   //  Allocate by subtracting from RSP
12146   //  Jump to continueMBB
12147   //
12148   // mallocMBB:
12149   //  Allocate by call to runtime
12150   //
12151   // continueMBB:
12152   //  ...
12153   //  [rest of original BB]
12154   //
12155
12156   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12157   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12158   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12159
12160   MachineRegisterInfo &MRI = MF->getRegInfo();
12161   const TargetRegisterClass *AddrRegClass =
12162     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12163
12164   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12165     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12166     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12167     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12168     sizeVReg = MI->getOperand(1).getReg(),
12169     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12170
12171   MachineFunction::iterator MBBIter = BB;
12172   ++MBBIter;
12173
12174   MF->insert(MBBIter, bumpMBB);
12175   MF->insert(MBBIter, mallocMBB);
12176   MF->insert(MBBIter, continueMBB);
12177
12178   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12179                       (MachineBasicBlock::iterator(MI)), BB->end());
12180   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12181
12182   // Add code to the main basic block to check if the stack limit has been hit,
12183   // and if so, jump to mallocMBB otherwise to bumpMBB.
12184   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12185   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12186     .addReg(tmpSPVReg).addReg(sizeVReg);
12187   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12188     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12189     .addReg(SPLimitVReg);
12190   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12191
12192   // bumpMBB simply decreases the stack pointer, since we know the current
12193   // stacklet has enough space.
12194   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12195     .addReg(SPLimitVReg);
12196   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12197     .addReg(SPLimitVReg);
12198   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12199
12200   // Calls into a routine in libgcc to allocate more space from the heap.
12201   if (Is64Bit) {
12202     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12203       .addReg(sizeVReg);
12204     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12205     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12206   } else {
12207     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12208       .addImm(12);
12209     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12210     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12211       .addExternalSymbol("__morestack_allocate_stack_space");
12212   }
12213
12214   if (!Is64Bit)
12215     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12216       .addImm(16);
12217
12218   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12219     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12220   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12221
12222   // Set up the CFG correctly.
12223   BB->addSuccessor(bumpMBB);
12224   BB->addSuccessor(mallocMBB);
12225   mallocMBB->addSuccessor(continueMBB);
12226   bumpMBB->addSuccessor(continueMBB);
12227
12228   // Take care of the PHI nodes.
12229   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12230           MI->getOperand(0).getReg())
12231     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12232     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12233
12234   // Delete the original pseudo instruction.
12235   MI->eraseFromParent();
12236
12237   // And we're done.
12238   return continueMBB;
12239 }
12240
12241 MachineBasicBlock *
12242 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12243                                           MachineBasicBlock *BB) const {
12244   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12245   DebugLoc DL = MI->getDebugLoc();
12246
12247   assert(!Subtarget->isTargetEnvMacho());
12248
12249   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12250   // non-trivial part is impdef of ESP.
12251
12252   if (Subtarget->isTargetWin64()) {
12253     if (Subtarget->isTargetCygMing()) {
12254       // ___chkstk(Mingw64):
12255       // Clobbers R10, R11, RAX and EFLAGS.
12256       // Updates RSP.
12257       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12258         .addExternalSymbol("___chkstk")
12259         .addReg(X86::RAX, RegState::Implicit)
12260         .addReg(X86::RSP, RegState::Implicit)
12261         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12262         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12263         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12264     } else {
12265       // __chkstk(MSVCRT): does not update stack pointer.
12266       // Clobbers R10, R11 and EFLAGS.
12267       // FIXME: RAX(allocated size) might be reused and not killed.
12268       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12269         .addExternalSymbol("__chkstk")
12270         .addReg(X86::RAX, RegState::Implicit)
12271         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12272       // RAX has the offset to subtracted from RSP.
12273       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12274         .addReg(X86::RSP)
12275         .addReg(X86::RAX);
12276     }
12277   } else {
12278     const char *StackProbeSymbol =
12279       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12280
12281     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12282       .addExternalSymbol(StackProbeSymbol)
12283       .addReg(X86::EAX, RegState::Implicit)
12284       .addReg(X86::ESP, RegState::Implicit)
12285       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12286       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12287       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12288   }
12289
12290   MI->eraseFromParent();   // The pseudo instruction is gone now.
12291   return BB;
12292 }
12293
12294 MachineBasicBlock *
12295 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12296                                       MachineBasicBlock *BB) const {
12297   // This is pretty easy.  We're taking the value that we received from
12298   // our load from the relocation, sticking it in either RDI (x86-64)
12299   // or EAX and doing an indirect call.  The return value will then
12300   // be in the normal return register.
12301   const X86InstrInfo *TII
12302     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12303   DebugLoc DL = MI->getDebugLoc();
12304   MachineFunction *F = BB->getParent();
12305
12306   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12307   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12308
12309   if (Subtarget->is64Bit()) {
12310     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12311                                       TII->get(X86::MOV64rm), X86::RDI)
12312     .addReg(X86::RIP)
12313     .addImm(0).addReg(0)
12314     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12315                       MI->getOperand(3).getTargetFlags())
12316     .addReg(0);
12317     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12318     addDirectMem(MIB, X86::RDI);
12319   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12320     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12321                                       TII->get(X86::MOV32rm), X86::EAX)
12322     .addReg(0)
12323     .addImm(0).addReg(0)
12324     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12325                       MI->getOperand(3).getTargetFlags())
12326     .addReg(0);
12327     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12328     addDirectMem(MIB, X86::EAX);
12329   } else {
12330     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12331                                       TII->get(X86::MOV32rm), X86::EAX)
12332     .addReg(TII->getGlobalBaseReg(F))
12333     .addImm(0).addReg(0)
12334     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12335                       MI->getOperand(3).getTargetFlags())
12336     .addReg(0);
12337     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12338     addDirectMem(MIB, X86::EAX);
12339   }
12340
12341   MI->eraseFromParent(); // The pseudo instruction is gone now.
12342   return BB;
12343 }
12344
12345 MachineBasicBlock *
12346 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12347                                                MachineBasicBlock *BB) const {
12348   switch (MI->getOpcode()) {
12349   default: assert(0 && "Unexpected instr type to insert");
12350   case X86::TAILJMPd64:
12351   case X86::TAILJMPr64:
12352   case X86::TAILJMPm64:
12353     assert(0 && "TAILJMP64 would not be touched here.");
12354   case X86::TCRETURNdi64:
12355   case X86::TCRETURNri64:
12356   case X86::TCRETURNmi64:
12357     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12358     // On AMD64, additional defs should be added before register allocation.
12359     if (!Subtarget->isTargetWin64()) {
12360       MI->addRegisterDefined(X86::RSI);
12361       MI->addRegisterDefined(X86::RDI);
12362       MI->addRegisterDefined(X86::XMM6);
12363       MI->addRegisterDefined(X86::XMM7);
12364       MI->addRegisterDefined(X86::XMM8);
12365       MI->addRegisterDefined(X86::XMM9);
12366       MI->addRegisterDefined(X86::XMM10);
12367       MI->addRegisterDefined(X86::XMM11);
12368       MI->addRegisterDefined(X86::XMM12);
12369       MI->addRegisterDefined(X86::XMM13);
12370       MI->addRegisterDefined(X86::XMM14);
12371       MI->addRegisterDefined(X86::XMM15);
12372     }
12373     return BB;
12374   case X86::WIN_ALLOCA:
12375     return EmitLoweredWinAlloca(MI, BB);
12376   case X86::SEG_ALLOCA_32:
12377     return EmitLoweredSegAlloca(MI, BB, false);
12378   case X86::SEG_ALLOCA_64:
12379     return EmitLoweredSegAlloca(MI, BB, true);
12380   case X86::TLSCall_32:
12381   case X86::TLSCall_64:
12382     return EmitLoweredTLSCall(MI, BB);
12383   case X86::CMOV_GR8:
12384   case X86::CMOV_FR32:
12385   case X86::CMOV_FR64:
12386   case X86::CMOV_V4F32:
12387   case X86::CMOV_V2F64:
12388   case X86::CMOV_V2I64:
12389   case X86::CMOV_V8F32:
12390   case X86::CMOV_V4F64:
12391   case X86::CMOV_V4I64:
12392   case X86::CMOV_GR16:
12393   case X86::CMOV_GR32:
12394   case X86::CMOV_RFP32:
12395   case X86::CMOV_RFP64:
12396   case X86::CMOV_RFP80:
12397     return EmitLoweredSelect(MI, BB);
12398
12399   case X86::FP32_TO_INT16_IN_MEM:
12400   case X86::FP32_TO_INT32_IN_MEM:
12401   case X86::FP32_TO_INT64_IN_MEM:
12402   case X86::FP64_TO_INT16_IN_MEM:
12403   case X86::FP64_TO_INT32_IN_MEM:
12404   case X86::FP64_TO_INT64_IN_MEM:
12405   case X86::FP80_TO_INT16_IN_MEM:
12406   case X86::FP80_TO_INT32_IN_MEM:
12407   case X86::FP80_TO_INT64_IN_MEM: {
12408     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12409     DebugLoc DL = MI->getDebugLoc();
12410
12411     // Change the floating point control register to use "round towards zero"
12412     // mode when truncating to an integer value.
12413     MachineFunction *F = BB->getParent();
12414     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12415     addFrameReference(BuildMI(*BB, MI, DL,
12416                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12417
12418     // Load the old value of the high byte of the control word...
12419     unsigned OldCW =
12420       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12421     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12422                       CWFrameIdx);
12423
12424     // Set the high part to be round to zero...
12425     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12426       .addImm(0xC7F);
12427
12428     // Reload the modified control word now...
12429     addFrameReference(BuildMI(*BB, MI, DL,
12430                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12431
12432     // Restore the memory image of control word to original value
12433     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12434       .addReg(OldCW);
12435
12436     // Get the X86 opcode to use.
12437     unsigned Opc;
12438     switch (MI->getOpcode()) {
12439     default: llvm_unreachable("illegal opcode!");
12440     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12441     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12442     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12443     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12444     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12445     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12446     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12447     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12448     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12449     }
12450
12451     X86AddressMode AM;
12452     MachineOperand &Op = MI->getOperand(0);
12453     if (Op.isReg()) {
12454       AM.BaseType = X86AddressMode::RegBase;
12455       AM.Base.Reg = Op.getReg();
12456     } else {
12457       AM.BaseType = X86AddressMode::FrameIndexBase;
12458       AM.Base.FrameIndex = Op.getIndex();
12459     }
12460     Op = MI->getOperand(1);
12461     if (Op.isImm())
12462       AM.Scale = Op.getImm();
12463     Op = MI->getOperand(2);
12464     if (Op.isImm())
12465       AM.IndexReg = Op.getImm();
12466     Op = MI->getOperand(3);
12467     if (Op.isGlobal()) {
12468       AM.GV = Op.getGlobal();
12469     } else {
12470       AM.Disp = Op.getImm();
12471     }
12472     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12473                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12474
12475     // Reload the original control word now.
12476     addFrameReference(BuildMI(*BB, MI, DL,
12477                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12478
12479     MI->eraseFromParent();   // The pseudo instruction is gone now.
12480     return BB;
12481   }
12482     // String/text processing lowering.
12483   case X86::PCMPISTRM128REG:
12484   case X86::VPCMPISTRM128REG:
12485     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12486   case X86::PCMPISTRM128MEM:
12487   case X86::VPCMPISTRM128MEM:
12488     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12489   case X86::PCMPESTRM128REG:
12490   case X86::VPCMPESTRM128REG:
12491     return EmitPCMP(MI, BB, 5, false /* in mem */);
12492   case X86::PCMPESTRM128MEM:
12493   case X86::VPCMPESTRM128MEM:
12494     return EmitPCMP(MI, BB, 5, true /* in mem */);
12495
12496     // Thread synchronization.
12497   case X86::MONITOR:
12498     return EmitMonitor(MI, BB);
12499   case X86::MWAIT:
12500     return EmitMwait(MI, BB);
12501
12502     // Atomic Lowering.
12503   case X86::ATOMAND32:
12504     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12505                                                X86::AND32ri, X86::MOV32rm,
12506                                                X86::LCMPXCHG32,
12507                                                X86::NOT32r, X86::EAX,
12508                                                X86::GR32RegisterClass);
12509   case X86::ATOMOR32:
12510     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12511                                                X86::OR32ri, X86::MOV32rm,
12512                                                X86::LCMPXCHG32,
12513                                                X86::NOT32r, X86::EAX,
12514                                                X86::GR32RegisterClass);
12515   case X86::ATOMXOR32:
12516     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12517                                                X86::XOR32ri, X86::MOV32rm,
12518                                                X86::LCMPXCHG32,
12519                                                X86::NOT32r, X86::EAX,
12520                                                X86::GR32RegisterClass);
12521   case X86::ATOMNAND32:
12522     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12523                                                X86::AND32ri, X86::MOV32rm,
12524                                                X86::LCMPXCHG32,
12525                                                X86::NOT32r, X86::EAX,
12526                                                X86::GR32RegisterClass, true);
12527   case X86::ATOMMIN32:
12528     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12529   case X86::ATOMMAX32:
12530     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12531   case X86::ATOMUMIN32:
12532     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12533   case X86::ATOMUMAX32:
12534     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12535
12536   case X86::ATOMAND16:
12537     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12538                                                X86::AND16ri, X86::MOV16rm,
12539                                                X86::LCMPXCHG16,
12540                                                X86::NOT16r, X86::AX,
12541                                                X86::GR16RegisterClass);
12542   case X86::ATOMOR16:
12543     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12544                                                X86::OR16ri, X86::MOV16rm,
12545                                                X86::LCMPXCHG16,
12546                                                X86::NOT16r, X86::AX,
12547                                                X86::GR16RegisterClass);
12548   case X86::ATOMXOR16:
12549     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12550                                                X86::XOR16ri, X86::MOV16rm,
12551                                                X86::LCMPXCHG16,
12552                                                X86::NOT16r, X86::AX,
12553                                                X86::GR16RegisterClass);
12554   case X86::ATOMNAND16:
12555     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12556                                                X86::AND16ri, X86::MOV16rm,
12557                                                X86::LCMPXCHG16,
12558                                                X86::NOT16r, X86::AX,
12559                                                X86::GR16RegisterClass, true);
12560   case X86::ATOMMIN16:
12561     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12562   case X86::ATOMMAX16:
12563     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12564   case X86::ATOMUMIN16:
12565     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12566   case X86::ATOMUMAX16:
12567     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12568
12569   case X86::ATOMAND8:
12570     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12571                                                X86::AND8ri, X86::MOV8rm,
12572                                                X86::LCMPXCHG8,
12573                                                X86::NOT8r, X86::AL,
12574                                                X86::GR8RegisterClass);
12575   case X86::ATOMOR8:
12576     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12577                                                X86::OR8ri, X86::MOV8rm,
12578                                                X86::LCMPXCHG8,
12579                                                X86::NOT8r, X86::AL,
12580                                                X86::GR8RegisterClass);
12581   case X86::ATOMXOR8:
12582     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12583                                                X86::XOR8ri, X86::MOV8rm,
12584                                                X86::LCMPXCHG8,
12585                                                X86::NOT8r, X86::AL,
12586                                                X86::GR8RegisterClass);
12587   case X86::ATOMNAND8:
12588     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12589                                                X86::AND8ri, X86::MOV8rm,
12590                                                X86::LCMPXCHG8,
12591                                                X86::NOT8r, X86::AL,
12592                                                X86::GR8RegisterClass, true);
12593   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12594   // This group is for 64-bit host.
12595   case X86::ATOMAND64:
12596     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12597                                                X86::AND64ri32, X86::MOV64rm,
12598                                                X86::LCMPXCHG64,
12599                                                X86::NOT64r, X86::RAX,
12600                                                X86::GR64RegisterClass);
12601   case X86::ATOMOR64:
12602     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12603                                                X86::OR64ri32, X86::MOV64rm,
12604                                                X86::LCMPXCHG64,
12605                                                X86::NOT64r, X86::RAX,
12606                                                X86::GR64RegisterClass);
12607   case X86::ATOMXOR64:
12608     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12609                                                X86::XOR64ri32, X86::MOV64rm,
12610                                                X86::LCMPXCHG64,
12611                                                X86::NOT64r, X86::RAX,
12612                                                X86::GR64RegisterClass);
12613   case X86::ATOMNAND64:
12614     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12615                                                X86::AND64ri32, X86::MOV64rm,
12616                                                X86::LCMPXCHG64,
12617                                                X86::NOT64r, X86::RAX,
12618                                                X86::GR64RegisterClass, true);
12619   case X86::ATOMMIN64:
12620     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12621   case X86::ATOMMAX64:
12622     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12623   case X86::ATOMUMIN64:
12624     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12625   case X86::ATOMUMAX64:
12626     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12627
12628   // This group does 64-bit operations on a 32-bit host.
12629   case X86::ATOMAND6432:
12630     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12631                                                X86::AND32rr, X86::AND32rr,
12632                                                X86::AND32ri, X86::AND32ri,
12633                                                false);
12634   case X86::ATOMOR6432:
12635     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12636                                                X86::OR32rr, X86::OR32rr,
12637                                                X86::OR32ri, X86::OR32ri,
12638                                                false);
12639   case X86::ATOMXOR6432:
12640     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12641                                                X86::XOR32rr, X86::XOR32rr,
12642                                                X86::XOR32ri, X86::XOR32ri,
12643                                                false);
12644   case X86::ATOMNAND6432:
12645     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12646                                                X86::AND32rr, X86::AND32rr,
12647                                                X86::AND32ri, X86::AND32ri,
12648                                                true);
12649   case X86::ATOMADD6432:
12650     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12651                                                X86::ADD32rr, X86::ADC32rr,
12652                                                X86::ADD32ri, X86::ADC32ri,
12653                                                false);
12654   case X86::ATOMSUB6432:
12655     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12656                                                X86::SUB32rr, X86::SBB32rr,
12657                                                X86::SUB32ri, X86::SBB32ri,
12658                                                false);
12659   case X86::ATOMSWAP6432:
12660     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12661                                                X86::MOV32rr, X86::MOV32rr,
12662                                                X86::MOV32ri, X86::MOV32ri,
12663                                                false);
12664   case X86::VASTART_SAVE_XMM_REGS:
12665     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12666
12667   case X86::VAARG_64:
12668     return EmitVAARG64WithCustomInserter(MI, BB);
12669   }
12670 }
12671
12672 //===----------------------------------------------------------------------===//
12673 //                           X86 Optimization Hooks
12674 //===----------------------------------------------------------------------===//
12675
12676 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12677                                                        const APInt &Mask,
12678                                                        APInt &KnownZero,
12679                                                        APInt &KnownOne,
12680                                                        const SelectionDAG &DAG,
12681                                                        unsigned Depth) const {
12682   unsigned Opc = Op.getOpcode();
12683   assert((Opc >= ISD::BUILTIN_OP_END ||
12684           Opc == ISD::INTRINSIC_WO_CHAIN ||
12685           Opc == ISD::INTRINSIC_W_CHAIN ||
12686           Opc == ISD::INTRINSIC_VOID) &&
12687          "Should use MaskedValueIsZero if you don't know whether Op"
12688          " is a target node!");
12689
12690   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12691   switch (Opc) {
12692   default: break;
12693   case X86ISD::ADD:
12694   case X86ISD::SUB:
12695   case X86ISD::ADC:
12696   case X86ISD::SBB:
12697   case X86ISD::SMUL:
12698   case X86ISD::UMUL:
12699   case X86ISD::INC:
12700   case X86ISD::DEC:
12701   case X86ISD::OR:
12702   case X86ISD::XOR:
12703   case X86ISD::AND:
12704     // These nodes' second result is a boolean.
12705     if (Op.getResNo() == 0)
12706       break;
12707     // Fallthrough
12708   case X86ISD::SETCC:
12709     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12710                                        Mask.getBitWidth() - 1);
12711     break;
12712   case ISD::INTRINSIC_WO_CHAIN: {
12713     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12714     unsigned NumLoBits = 0;
12715     switch (IntId) {
12716     default: break;
12717     case Intrinsic::x86_sse_movmsk_ps:
12718     case Intrinsic::x86_avx_movmsk_ps_256:
12719     case Intrinsic::x86_sse2_movmsk_pd:
12720     case Intrinsic::x86_avx_movmsk_pd_256:
12721     case Intrinsic::x86_mmx_pmovmskb:
12722     case Intrinsic::x86_sse2_pmovmskb_128: {
12723       // High bits of movmskp{s|d}, pmovmskb are known zero.
12724       switch (IntId) {
12725         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12726         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12727         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12728         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12729         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12730         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12731       }
12732       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12733                                         Mask.getBitWidth() - NumLoBits);
12734       break;
12735     }
12736     }
12737     break;
12738   }
12739   }
12740 }
12741
12742 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12743                                                          unsigned Depth) const {
12744   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12745   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12746     return Op.getValueType().getScalarType().getSizeInBits();
12747
12748   // Fallback case.
12749   return 1;
12750 }
12751
12752 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12753 /// node is a GlobalAddress + offset.
12754 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12755                                        const GlobalValue* &GA,
12756                                        int64_t &Offset) const {
12757   if (N->getOpcode() == X86ISD::Wrapper) {
12758     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12759       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12760       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12761       return true;
12762     }
12763   }
12764   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12765 }
12766
12767 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12768 /// same as extracting the high 128-bit part of 256-bit vector and then
12769 /// inserting the result into the low part of a new 256-bit vector
12770 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12771   EVT VT = SVOp->getValueType(0);
12772   int NumElems = VT.getVectorNumElements();
12773
12774   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12775   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12776     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12777         SVOp->getMaskElt(j) >= 0)
12778       return false;
12779
12780   return true;
12781 }
12782
12783 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12784 /// same as extracting the low 128-bit part of 256-bit vector and then
12785 /// inserting the result into the high part of a new 256-bit vector
12786 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12787   EVT VT = SVOp->getValueType(0);
12788   int NumElems = VT.getVectorNumElements();
12789
12790   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12791   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12792     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12793         SVOp->getMaskElt(j) >= 0)
12794       return false;
12795
12796   return true;
12797 }
12798
12799 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12800 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12801                                         TargetLowering::DAGCombinerInfo &DCI) {
12802   DebugLoc dl = N->getDebugLoc();
12803   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12804   SDValue V1 = SVOp->getOperand(0);
12805   SDValue V2 = SVOp->getOperand(1);
12806   EVT VT = SVOp->getValueType(0);
12807   int NumElems = VT.getVectorNumElements();
12808
12809   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12810       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12811     //
12812     //                   0,0,0,...
12813     //                      |
12814     //    V      UNDEF    BUILD_VECTOR    UNDEF
12815     //     \      /           \           /
12816     //  CONCAT_VECTOR         CONCAT_VECTOR
12817     //         \                  /
12818     //          \                /
12819     //          RESULT: V + zero extended
12820     //
12821     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12822         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12823         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12824       return SDValue();
12825
12826     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12827       return SDValue();
12828
12829     // To match the shuffle mask, the first half of the mask should
12830     // be exactly the first vector, and all the rest a splat with the
12831     // first element of the second one.
12832     for (int i = 0; i < NumElems/2; ++i)
12833       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12834           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12835         return SDValue();
12836
12837     // Emit a zeroed vector and insert the desired subvector on its
12838     // first half.
12839     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12840     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12841                          DAG.getConstant(0, MVT::i32), DAG, dl);
12842     return DCI.CombineTo(N, InsV);
12843   }
12844
12845   //===--------------------------------------------------------------------===//
12846   // Combine some shuffles into subvector extracts and inserts:
12847   //
12848
12849   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12850   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12851     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12852                                     DAG, dl);
12853     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12854                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12855     return DCI.CombineTo(N, InsV);
12856   }
12857
12858   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12859   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12860     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12861     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12862                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12863     return DCI.CombineTo(N, InsV);
12864   }
12865
12866   return SDValue();
12867 }
12868
12869 /// PerformShuffleCombine - Performs several different shuffle combines.
12870 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12871                                      TargetLowering::DAGCombinerInfo &DCI,
12872                                      const X86Subtarget *Subtarget) {
12873   DebugLoc dl = N->getDebugLoc();
12874   EVT VT = N->getValueType(0);
12875
12876   // Don't create instructions with illegal types after legalize types has run.
12877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12878   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12879     return SDValue();
12880
12881   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12882   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12883       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12884     return PerformShuffleCombine256(N, DAG, DCI);
12885
12886   // Only handle 128 wide vector from here on.
12887   if (VT.getSizeInBits() != 128)
12888     return SDValue();
12889
12890   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12891   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12892   // consecutive, non-overlapping, and in the right order.
12893   SmallVector<SDValue, 16> Elts;
12894   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12895     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12896
12897   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12898 }
12899
12900 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12901 /// generation and convert it from being a bunch of shuffles and extracts
12902 /// to a simple store and scalar loads to extract the elements.
12903 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12904                                                 const TargetLowering &TLI) {
12905   SDValue InputVector = N->getOperand(0);
12906
12907   // Only operate on vectors of 4 elements, where the alternative shuffling
12908   // gets to be more expensive.
12909   if (InputVector.getValueType() != MVT::v4i32)
12910     return SDValue();
12911
12912   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12913   // single use which is a sign-extend or zero-extend, and all elements are
12914   // used.
12915   SmallVector<SDNode *, 4> Uses;
12916   unsigned ExtractedElements = 0;
12917   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12918        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12919     if (UI.getUse().getResNo() != InputVector.getResNo())
12920       return SDValue();
12921
12922     SDNode *Extract = *UI;
12923     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12924       return SDValue();
12925
12926     if (Extract->getValueType(0) != MVT::i32)
12927       return SDValue();
12928     if (!Extract->hasOneUse())
12929       return SDValue();
12930     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12931         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12932       return SDValue();
12933     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12934       return SDValue();
12935
12936     // Record which element was extracted.
12937     ExtractedElements |=
12938       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12939
12940     Uses.push_back(Extract);
12941   }
12942
12943   // If not all the elements were used, this may not be worthwhile.
12944   if (ExtractedElements != 15)
12945     return SDValue();
12946
12947   // Ok, we've now decided to do the transformation.
12948   DebugLoc dl = InputVector.getDebugLoc();
12949
12950   // Store the value to a temporary stack slot.
12951   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12952   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12953                             MachinePointerInfo(), false, false, 0);
12954
12955   // Replace each use (extract) with a load of the appropriate element.
12956   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12957        UE = Uses.end(); UI != UE; ++UI) {
12958     SDNode *Extract = *UI;
12959
12960     // cOMpute the element's address.
12961     SDValue Idx = Extract->getOperand(1);
12962     unsigned EltSize =
12963         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12964     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12965     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12966
12967     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12968                                      StackPtr, OffsetVal);
12969
12970     // Load the scalar.
12971     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12972                                      ScalarAddr, MachinePointerInfo(),
12973                                      false, false, false, 0);
12974
12975     // Replace the exact with the load.
12976     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12977   }
12978
12979   // The replacement was made in place; don't return anything.
12980   return SDValue();
12981 }
12982
12983 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12984 /// nodes.
12985 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12986                                     const X86Subtarget *Subtarget) {
12987   DebugLoc DL = N->getDebugLoc();
12988   SDValue Cond = N->getOperand(0);
12989   // Get the LHS/RHS of the select.
12990   SDValue LHS = N->getOperand(1);
12991   SDValue RHS = N->getOperand(2);
12992   EVT VT = LHS.getValueType();
12993
12994   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12995   // instructions match the semantics of the common C idiom x<y?x:y but not
12996   // x<=y?x:y, because of how they handle negative zero (which can be
12997   // ignored in unsafe-math mode).
12998   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12999       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13000       (Subtarget->hasXMMInt() ||
13001        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13002     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13003
13004     unsigned Opcode = 0;
13005     // Check for x CC y ? x : y.
13006     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13007         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13008       switch (CC) {
13009       default: break;
13010       case ISD::SETULT:
13011         // Converting this to a min would handle NaNs incorrectly, and swapping
13012         // the operands would cause it to handle comparisons between positive
13013         // and negative zero incorrectly.
13014         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13015           if (!UnsafeFPMath &&
13016               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13017             break;
13018           std::swap(LHS, RHS);
13019         }
13020         Opcode = X86ISD::FMIN;
13021         break;
13022       case ISD::SETOLE:
13023         // Converting this to a min would handle comparisons between positive
13024         // and negative zero incorrectly.
13025         if (!UnsafeFPMath &&
13026             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13027           break;
13028         Opcode = X86ISD::FMIN;
13029         break;
13030       case ISD::SETULE:
13031         // Converting this to a min would handle both negative zeros and NaNs
13032         // incorrectly, but we can swap the operands to fix both.
13033         std::swap(LHS, RHS);
13034       case ISD::SETOLT:
13035       case ISD::SETLT:
13036       case ISD::SETLE:
13037         Opcode = X86ISD::FMIN;
13038         break;
13039
13040       case ISD::SETOGE:
13041         // Converting this to a max would handle comparisons between positive
13042         // and negative zero incorrectly.
13043         if (!UnsafeFPMath &&
13044             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13045           break;
13046         Opcode = X86ISD::FMAX;
13047         break;
13048       case ISD::SETUGT:
13049         // Converting this to a max would handle NaNs incorrectly, and swapping
13050         // the operands would cause it to handle comparisons between positive
13051         // and negative zero incorrectly.
13052         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13053           if (!UnsafeFPMath &&
13054               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13055             break;
13056           std::swap(LHS, RHS);
13057         }
13058         Opcode = X86ISD::FMAX;
13059         break;
13060       case ISD::SETUGE:
13061         // Converting this to a max would handle both negative zeros and NaNs
13062         // incorrectly, but we can swap the operands to fix both.
13063         std::swap(LHS, RHS);
13064       case ISD::SETOGT:
13065       case ISD::SETGT:
13066       case ISD::SETGE:
13067         Opcode = X86ISD::FMAX;
13068         break;
13069       }
13070     // Check for x CC y ? y : x -- a min/max with reversed arms.
13071     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13072                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13073       switch (CC) {
13074       default: break;
13075       case ISD::SETOGE:
13076         // Converting this to a min would handle comparisons between positive
13077         // and negative zero incorrectly, and swapping the operands would
13078         // cause it to handle NaNs incorrectly.
13079         if (!UnsafeFPMath &&
13080             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13081           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13082             break;
13083           std::swap(LHS, RHS);
13084         }
13085         Opcode = X86ISD::FMIN;
13086         break;
13087       case ISD::SETUGT:
13088         // Converting this to a min would handle NaNs incorrectly.
13089         if (!UnsafeFPMath &&
13090             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13091           break;
13092         Opcode = X86ISD::FMIN;
13093         break;
13094       case ISD::SETUGE:
13095         // Converting this to a min would handle both negative zeros and NaNs
13096         // incorrectly, but we can swap the operands to fix both.
13097         std::swap(LHS, RHS);
13098       case ISD::SETOGT:
13099       case ISD::SETGT:
13100       case ISD::SETGE:
13101         Opcode = X86ISD::FMIN;
13102         break;
13103
13104       case ISD::SETULT:
13105         // Converting this to a max would handle NaNs incorrectly.
13106         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13107           break;
13108         Opcode = X86ISD::FMAX;
13109         break;
13110       case ISD::SETOLE:
13111         // Converting this to a max would handle comparisons between positive
13112         // and negative zero incorrectly, and swapping the operands would
13113         // cause it to handle NaNs incorrectly.
13114         if (!UnsafeFPMath &&
13115             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13116           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13117             break;
13118           std::swap(LHS, RHS);
13119         }
13120         Opcode = X86ISD::FMAX;
13121         break;
13122       case ISD::SETULE:
13123         // Converting this to a max would handle both negative zeros and NaNs
13124         // incorrectly, but we can swap the operands to fix both.
13125         std::swap(LHS, RHS);
13126       case ISD::SETOLT:
13127       case ISD::SETLT:
13128       case ISD::SETLE:
13129         Opcode = X86ISD::FMAX;
13130         break;
13131       }
13132     }
13133
13134     if (Opcode)
13135       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13136   }
13137
13138   // If this is a select between two integer constants, try to do some
13139   // optimizations.
13140   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13141     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13142       // Don't do this for crazy integer types.
13143       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13144         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13145         // so that TrueC (the true value) is larger than FalseC.
13146         bool NeedsCondInvert = false;
13147
13148         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13149             // Efficiently invertible.
13150             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13151              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13152               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13153           NeedsCondInvert = true;
13154           std::swap(TrueC, FalseC);
13155         }
13156
13157         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13158         if (FalseC->getAPIntValue() == 0 &&
13159             TrueC->getAPIntValue().isPowerOf2()) {
13160           if (NeedsCondInvert) // Invert the condition if needed.
13161             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13162                                DAG.getConstant(1, Cond.getValueType()));
13163
13164           // Zero extend the condition if needed.
13165           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13166
13167           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13168           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13169                              DAG.getConstant(ShAmt, MVT::i8));
13170         }
13171
13172         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13173         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13174           if (NeedsCondInvert) // Invert the condition if needed.
13175             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13176                                DAG.getConstant(1, Cond.getValueType()));
13177
13178           // Zero extend the condition if needed.
13179           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13180                              FalseC->getValueType(0), Cond);
13181           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13182                              SDValue(FalseC, 0));
13183         }
13184
13185         // Optimize cases that will turn into an LEA instruction.  This requires
13186         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13187         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13188           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13189           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13190
13191           bool isFastMultiplier = false;
13192           if (Diff < 10) {
13193             switch ((unsigned char)Diff) {
13194               default: break;
13195               case 1:  // result = add base, cond
13196               case 2:  // result = lea base(    , cond*2)
13197               case 3:  // result = lea base(cond, cond*2)
13198               case 4:  // result = lea base(    , cond*4)
13199               case 5:  // result = lea base(cond, cond*4)
13200               case 8:  // result = lea base(    , cond*8)
13201               case 9:  // result = lea base(cond, cond*8)
13202                 isFastMultiplier = true;
13203                 break;
13204             }
13205           }
13206
13207           if (isFastMultiplier) {
13208             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13209             if (NeedsCondInvert) // Invert the condition if needed.
13210               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13211                                  DAG.getConstant(1, Cond.getValueType()));
13212
13213             // Zero extend the condition if needed.
13214             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13215                                Cond);
13216             // Scale the condition by the difference.
13217             if (Diff != 1)
13218               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13219                                  DAG.getConstant(Diff, Cond.getValueType()));
13220
13221             // Add the base if non-zero.
13222             if (FalseC->getAPIntValue() != 0)
13223               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13224                                  SDValue(FalseC, 0));
13225             return Cond;
13226           }
13227         }
13228       }
13229   }
13230
13231   return SDValue();
13232 }
13233
13234 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13235 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13236                                   TargetLowering::DAGCombinerInfo &DCI) {
13237   DebugLoc DL = N->getDebugLoc();
13238
13239   // If the flag operand isn't dead, don't touch this CMOV.
13240   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13241     return SDValue();
13242
13243   SDValue FalseOp = N->getOperand(0);
13244   SDValue TrueOp = N->getOperand(1);
13245   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13246   SDValue Cond = N->getOperand(3);
13247   if (CC == X86::COND_E || CC == X86::COND_NE) {
13248     switch (Cond.getOpcode()) {
13249     default: break;
13250     case X86ISD::BSR:
13251     case X86ISD::BSF:
13252       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13253       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13254         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13255     }
13256   }
13257
13258   // If this is a select between two integer constants, try to do some
13259   // optimizations.  Note that the operands are ordered the opposite of SELECT
13260   // operands.
13261   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13262     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13263       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13264       // larger than FalseC (the false value).
13265       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13266         CC = X86::GetOppositeBranchCondition(CC);
13267         std::swap(TrueC, FalseC);
13268       }
13269
13270       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13271       // This is efficient for any integer data type (including i8/i16) and
13272       // shift amount.
13273       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13274         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13275                            DAG.getConstant(CC, MVT::i8), Cond);
13276
13277         // Zero extend the condition if needed.
13278         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13279
13280         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13281         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13282                            DAG.getConstant(ShAmt, MVT::i8));
13283         if (N->getNumValues() == 2)  // Dead flag value?
13284           return DCI.CombineTo(N, Cond, SDValue());
13285         return Cond;
13286       }
13287
13288       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13289       // for any integer data type, including i8/i16.
13290       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13291         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13292                            DAG.getConstant(CC, MVT::i8), Cond);
13293
13294         // Zero extend the condition if needed.
13295         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13296                            FalseC->getValueType(0), Cond);
13297         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13298                            SDValue(FalseC, 0));
13299
13300         if (N->getNumValues() == 2)  // Dead flag value?
13301           return DCI.CombineTo(N, Cond, SDValue());
13302         return Cond;
13303       }
13304
13305       // Optimize cases that will turn into an LEA instruction.  This requires
13306       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13307       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13308         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13309         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13310
13311         bool isFastMultiplier = false;
13312         if (Diff < 10) {
13313           switch ((unsigned char)Diff) {
13314           default: break;
13315           case 1:  // result = add base, cond
13316           case 2:  // result = lea base(    , cond*2)
13317           case 3:  // result = lea base(cond, cond*2)
13318           case 4:  // result = lea base(    , cond*4)
13319           case 5:  // result = lea base(cond, cond*4)
13320           case 8:  // result = lea base(    , cond*8)
13321           case 9:  // result = lea base(cond, cond*8)
13322             isFastMultiplier = true;
13323             break;
13324           }
13325         }
13326
13327         if (isFastMultiplier) {
13328           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13329           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13330                              DAG.getConstant(CC, MVT::i8), Cond);
13331           // Zero extend the condition if needed.
13332           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13333                              Cond);
13334           // Scale the condition by the difference.
13335           if (Diff != 1)
13336             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13337                                DAG.getConstant(Diff, Cond.getValueType()));
13338
13339           // Add the base if non-zero.
13340           if (FalseC->getAPIntValue() != 0)
13341             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13342                                SDValue(FalseC, 0));
13343           if (N->getNumValues() == 2)  // Dead flag value?
13344             return DCI.CombineTo(N, Cond, SDValue());
13345           return Cond;
13346         }
13347       }
13348     }
13349   }
13350   return SDValue();
13351 }
13352
13353
13354 /// PerformMulCombine - Optimize a single multiply with constant into two
13355 /// in order to implement it with two cheaper instructions, e.g.
13356 /// LEA + SHL, LEA + LEA.
13357 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13358                                  TargetLowering::DAGCombinerInfo &DCI) {
13359   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13360     return SDValue();
13361
13362   EVT VT = N->getValueType(0);
13363   if (VT != MVT::i64)
13364     return SDValue();
13365
13366   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13367   if (!C)
13368     return SDValue();
13369   uint64_t MulAmt = C->getZExtValue();
13370   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13371     return SDValue();
13372
13373   uint64_t MulAmt1 = 0;
13374   uint64_t MulAmt2 = 0;
13375   if ((MulAmt % 9) == 0) {
13376     MulAmt1 = 9;
13377     MulAmt2 = MulAmt / 9;
13378   } else if ((MulAmt % 5) == 0) {
13379     MulAmt1 = 5;
13380     MulAmt2 = MulAmt / 5;
13381   } else if ((MulAmt % 3) == 0) {
13382     MulAmt1 = 3;
13383     MulAmt2 = MulAmt / 3;
13384   }
13385   if (MulAmt2 &&
13386       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13387     DebugLoc DL = N->getDebugLoc();
13388
13389     if (isPowerOf2_64(MulAmt2) &&
13390         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13391       // If second multiplifer is pow2, issue it first. We want the multiply by
13392       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13393       // is an add.
13394       std::swap(MulAmt1, MulAmt2);
13395
13396     SDValue NewMul;
13397     if (isPowerOf2_64(MulAmt1))
13398       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13399                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13400     else
13401       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13402                            DAG.getConstant(MulAmt1, VT));
13403
13404     if (isPowerOf2_64(MulAmt2))
13405       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13406                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13407     else
13408       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13409                            DAG.getConstant(MulAmt2, VT));
13410
13411     // Do not add new nodes to DAG combiner worklist.
13412     DCI.CombineTo(N, NewMul, false);
13413   }
13414   return SDValue();
13415 }
13416
13417 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13418   SDValue N0 = N->getOperand(0);
13419   SDValue N1 = N->getOperand(1);
13420   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13421   EVT VT = N0.getValueType();
13422
13423   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13424   // since the result of setcc_c is all zero's or all ones.
13425   if (VT.isInteger() && !VT.isVector() &&
13426       N1C && N0.getOpcode() == ISD::AND &&
13427       N0.getOperand(1).getOpcode() == ISD::Constant) {
13428     SDValue N00 = N0.getOperand(0);
13429     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13430         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13431           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13432          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13433       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13434       APInt ShAmt = N1C->getAPIntValue();
13435       Mask = Mask.shl(ShAmt);
13436       if (Mask != 0)
13437         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13438                            N00, DAG.getConstant(Mask, VT));
13439     }
13440   }
13441
13442
13443   // Hardware support for vector shifts is sparse which makes us scalarize the
13444   // vector operations in many cases. Also, on sandybridge ADD is faster than
13445   // shl.
13446   // (shl V, 1) -> add V,V
13447   if (isSplatVector(N1.getNode())) {
13448     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13449     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13450     // We shift all of the values by one. In many cases we do not have
13451     // hardware support for this operation. This is better expressed as an ADD
13452     // of two values.
13453     if (N1C && (1 == N1C->getZExtValue())) {
13454       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13455     }
13456   }
13457
13458   return SDValue();
13459 }
13460
13461 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13462 ///                       when possible.
13463 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13464                                    const X86Subtarget *Subtarget) {
13465   EVT VT = N->getValueType(0);
13466   if (N->getOpcode() == ISD::SHL) {
13467     SDValue V = PerformSHLCombine(N, DAG);
13468     if (V.getNode()) return V;
13469   }
13470
13471   // On X86 with SSE2 support, we can transform this to a vector shift if
13472   // all elements are shifted by the same amount.  We can't do this in legalize
13473   // because the a constant vector is typically transformed to a constant pool
13474   // so we have no knowledge of the shift amount.
13475   if (!Subtarget->hasXMMInt())
13476     return SDValue();
13477
13478   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13479       (!Subtarget->hasAVX2() ||
13480        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13481     return SDValue();
13482
13483   SDValue ShAmtOp = N->getOperand(1);
13484   EVT EltVT = VT.getVectorElementType();
13485   DebugLoc DL = N->getDebugLoc();
13486   SDValue BaseShAmt = SDValue();
13487   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13488     unsigned NumElts = VT.getVectorNumElements();
13489     unsigned i = 0;
13490     for (; i != NumElts; ++i) {
13491       SDValue Arg = ShAmtOp.getOperand(i);
13492       if (Arg.getOpcode() == ISD::UNDEF) continue;
13493       BaseShAmt = Arg;
13494       break;
13495     }
13496     for (; i != NumElts; ++i) {
13497       SDValue Arg = ShAmtOp.getOperand(i);
13498       if (Arg.getOpcode() == ISD::UNDEF) continue;
13499       if (Arg != BaseShAmt) {
13500         return SDValue();
13501       }
13502     }
13503   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13504              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13505     SDValue InVec = ShAmtOp.getOperand(0);
13506     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13507       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13508       unsigned i = 0;
13509       for (; i != NumElts; ++i) {
13510         SDValue Arg = InVec.getOperand(i);
13511         if (Arg.getOpcode() == ISD::UNDEF) continue;
13512         BaseShAmt = Arg;
13513         break;
13514       }
13515     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13516        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13517          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13518          if (C->getZExtValue() == SplatIdx)
13519            BaseShAmt = InVec.getOperand(1);
13520        }
13521     }
13522     if (BaseShAmt.getNode() == 0)
13523       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13524                               DAG.getIntPtrConstant(0));
13525   } else
13526     return SDValue();
13527
13528   // The shift amount is an i32.
13529   if (EltVT.bitsGT(MVT::i32))
13530     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13531   else if (EltVT.bitsLT(MVT::i32))
13532     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13533
13534   // The shift amount is identical so we can do a vector shift.
13535   SDValue  ValOp = N->getOperand(0);
13536   switch (N->getOpcode()) {
13537   default:
13538     llvm_unreachable("Unknown shift opcode!");
13539     break;
13540   case ISD::SHL:
13541     if (VT == MVT::v2i64)
13542       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13543                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13544                          ValOp, BaseShAmt);
13545     if (VT == MVT::v4i32)
13546       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13547                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13548                          ValOp, BaseShAmt);
13549     if (VT == MVT::v8i16)
13550       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13551                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13552                          ValOp, BaseShAmt);
13553     if (VT == MVT::v4i64)
13554       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13555                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13556                          ValOp, BaseShAmt);
13557     if (VT == MVT::v8i32)
13558       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13559                          DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13560                          ValOp, BaseShAmt);
13561     if (VT == MVT::v16i16)
13562       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13563                          DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13564                          ValOp, BaseShAmt);
13565     break;
13566   case ISD::SRA:
13567     if (VT == MVT::v4i32)
13568       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13569                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13570                          ValOp, BaseShAmt);
13571     if (VT == MVT::v8i16)
13572       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13573                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13574                          ValOp, BaseShAmt);
13575     if (VT == MVT::v8i32)
13576       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13577                          DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13578                          ValOp, BaseShAmt);
13579     if (VT == MVT::v16i16)
13580       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13581                          DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13582                          ValOp, BaseShAmt);
13583     break;
13584   case ISD::SRL:
13585     if (VT == MVT::v2i64)
13586       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13587                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13588                          ValOp, BaseShAmt);
13589     if (VT == MVT::v4i32)
13590       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13591                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13592                          ValOp, BaseShAmt);
13593     if (VT ==  MVT::v8i16)
13594       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13595                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13596                          ValOp, BaseShAmt);
13597     if (VT == MVT::v4i64)
13598       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13599                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13600                          ValOp, BaseShAmt);
13601     if (VT == MVT::v8i32)
13602       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13603                          DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13604                          ValOp, BaseShAmt);
13605     if (VT ==  MVT::v16i16)
13606       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13607                          DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13608                          ValOp, BaseShAmt);
13609     break;
13610   }
13611   return SDValue();
13612 }
13613
13614
13615 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13616 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13617 // and friends.  Likewise for OR -> CMPNEQSS.
13618 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13619                             TargetLowering::DAGCombinerInfo &DCI,
13620                             const X86Subtarget *Subtarget) {
13621   unsigned opcode;
13622
13623   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13624   // we're requiring SSE2 for both.
13625   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13626     SDValue N0 = N->getOperand(0);
13627     SDValue N1 = N->getOperand(1);
13628     SDValue CMP0 = N0->getOperand(1);
13629     SDValue CMP1 = N1->getOperand(1);
13630     DebugLoc DL = N->getDebugLoc();
13631
13632     // The SETCCs should both refer to the same CMP.
13633     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13634       return SDValue();
13635
13636     SDValue CMP00 = CMP0->getOperand(0);
13637     SDValue CMP01 = CMP0->getOperand(1);
13638     EVT     VT    = CMP00.getValueType();
13639
13640     if (VT == MVT::f32 || VT == MVT::f64) {
13641       bool ExpectingFlags = false;
13642       // Check for any users that want flags:
13643       for (SDNode::use_iterator UI = N->use_begin(),
13644              UE = N->use_end();
13645            !ExpectingFlags && UI != UE; ++UI)
13646         switch (UI->getOpcode()) {
13647         default:
13648         case ISD::BR_CC:
13649         case ISD::BRCOND:
13650         case ISD::SELECT:
13651           ExpectingFlags = true;
13652           break;
13653         case ISD::CopyToReg:
13654         case ISD::SIGN_EXTEND:
13655         case ISD::ZERO_EXTEND:
13656         case ISD::ANY_EXTEND:
13657           break;
13658         }
13659
13660       if (!ExpectingFlags) {
13661         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13662         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13663
13664         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13665           X86::CondCode tmp = cc0;
13666           cc0 = cc1;
13667           cc1 = tmp;
13668         }
13669
13670         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13671             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13672           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13673           X86ISD::NodeType NTOperator = is64BitFP ?
13674             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13675           // FIXME: need symbolic constants for these magic numbers.
13676           // See X86ATTInstPrinter.cpp:printSSECC().
13677           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13678           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13679                                               DAG.getConstant(x86cc, MVT::i8));
13680           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13681                                               OnesOrZeroesF);
13682           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13683                                       DAG.getConstant(1, MVT::i32));
13684           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13685           return OneBitOfTruth;
13686         }
13687       }
13688     }
13689   }
13690   return SDValue();
13691 }
13692
13693 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13694 /// so it can be folded inside ANDNP.
13695 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13696   EVT VT = N->getValueType(0);
13697
13698   // Match direct AllOnes for 128 and 256-bit vectors
13699   if (ISD::isBuildVectorAllOnes(N))
13700     return true;
13701
13702   // Look through a bit convert.
13703   if (N->getOpcode() == ISD::BITCAST)
13704     N = N->getOperand(0).getNode();
13705
13706   // Sometimes the operand may come from a insert_subvector building a 256-bit
13707   // allones vector
13708   if (VT.getSizeInBits() == 256 &&
13709       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13710     SDValue V1 = N->getOperand(0);
13711     SDValue V2 = N->getOperand(1);
13712
13713     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13714         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13715         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13716         ISD::isBuildVectorAllOnes(V2.getNode()))
13717       return true;
13718   }
13719
13720   return false;
13721 }
13722
13723 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13724                                  TargetLowering::DAGCombinerInfo &DCI,
13725                                  const X86Subtarget *Subtarget) {
13726   if (DCI.isBeforeLegalizeOps())
13727     return SDValue();
13728
13729   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13730   if (R.getNode())
13731     return R;
13732
13733   EVT VT = N->getValueType(0);
13734
13735   // Create ANDN, BLSI, and BLSR instructions
13736   // BLSI is X & (-X)
13737   // BLSR is X & (X-1)
13738   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13739     SDValue N0 = N->getOperand(0);
13740     SDValue N1 = N->getOperand(1);
13741     DebugLoc DL = N->getDebugLoc();
13742
13743     // Check LHS for not
13744     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13745       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13746     // Check RHS for not
13747     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13748       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13749
13750     // Check LHS for neg
13751     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13752         isZero(N0.getOperand(0)))
13753       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13754
13755     // Check RHS for neg
13756     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13757         isZero(N1.getOperand(0)))
13758       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13759
13760     // Check LHS for X-1
13761     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13762         isAllOnes(N0.getOperand(1)))
13763       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13764
13765     // Check RHS for X-1
13766     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13767         isAllOnes(N1.getOperand(1)))
13768       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13769
13770     return SDValue();
13771   }
13772
13773   // Want to form ANDNP nodes:
13774   // 1) In the hopes of then easily combining them with OR and AND nodes
13775   //    to form PBLEND/PSIGN.
13776   // 2) To match ANDN packed intrinsics
13777   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13778     return SDValue();
13779
13780   SDValue N0 = N->getOperand(0);
13781   SDValue N1 = N->getOperand(1);
13782   DebugLoc DL = N->getDebugLoc();
13783
13784   // Check LHS for vnot
13785   if (N0.getOpcode() == ISD::XOR &&
13786       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13787       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13788     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13789
13790   // Check RHS for vnot
13791   if (N1.getOpcode() == ISD::XOR &&
13792       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13793       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13794     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13795
13796   return SDValue();
13797 }
13798
13799 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13800                                 TargetLowering::DAGCombinerInfo &DCI,
13801                                 const X86Subtarget *Subtarget) {
13802   if (DCI.isBeforeLegalizeOps())
13803     return SDValue();
13804
13805   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13806   if (R.getNode())
13807     return R;
13808
13809   EVT VT = N->getValueType(0);
13810   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13811     return SDValue();
13812
13813   SDValue N0 = N->getOperand(0);
13814   SDValue N1 = N->getOperand(1);
13815
13816   // look for psign/blend
13817   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13818     if (VT == MVT::v2i64) {
13819       // Canonicalize pandn to RHS
13820       if (N0.getOpcode() == X86ISD::ANDNP)
13821         std::swap(N0, N1);
13822       // or (and (m, x), (pandn m, y))
13823       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13824         SDValue Mask = N1.getOperand(0);
13825         SDValue X    = N1.getOperand(1);
13826         SDValue Y;
13827         if (N0.getOperand(0) == Mask)
13828           Y = N0.getOperand(1);
13829         if (N0.getOperand(1) == Mask)
13830           Y = N0.getOperand(0);
13831
13832         // Check to see if the mask appeared in both the AND and ANDNP and
13833         if (!Y.getNode())
13834           return SDValue();
13835
13836         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13837         if (Mask.getOpcode() != ISD::BITCAST ||
13838             X.getOpcode() != ISD::BITCAST ||
13839             Y.getOpcode() != ISD::BITCAST)
13840           return SDValue();
13841
13842         // Look through mask bitcast.
13843         Mask = Mask.getOperand(0);
13844         EVT MaskVT = Mask.getValueType();
13845
13846         // Validate that the Mask operand is a vector sra node.  The sra node
13847         // will be an intrinsic.
13848         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13849           return SDValue();
13850
13851         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13852         // there is no psrai.b
13853         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13854         case Intrinsic::x86_sse2_psrai_w:
13855         case Intrinsic::x86_sse2_psrai_d:
13856           break;
13857         default: return SDValue();
13858         }
13859
13860         // Check that the SRA is all signbits.
13861         SDValue SraC = Mask.getOperand(2);
13862         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13863         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13864         if ((SraAmt + 1) != EltBits)
13865           return SDValue();
13866
13867         DebugLoc DL = N->getDebugLoc();
13868
13869         // Now we know we at least have a plendvb with the mask val.  See if
13870         // we can form a psignb/w/d.
13871         // psign = x.type == y.type == mask.type && y = sub(0, x);
13872         X = X.getOperand(0);
13873         Y = Y.getOperand(0);
13874         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13875             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13876             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13877           unsigned Opc = 0;
13878           switch (EltBits) {
13879           case 8: Opc = X86ISD::PSIGNB; break;
13880           case 16: Opc = X86ISD::PSIGNW; break;
13881           case 32: Opc = X86ISD::PSIGND; break;
13882           default: break;
13883           }
13884           if (Opc) {
13885             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13886             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13887           }
13888         }
13889         // PBLENDVB only available on SSE 4.1
13890         if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13891           return SDValue();
13892
13893         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13894         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13895         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13896         Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13897         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13898       }
13899     }
13900   }
13901
13902   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13903   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13904     std::swap(N0, N1);
13905   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13906     return SDValue();
13907   if (!N0.hasOneUse() || !N1.hasOneUse())
13908     return SDValue();
13909
13910   SDValue ShAmt0 = N0.getOperand(1);
13911   if (ShAmt0.getValueType() != MVT::i8)
13912     return SDValue();
13913   SDValue ShAmt1 = N1.getOperand(1);
13914   if (ShAmt1.getValueType() != MVT::i8)
13915     return SDValue();
13916   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13917     ShAmt0 = ShAmt0.getOperand(0);
13918   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13919     ShAmt1 = ShAmt1.getOperand(0);
13920
13921   DebugLoc DL = N->getDebugLoc();
13922   unsigned Opc = X86ISD::SHLD;
13923   SDValue Op0 = N0.getOperand(0);
13924   SDValue Op1 = N1.getOperand(0);
13925   if (ShAmt0.getOpcode() == ISD::SUB) {
13926     Opc = X86ISD::SHRD;
13927     std::swap(Op0, Op1);
13928     std::swap(ShAmt0, ShAmt1);
13929   }
13930
13931   unsigned Bits = VT.getSizeInBits();
13932   if (ShAmt1.getOpcode() == ISD::SUB) {
13933     SDValue Sum = ShAmt1.getOperand(0);
13934     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13935       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13936       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13937         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13938       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13939         return DAG.getNode(Opc, DL, VT,
13940                            Op0, Op1,
13941                            DAG.getNode(ISD::TRUNCATE, DL,
13942                                        MVT::i8, ShAmt0));
13943     }
13944   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13945     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13946     if (ShAmt0C &&
13947         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13948       return DAG.getNode(Opc, DL, VT,
13949                          N0.getOperand(0), N1.getOperand(0),
13950                          DAG.getNode(ISD::TRUNCATE, DL,
13951                                        MVT::i8, ShAmt0));
13952   }
13953
13954   return SDValue();
13955 }
13956
13957 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13958                                  TargetLowering::DAGCombinerInfo &DCI,
13959                                  const X86Subtarget *Subtarget) {
13960   if (DCI.isBeforeLegalizeOps())
13961     return SDValue();
13962
13963   EVT VT = N->getValueType(0);
13964
13965   if (VT != MVT::i32 && VT != MVT::i64)
13966     return SDValue();
13967
13968   // Create BLSMSK instructions by finding X ^ (X-1)
13969   SDValue N0 = N->getOperand(0);
13970   SDValue N1 = N->getOperand(1);
13971   DebugLoc DL = N->getDebugLoc();
13972
13973   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13974       isAllOnes(N0.getOperand(1)))
13975     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13976
13977   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13978       isAllOnes(N1.getOperand(1)))
13979     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13980
13981   return SDValue();
13982 }
13983
13984 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13985 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13986                                    const X86Subtarget *Subtarget) {
13987   LoadSDNode *Ld = cast<LoadSDNode>(N);
13988   EVT RegVT = Ld->getValueType(0);
13989   EVT MemVT = Ld->getMemoryVT();
13990   DebugLoc dl = Ld->getDebugLoc();
13991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13992
13993   ISD::LoadExtType Ext = Ld->getExtensionType();
13994
13995   // If this is a vector EXT Load then attempt to optimize it using a
13996   // shuffle. We need SSE4 for the shuffles.
13997   // TODO: It is possible to support ZExt by zeroing the undef values
13998   // during the shuffle phase or after the shuffle.
13999   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14000     assert(MemVT != RegVT && "Cannot extend to the same type");
14001     assert(MemVT.isVector() && "Must load a vector from memory");
14002
14003     unsigned NumElems = RegVT.getVectorNumElements();
14004     unsigned RegSz = RegVT.getSizeInBits();
14005     unsigned MemSz = MemVT.getSizeInBits();
14006     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14007     // All sizes must be a power of two
14008     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14009
14010     // Attempt to load the original value using a single load op.
14011     // Find a scalar type which is equal to the loaded word size.
14012     MVT SclrLoadTy = MVT::i8;
14013     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14014          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14015       MVT Tp = (MVT::SimpleValueType)tp;
14016       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14017         SclrLoadTy = Tp;
14018         break;
14019       }
14020     }
14021
14022     // Proceed if a load word is found.
14023     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14024
14025     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14026       RegSz/SclrLoadTy.getSizeInBits());
14027
14028     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14029                                   RegSz/MemVT.getScalarType().getSizeInBits());
14030     // Can't shuffle using an illegal type.
14031     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14032
14033     // Perform a single load.
14034     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14035                                   Ld->getBasePtr(),
14036                                   Ld->getPointerInfo(), Ld->isVolatile(),
14037                                   Ld->isNonTemporal(), Ld->isInvariant(),
14038                                   Ld->getAlignment());
14039
14040     // Insert the word loaded into a vector.
14041     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14042       LoadUnitVecVT, ScalarLoad);
14043
14044     // Bitcast the loaded value to a vector of the original element type, in
14045     // the size of the target vector type.
14046     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14047     unsigned SizeRatio = RegSz/MemSz;
14048
14049     // Redistribute the loaded elements into the different locations.
14050     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14051     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14052
14053     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14054                                 DAG.getUNDEF(SlicedVec.getValueType()),
14055                                 ShuffleVec.data());
14056
14057     // Bitcast to the requested type.
14058     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14059     // Replace the original load with the new sequence
14060     // and return the new chain.
14061     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14062     return SDValue(ScalarLoad.getNode(), 1);
14063   }
14064
14065   return SDValue();
14066 }
14067
14068 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14069 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14070                                    const X86Subtarget *Subtarget) {
14071   StoreSDNode *St = cast<StoreSDNode>(N);
14072   EVT VT = St->getValue().getValueType();
14073   EVT StVT = St->getMemoryVT();
14074   DebugLoc dl = St->getDebugLoc();
14075   SDValue StoredVal = St->getOperand(1);
14076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14077
14078   // If we are saving a concatination of two XMM registers, perform two stores.
14079   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14080   // 128-bit ones. If in the future the cost becomes only one memory access the
14081   // first version would be better.
14082   if (VT.getSizeInBits() == 256 &&
14083     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14084     StoredVal.getNumOperands() == 2) {
14085
14086     SDValue Value0 = StoredVal.getOperand(0);
14087     SDValue Value1 = StoredVal.getOperand(1);
14088
14089     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14090     SDValue Ptr0 = St->getBasePtr();
14091     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14092
14093     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14094                                 St->getPointerInfo(), St->isVolatile(),
14095                                 St->isNonTemporal(), St->getAlignment());
14096     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14097                                 St->getPointerInfo(), St->isVolatile(),
14098                                 St->isNonTemporal(), St->getAlignment());
14099     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14100   }
14101
14102   // Optimize trunc store (of multiple scalars) to shuffle and store.
14103   // First, pack all of the elements in one place. Next, store to memory
14104   // in fewer chunks.
14105   if (St->isTruncatingStore() && VT.isVector()) {
14106     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14107     unsigned NumElems = VT.getVectorNumElements();
14108     assert(StVT != VT && "Cannot truncate to the same type");
14109     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14110     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14111
14112     // From, To sizes and ElemCount must be pow of two
14113     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14114     // We are going to use the original vector elt for storing.
14115     // Accumulated smaller vector elements must be a multiple of the store size.
14116     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14117
14118     unsigned SizeRatio  = FromSz / ToSz;
14119
14120     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14121
14122     // Create a type on which we perform the shuffle
14123     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14124             StVT.getScalarType(), NumElems*SizeRatio);
14125
14126     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14127
14128     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14129     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14130     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14131
14132     // Can't shuffle using an illegal type
14133     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14134
14135     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14136                                 DAG.getUNDEF(WideVec.getValueType()),
14137                                 ShuffleVec.data());
14138     // At this point all of the data is stored at the bottom of the
14139     // register. We now need to save it to mem.
14140
14141     // Find the largest store unit
14142     MVT StoreType = MVT::i8;
14143     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14144          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14145       MVT Tp = (MVT::SimpleValueType)tp;
14146       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14147         StoreType = Tp;
14148     }
14149
14150     // Bitcast the original vector into a vector of store-size units
14151     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14152             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14153     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14154     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14155     SmallVector<SDValue, 8> Chains;
14156     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14157                                         TLI.getPointerTy());
14158     SDValue Ptr = St->getBasePtr();
14159
14160     // Perform one or more big stores into memory.
14161     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14162       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14163                                    StoreType, ShuffWide,
14164                                    DAG.getIntPtrConstant(i));
14165       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14166                                 St->getPointerInfo(), St->isVolatile(),
14167                                 St->isNonTemporal(), St->getAlignment());
14168       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14169       Chains.push_back(Ch);
14170     }
14171
14172     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14173                                Chains.size());
14174   }
14175
14176
14177   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14178   // the FP state in cases where an emms may be missing.
14179   // A preferable solution to the general problem is to figure out the right
14180   // places to insert EMMS.  This qualifies as a quick hack.
14181
14182   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14183   if (VT.getSizeInBits() != 64)
14184     return SDValue();
14185
14186   const Function *F = DAG.getMachineFunction().getFunction();
14187   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14188   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14189                      && Subtarget->hasXMMInt();
14190   if ((VT.isVector() ||
14191        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14192       isa<LoadSDNode>(St->getValue()) &&
14193       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14194       St->getChain().hasOneUse() && !St->isVolatile()) {
14195     SDNode* LdVal = St->getValue().getNode();
14196     LoadSDNode *Ld = 0;
14197     int TokenFactorIndex = -1;
14198     SmallVector<SDValue, 8> Ops;
14199     SDNode* ChainVal = St->getChain().getNode();
14200     // Must be a store of a load.  We currently handle two cases:  the load
14201     // is a direct child, and it's under an intervening TokenFactor.  It is
14202     // possible to dig deeper under nested TokenFactors.
14203     if (ChainVal == LdVal)
14204       Ld = cast<LoadSDNode>(St->getChain());
14205     else if (St->getValue().hasOneUse() &&
14206              ChainVal->getOpcode() == ISD::TokenFactor) {
14207       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14208         if (ChainVal->getOperand(i).getNode() == LdVal) {
14209           TokenFactorIndex = i;
14210           Ld = cast<LoadSDNode>(St->getValue());
14211         } else
14212           Ops.push_back(ChainVal->getOperand(i));
14213       }
14214     }
14215
14216     if (!Ld || !ISD::isNormalLoad(Ld))
14217       return SDValue();
14218
14219     // If this is not the MMX case, i.e. we are just turning i64 load/store
14220     // into f64 load/store, avoid the transformation if there are multiple
14221     // uses of the loaded value.
14222     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14223       return SDValue();
14224
14225     DebugLoc LdDL = Ld->getDebugLoc();
14226     DebugLoc StDL = N->getDebugLoc();
14227     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14228     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14229     // pair instead.
14230     if (Subtarget->is64Bit() || F64IsLegal) {
14231       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14232       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14233                                   Ld->getPointerInfo(), Ld->isVolatile(),
14234                                   Ld->isNonTemporal(), Ld->isInvariant(),
14235                                   Ld->getAlignment());
14236       SDValue NewChain = NewLd.getValue(1);
14237       if (TokenFactorIndex != -1) {
14238         Ops.push_back(NewChain);
14239         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14240                                Ops.size());
14241       }
14242       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14243                           St->getPointerInfo(),
14244                           St->isVolatile(), St->isNonTemporal(),
14245                           St->getAlignment());
14246     }
14247
14248     // Otherwise, lower to two pairs of 32-bit loads / stores.
14249     SDValue LoAddr = Ld->getBasePtr();
14250     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14251                                  DAG.getConstant(4, MVT::i32));
14252
14253     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14254                                Ld->getPointerInfo(),
14255                                Ld->isVolatile(), Ld->isNonTemporal(),
14256                                Ld->isInvariant(), Ld->getAlignment());
14257     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14258                                Ld->getPointerInfo().getWithOffset(4),
14259                                Ld->isVolatile(), Ld->isNonTemporal(),
14260                                Ld->isInvariant(),
14261                                MinAlign(Ld->getAlignment(), 4));
14262
14263     SDValue NewChain = LoLd.getValue(1);
14264     if (TokenFactorIndex != -1) {
14265       Ops.push_back(LoLd);
14266       Ops.push_back(HiLd);
14267       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14268                              Ops.size());
14269     }
14270
14271     LoAddr = St->getBasePtr();
14272     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14273                          DAG.getConstant(4, MVT::i32));
14274
14275     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14276                                 St->getPointerInfo(),
14277                                 St->isVolatile(), St->isNonTemporal(),
14278                                 St->getAlignment());
14279     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14280                                 St->getPointerInfo().getWithOffset(4),
14281                                 St->isVolatile(),
14282                                 St->isNonTemporal(),
14283                                 MinAlign(St->getAlignment(), 4));
14284     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14285   }
14286   return SDValue();
14287 }
14288
14289 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14290 /// and return the operands for the horizontal operation in LHS and RHS.  A
14291 /// horizontal operation performs the binary operation on successive elements
14292 /// of its first operand, then on successive elements of its second operand,
14293 /// returning the resulting values in a vector.  For example, if
14294 ///   A = < float a0, float a1, float a2, float a3 >
14295 /// and
14296 ///   B = < float b0, float b1, float b2, float b3 >
14297 /// then the result of doing a horizontal operation on A and B is
14298 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14299 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14300 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14301 /// set to A, RHS to B, and the routine returns 'true'.
14302 /// Note that the binary operation should have the property that if one of the
14303 /// operands is UNDEF then the result is UNDEF.
14304 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14305   // Look for the following pattern: if
14306   //   A = < float a0, float a1, float a2, float a3 >
14307   //   B = < float b0, float b1, float b2, float b3 >
14308   // and
14309   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14310   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14311   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14312   // which is A horizontal-op B.
14313
14314   // At least one of the operands should be a vector shuffle.
14315   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14316       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14317     return false;
14318
14319   EVT VT = LHS.getValueType();
14320   unsigned N = VT.getVectorNumElements();
14321
14322   // View LHS in the form
14323   //   LHS = VECTOR_SHUFFLE A, B, LMask
14324   // If LHS is not a shuffle then pretend it is the shuffle
14325   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14326   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14327   // type VT.
14328   SDValue A, B;
14329   SmallVector<int, 8> LMask(N);
14330   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14331     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14332       A = LHS.getOperand(0);
14333     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14334       B = LHS.getOperand(1);
14335     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14336   } else {
14337     if (LHS.getOpcode() != ISD::UNDEF)
14338       A = LHS;
14339     for (unsigned i = 0; i != N; ++i)
14340       LMask[i] = i;
14341   }
14342
14343   // Likewise, view RHS in the form
14344   //   RHS = VECTOR_SHUFFLE C, D, RMask
14345   SDValue C, D;
14346   SmallVector<int, 8> RMask(N);
14347   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14348     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14349       C = RHS.getOperand(0);
14350     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14351       D = RHS.getOperand(1);
14352     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14353   } else {
14354     if (RHS.getOpcode() != ISD::UNDEF)
14355       C = RHS;
14356     for (unsigned i = 0; i != N; ++i)
14357       RMask[i] = i;
14358   }
14359
14360   // Check that the shuffles are both shuffling the same vectors.
14361   if (!(A == C && B == D) && !(A == D && B == C))
14362     return false;
14363
14364   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14365   if (!A.getNode() && !B.getNode())
14366     return false;
14367
14368   // If A and B occur in reverse order in RHS, then "swap" them (which means
14369   // rewriting the mask).
14370   if (A != C)
14371     for (unsigned i = 0; i != N; ++i) {
14372       unsigned Idx = RMask[i];
14373       if (Idx < N)
14374         RMask[i] += N;
14375       else if (Idx < 2*N)
14376         RMask[i] -= N;
14377     }
14378
14379   // At this point LHS and RHS are equivalent to
14380   //   LHS = VECTOR_SHUFFLE A, B, LMask
14381   //   RHS = VECTOR_SHUFFLE A, B, RMask
14382   // Check that the masks correspond to performing a horizontal operation.
14383   for (unsigned i = 0; i != N; ++i) {
14384     unsigned LIdx = LMask[i], RIdx = RMask[i];
14385
14386     // Ignore any UNDEF components.
14387     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14388         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14389       continue;
14390
14391     // Check that successive elements are being operated on.  If not, this is
14392     // not a horizontal operation.
14393     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14394         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14395       return false;
14396   }
14397
14398   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14399   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14400   return true;
14401 }
14402
14403 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14404 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14405                                   const X86Subtarget *Subtarget) {
14406   EVT VT = N->getValueType(0);
14407   SDValue LHS = N->getOperand(0);
14408   SDValue RHS = N->getOperand(1);
14409
14410   // Try to synthesize horizontal adds from adds of shuffles.
14411   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14412       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14413       isHorizontalBinOp(LHS, RHS, true))
14414     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14415   return SDValue();
14416 }
14417
14418 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14419 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14420                                   const X86Subtarget *Subtarget) {
14421   EVT VT = N->getValueType(0);
14422   SDValue LHS = N->getOperand(0);
14423   SDValue RHS = N->getOperand(1);
14424
14425   // Try to synthesize horizontal subs from subs of shuffles.
14426   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14427       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14428       isHorizontalBinOp(LHS, RHS, false))
14429     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14430   return SDValue();
14431 }
14432
14433 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14434 /// X86ISD::FXOR nodes.
14435 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14436   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14437   // F[X]OR(0.0, x) -> x
14438   // F[X]OR(x, 0.0) -> x
14439   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14440     if (C->getValueAPF().isPosZero())
14441       return N->getOperand(1);
14442   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14443     if (C->getValueAPF().isPosZero())
14444       return N->getOperand(0);
14445   return SDValue();
14446 }
14447
14448 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14449 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14450   // FAND(0.0, x) -> 0.0
14451   // FAND(x, 0.0) -> 0.0
14452   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14453     if (C->getValueAPF().isPosZero())
14454       return N->getOperand(0);
14455   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14456     if (C->getValueAPF().isPosZero())
14457       return N->getOperand(1);
14458   return SDValue();
14459 }
14460
14461 static SDValue PerformBTCombine(SDNode *N,
14462                                 SelectionDAG &DAG,
14463                                 TargetLowering::DAGCombinerInfo &DCI) {
14464   // BT ignores high bits in the bit index operand.
14465   SDValue Op1 = N->getOperand(1);
14466   if (Op1.hasOneUse()) {
14467     unsigned BitWidth = Op1.getValueSizeInBits();
14468     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14469     APInt KnownZero, KnownOne;
14470     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14471                                           !DCI.isBeforeLegalizeOps());
14472     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14473     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14474         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14475       DCI.CommitTargetLoweringOpt(TLO);
14476   }
14477   return SDValue();
14478 }
14479
14480 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14481   SDValue Op = N->getOperand(0);
14482   if (Op.getOpcode() == ISD::BITCAST)
14483     Op = Op.getOperand(0);
14484   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14485   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14486       VT.getVectorElementType().getSizeInBits() ==
14487       OpVT.getVectorElementType().getSizeInBits()) {
14488     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14489   }
14490   return SDValue();
14491 }
14492
14493 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14494   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14495   //           (and (i32 x86isd::setcc_carry), 1)
14496   // This eliminates the zext. This transformation is necessary because
14497   // ISD::SETCC is always legalized to i8.
14498   DebugLoc dl = N->getDebugLoc();
14499   SDValue N0 = N->getOperand(0);
14500   EVT VT = N->getValueType(0);
14501   if (N0.getOpcode() == ISD::AND &&
14502       N0.hasOneUse() &&
14503       N0.getOperand(0).hasOneUse()) {
14504     SDValue N00 = N0.getOperand(0);
14505     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14506       return SDValue();
14507     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14508     if (!C || C->getZExtValue() != 1)
14509       return SDValue();
14510     return DAG.getNode(ISD::AND, dl, VT,
14511                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14512                                    N00.getOperand(0), N00.getOperand(1)),
14513                        DAG.getConstant(1, VT));
14514   }
14515
14516   return SDValue();
14517 }
14518
14519 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14520 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14521   unsigned X86CC = N->getConstantOperandVal(0);
14522   SDValue EFLAG = N->getOperand(1);
14523   DebugLoc DL = N->getDebugLoc();
14524
14525   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14526   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14527   // cases.
14528   if (X86CC == X86::COND_B)
14529     return DAG.getNode(ISD::AND, DL, MVT::i8,
14530                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14531                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14532                        DAG.getConstant(1, MVT::i8));
14533
14534   return SDValue();
14535 }
14536
14537 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14538                                         const X86TargetLowering *XTLI) {
14539   SDValue Op0 = N->getOperand(0);
14540   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14541   // a 32-bit target where SSE doesn't support i64->FP operations.
14542   if (Op0.getOpcode() == ISD::LOAD) {
14543     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14544     EVT VT = Ld->getValueType(0);
14545     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14546         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14547         !XTLI->getSubtarget()->is64Bit() &&
14548         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14549       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14550                                           Ld->getChain(), Op0, DAG);
14551       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14552       return FILDChain;
14553     }
14554   }
14555   return SDValue();
14556 }
14557
14558 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14559 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14560                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14561   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14562   // the result is either zero or one (depending on the input carry bit).
14563   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14564   if (X86::isZeroNode(N->getOperand(0)) &&
14565       X86::isZeroNode(N->getOperand(1)) &&
14566       // We don't have a good way to replace an EFLAGS use, so only do this when
14567       // dead right now.
14568       SDValue(N, 1).use_empty()) {
14569     DebugLoc DL = N->getDebugLoc();
14570     EVT VT = N->getValueType(0);
14571     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14572     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14573                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14574                                            DAG.getConstant(X86::COND_B,MVT::i8),
14575                                            N->getOperand(2)),
14576                                DAG.getConstant(1, VT));
14577     return DCI.CombineTo(N, Res1, CarryOut);
14578   }
14579
14580   return SDValue();
14581 }
14582
14583 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14584 //      (add Y, (setne X, 0)) -> sbb -1, Y
14585 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14586 //      (sub (setne X, 0), Y) -> adc -1, Y
14587 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14588   DebugLoc DL = N->getDebugLoc();
14589
14590   // Look through ZExts.
14591   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14592   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14593     return SDValue();
14594
14595   SDValue SetCC = Ext.getOperand(0);
14596   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14597     return SDValue();
14598
14599   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14600   if (CC != X86::COND_E && CC != X86::COND_NE)
14601     return SDValue();
14602
14603   SDValue Cmp = SetCC.getOperand(1);
14604   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14605       !X86::isZeroNode(Cmp.getOperand(1)) ||
14606       !Cmp.getOperand(0).getValueType().isInteger())
14607     return SDValue();
14608
14609   SDValue CmpOp0 = Cmp.getOperand(0);
14610   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14611                                DAG.getConstant(1, CmpOp0.getValueType()));
14612
14613   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14614   if (CC == X86::COND_NE)
14615     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14616                        DL, OtherVal.getValueType(), OtherVal,
14617                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14618   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14619                      DL, OtherVal.getValueType(), OtherVal,
14620                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14621 }
14622
14623 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14624   SDValue Op0 = N->getOperand(0);
14625   SDValue Op1 = N->getOperand(1);
14626
14627   // X86 can't encode an immediate LHS of a sub. See if we can push the
14628   // negation into a preceding instruction.
14629   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14630     // If the RHS of the sub is a XOR with one use and a constant, invert the
14631     // immediate. Then add one to the LHS of the sub so we can turn
14632     // X-Y -> X+~Y+1, saving one register.
14633     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14634         isa<ConstantSDNode>(Op1.getOperand(1))) {
14635       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14636       EVT VT = Op0.getValueType();
14637       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14638                                    Op1.getOperand(0),
14639                                    DAG.getConstant(~XorC, VT));
14640       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14641                          DAG.getConstant(C->getAPIntValue()+1, VT));
14642     }
14643   }
14644
14645   return OptimizeConditionalInDecrement(N, DAG);
14646 }
14647
14648 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14649                                              DAGCombinerInfo &DCI) const {
14650   SelectionDAG &DAG = DCI.DAG;
14651   switch (N->getOpcode()) {
14652   default: break;
14653   case ISD::EXTRACT_VECTOR_ELT:
14654     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14655   case ISD::VSELECT:
14656   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14657   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14658   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14659   case ISD::SUB:            return PerformSubCombine(N, DAG);
14660   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14661   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14662   case ISD::SHL:
14663   case ISD::SRA:
14664   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14665   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14666   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14667   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14668   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14669   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14670   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14671   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14672   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14673   case X86ISD::FXOR:
14674   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14675   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14676   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14677   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14678   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14679   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14680   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14681   case X86ISD::SHUFPD:
14682   case X86ISD::PALIGN:
14683   case X86ISD::PUNPCKHBW:
14684   case X86ISD::PUNPCKHWD:
14685   case X86ISD::PUNPCKHDQ:
14686   case X86ISD::PUNPCKHQDQ:
14687   case X86ISD::UNPCKHPS:
14688   case X86ISD::UNPCKHPD:
14689   case X86ISD::VUNPCKHPSY:
14690   case X86ISD::VUNPCKHPDY:
14691   case X86ISD::PUNPCKLBW:
14692   case X86ISD::PUNPCKLWD:
14693   case X86ISD::PUNPCKLDQ:
14694   case X86ISD::PUNPCKLQDQ:
14695   case X86ISD::UNPCKLPS:
14696   case X86ISD::UNPCKLPD:
14697   case X86ISD::VUNPCKLPSY:
14698   case X86ISD::VUNPCKLPDY:
14699   case X86ISD::MOVHLPS:
14700   case X86ISD::MOVLHPS:
14701   case X86ISD::PSHUFD:
14702   case X86ISD::PSHUFHW:
14703   case X86ISD::PSHUFLW:
14704   case X86ISD::MOVSS:
14705   case X86ISD::MOVSD:
14706   case X86ISD::VPERMILPS:
14707   case X86ISD::VPERMILPSY:
14708   case X86ISD::VPERMILPD:
14709   case X86ISD::VPERMILPDY:
14710   case X86ISD::VPERM2F128:
14711   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14712   }
14713
14714   return SDValue();
14715 }
14716
14717 /// isTypeDesirableForOp - Return true if the target has native support for
14718 /// the specified value type and it is 'desirable' to use the type for the
14719 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14720 /// instruction encodings are longer and some i16 instructions are slow.
14721 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14722   if (!isTypeLegal(VT))
14723     return false;
14724   if (VT != MVT::i16)
14725     return true;
14726
14727   switch (Opc) {
14728   default:
14729     return true;
14730   case ISD::LOAD:
14731   case ISD::SIGN_EXTEND:
14732   case ISD::ZERO_EXTEND:
14733   case ISD::ANY_EXTEND:
14734   case ISD::SHL:
14735   case ISD::SRL:
14736   case ISD::SUB:
14737   case ISD::ADD:
14738   case ISD::MUL:
14739   case ISD::AND:
14740   case ISD::OR:
14741   case ISD::XOR:
14742     return false;
14743   }
14744 }
14745
14746 /// IsDesirableToPromoteOp - This method query the target whether it is
14747 /// beneficial for dag combiner to promote the specified node. If true, it
14748 /// should return the desired promotion type by reference.
14749 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14750   EVT VT = Op.getValueType();
14751   if (VT != MVT::i16)
14752     return false;
14753
14754   bool Promote = false;
14755   bool Commute = false;
14756   switch (Op.getOpcode()) {
14757   default: break;
14758   case ISD::LOAD: {
14759     LoadSDNode *LD = cast<LoadSDNode>(Op);
14760     // If the non-extending load has a single use and it's not live out, then it
14761     // might be folded.
14762     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14763                                                      Op.hasOneUse()*/) {
14764       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14765              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14766         // The only case where we'd want to promote LOAD (rather then it being
14767         // promoted as an operand is when it's only use is liveout.
14768         if (UI->getOpcode() != ISD::CopyToReg)
14769           return false;
14770       }
14771     }
14772     Promote = true;
14773     break;
14774   }
14775   case ISD::SIGN_EXTEND:
14776   case ISD::ZERO_EXTEND:
14777   case ISD::ANY_EXTEND:
14778     Promote = true;
14779     break;
14780   case ISD::SHL:
14781   case ISD::SRL: {
14782     SDValue N0 = Op.getOperand(0);
14783     // Look out for (store (shl (load), x)).
14784     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14785       return false;
14786     Promote = true;
14787     break;
14788   }
14789   case ISD::ADD:
14790   case ISD::MUL:
14791   case ISD::AND:
14792   case ISD::OR:
14793   case ISD::XOR:
14794     Commute = true;
14795     // fallthrough
14796   case ISD::SUB: {
14797     SDValue N0 = Op.getOperand(0);
14798     SDValue N1 = Op.getOperand(1);
14799     if (!Commute && MayFoldLoad(N1))
14800       return false;
14801     // Avoid disabling potential load folding opportunities.
14802     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14803       return false;
14804     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14805       return false;
14806     Promote = true;
14807   }
14808   }
14809
14810   PVT = MVT::i32;
14811   return Promote;
14812 }
14813
14814 //===----------------------------------------------------------------------===//
14815 //                           X86 Inline Assembly Support
14816 //===----------------------------------------------------------------------===//
14817
14818 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14819   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14820
14821   std::string AsmStr = IA->getAsmString();
14822
14823   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14824   SmallVector<StringRef, 4> AsmPieces;
14825   SplitString(AsmStr, AsmPieces, ";\n");
14826
14827   switch (AsmPieces.size()) {
14828   default: return false;
14829   case 1:
14830     AsmStr = AsmPieces[0];
14831     AsmPieces.clear();
14832     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14833
14834     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14835     // we will turn this bswap into something that will be lowered to logical ops
14836     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14837     // so don't worry about this.
14838     // bswap $0
14839     if (AsmPieces.size() == 2 &&
14840         (AsmPieces[0] == "bswap" ||
14841          AsmPieces[0] == "bswapq" ||
14842          AsmPieces[0] == "bswapl") &&
14843         (AsmPieces[1] == "$0" ||
14844          AsmPieces[1] == "${0:q}")) {
14845       // No need to check constraints, nothing other than the equivalent of
14846       // "=r,0" would be valid here.
14847       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14848       if (!Ty || Ty->getBitWidth() % 16 != 0)
14849         return false;
14850       return IntrinsicLowering::LowerToByteSwap(CI);
14851     }
14852     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14853     if (CI->getType()->isIntegerTy(16) &&
14854         AsmPieces.size() == 3 &&
14855         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14856         AsmPieces[1] == "$$8," &&
14857         AsmPieces[2] == "${0:w}" &&
14858         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14859       AsmPieces.clear();
14860       const std::string &ConstraintsStr = IA->getConstraintString();
14861       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14862       std::sort(AsmPieces.begin(), AsmPieces.end());
14863       if (AsmPieces.size() == 4 &&
14864           AsmPieces[0] == "~{cc}" &&
14865           AsmPieces[1] == "~{dirflag}" &&
14866           AsmPieces[2] == "~{flags}" &&
14867           AsmPieces[3] == "~{fpsr}") {
14868         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14869         if (!Ty || Ty->getBitWidth() % 16 != 0)
14870           return false;
14871         return IntrinsicLowering::LowerToByteSwap(CI);
14872       }
14873     }
14874     break;
14875   case 3:
14876     if (CI->getType()->isIntegerTy(32) &&
14877         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14878       SmallVector<StringRef, 4> Words;
14879       SplitString(AsmPieces[0], Words, " \t,");
14880       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14881           Words[2] == "${0:w}") {
14882         Words.clear();
14883         SplitString(AsmPieces[1], Words, " \t,");
14884         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14885             Words[2] == "$0") {
14886           Words.clear();
14887           SplitString(AsmPieces[2], Words, " \t,");
14888           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14889               Words[2] == "${0:w}") {
14890             AsmPieces.clear();
14891             const std::string &ConstraintsStr = IA->getConstraintString();
14892             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14893             std::sort(AsmPieces.begin(), AsmPieces.end());
14894             if (AsmPieces.size() == 4 &&
14895                 AsmPieces[0] == "~{cc}" &&
14896                 AsmPieces[1] == "~{dirflag}" &&
14897                 AsmPieces[2] == "~{flags}" &&
14898                 AsmPieces[3] == "~{fpsr}") {
14899               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14900               if (!Ty || Ty->getBitWidth() % 16 != 0)
14901                 return false;
14902               return IntrinsicLowering::LowerToByteSwap(CI);
14903             }
14904           }
14905         }
14906       }
14907     }
14908
14909     if (CI->getType()->isIntegerTy(64)) {
14910       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14911       if (Constraints.size() >= 2 &&
14912           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14913           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14914         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14915         SmallVector<StringRef, 4> Words;
14916         SplitString(AsmPieces[0], Words, " \t");
14917         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14918           Words.clear();
14919           SplitString(AsmPieces[1], Words, " \t");
14920           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14921             Words.clear();
14922             SplitString(AsmPieces[2], Words, " \t,");
14923             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14924                 Words[2] == "%edx") {
14925               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14926               if (!Ty || Ty->getBitWidth() % 16 != 0)
14927                 return false;
14928               return IntrinsicLowering::LowerToByteSwap(CI);
14929             }
14930           }
14931         }
14932       }
14933     }
14934     break;
14935   }
14936   return false;
14937 }
14938
14939
14940
14941 /// getConstraintType - Given a constraint letter, return the type of
14942 /// constraint it is for this target.
14943 X86TargetLowering::ConstraintType
14944 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14945   if (Constraint.size() == 1) {
14946     switch (Constraint[0]) {
14947     case 'R':
14948     case 'q':
14949     case 'Q':
14950     case 'f':
14951     case 't':
14952     case 'u':
14953     case 'y':
14954     case 'x':
14955     case 'Y':
14956     case 'l':
14957       return C_RegisterClass;
14958     case 'a':
14959     case 'b':
14960     case 'c':
14961     case 'd':
14962     case 'S':
14963     case 'D':
14964     case 'A':
14965       return C_Register;
14966     case 'I':
14967     case 'J':
14968     case 'K':
14969     case 'L':
14970     case 'M':
14971     case 'N':
14972     case 'G':
14973     case 'C':
14974     case 'e':
14975     case 'Z':
14976       return C_Other;
14977     default:
14978       break;
14979     }
14980   }
14981   return TargetLowering::getConstraintType(Constraint);
14982 }
14983
14984 /// Examine constraint type and operand type and determine a weight value.
14985 /// This object must already have been set up with the operand type
14986 /// and the current alternative constraint selected.
14987 TargetLowering::ConstraintWeight
14988   X86TargetLowering::getSingleConstraintMatchWeight(
14989     AsmOperandInfo &info, const char *constraint) const {
14990   ConstraintWeight weight = CW_Invalid;
14991   Value *CallOperandVal = info.CallOperandVal;
14992     // If we don't have a value, we can't do a match,
14993     // but allow it at the lowest weight.
14994   if (CallOperandVal == NULL)
14995     return CW_Default;
14996   Type *type = CallOperandVal->getType();
14997   // Look at the constraint type.
14998   switch (*constraint) {
14999   default:
15000     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15001   case 'R':
15002   case 'q':
15003   case 'Q':
15004   case 'a':
15005   case 'b':
15006   case 'c':
15007   case 'd':
15008   case 'S':
15009   case 'D':
15010   case 'A':
15011     if (CallOperandVal->getType()->isIntegerTy())
15012       weight = CW_SpecificReg;
15013     break;
15014   case 'f':
15015   case 't':
15016   case 'u':
15017       if (type->isFloatingPointTy())
15018         weight = CW_SpecificReg;
15019       break;
15020   case 'y':
15021       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15022         weight = CW_SpecificReg;
15023       break;
15024   case 'x':
15025   case 'Y':
15026     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15027       weight = CW_Register;
15028     break;
15029   case 'I':
15030     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15031       if (C->getZExtValue() <= 31)
15032         weight = CW_Constant;
15033     }
15034     break;
15035   case 'J':
15036     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15037       if (C->getZExtValue() <= 63)
15038         weight = CW_Constant;
15039     }
15040     break;
15041   case 'K':
15042     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15043       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15044         weight = CW_Constant;
15045     }
15046     break;
15047   case 'L':
15048     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15049       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15050         weight = CW_Constant;
15051     }
15052     break;
15053   case 'M':
15054     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15055       if (C->getZExtValue() <= 3)
15056         weight = CW_Constant;
15057     }
15058     break;
15059   case 'N':
15060     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15061       if (C->getZExtValue() <= 0xff)
15062         weight = CW_Constant;
15063     }
15064     break;
15065   case 'G':
15066   case 'C':
15067     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15068       weight = CW_Constant;
15069     }
15070     break;
15071   case 'e':
15072     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15073       if ((C->getSExtValue() >= -0x80000000LL) &&
15074           (C->getSExtValue() <= 0x7fffffffLL))
15075         weight = CW_Constant;
15076     }
15077     break;
15078   case 'Z':
15079     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15080       if (C->getZExtValue() <= 0xffffffff)
15081         weight = CW_Constant;
15082     }
15083     break;
15084   }
15085   return weight;
15086 }
15087
15088 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15089 /// with another that has more specific requirements based on the type of the
15090 /// corresponding operand.
15091 const char *X86TargetLowering::
15092 LowerXConstraint(EVT ConstraintVT) const {
15093   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15094   // 'f' like normal targets.
15095   if (ConstraintVT.isFloatingPoint()) {
15096     if (Subtarget->hasXMMInt())
15097       return "Y";
15098     if (Subtarget->hasXMM())
15099       return "x";
15100   }
15101
15102   return TargetLowering::LowerXConstraint(ConstraintVT);
15103 }
15104
15105 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15106 /// vector.  If it is invalid, don't add anything to Ops.
15107 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15108                                                      std::string &Constraint,
15109                                                      std::vector<SDValue>&Ops,
15110                                                      SelectionDAG &DAG) const {
15111   SDValue Result(0, 0);
15112
15113   // Only support length 1 constraints for now.
15114   if (Constraint.length() > 1) return;
15115
15116   char ConstraintLetter = Constraint[0];
15117   switch (ConstraintLetter) {
15118   default: break;
15119   case 'I':
15120     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15121       if (C->getZExtValue() <= 31) {
15122         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15123         break;
15124       }
15125     }
15126     return;
15127   case 'J':
15128     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15129       if (C->getZExtValue() <= 63) {
15130         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15131         break;
15132       }
15133     }
15134     return;
15135   case 'K':
15136     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15137       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15138         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15139         break;
15140       }
15141     }
15142     return;
15143   case 'N':
15144     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15145       if (C->getZExtValue() <= 255) {
15146         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15147         break;
15148       }
15149     }
15150     return;
15151   case 'e': {
15152     // 32-bit signed value
15153     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15154       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15155                                            C->getSExtValue())) {
15156         // Widen to 64 bits here to get it sign extended.
15157         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15158         break;
15159       }
15160     // FIXME gcc accepts some relocatable values here too, but only in certain
15161     // memory models; it's complicated.
15162     }
15163     return;
15164   }
15165   case 'Z': {
15166     // 32-bit unsigned value
15167     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15168       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15169                                            C->getZExtValue())) {
15170         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15171         break;
15172       }
15173     }
15174     // FIXME gcc accepts some relocatable values here too, but only in certain
15175     // memory models; it's complicated.
15176     return;
15177   }
15178   case 'i': {
15179     // Literal immediates are always ok.
15180     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15181       // Widen to 64 bits here to get it sign extended.
15182       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15183       break;
15184     }
15185
15186     // In any sort of PIC mode addresses need to be computed at runtime by
15187     // adding in a register or some sort of table lookup.  These can't
15188     // be used as immediates.
15189     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15190       return;
15191
15192     // If we are in non-pic codegen mode, we allow the address of a global (with
15193     // an optional displacement) to be used with 'i'.
15194     GlobalAddressSDNode *GA = 0;
15195     int64_t Offset = 0;
15196
15197     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15198     while (1) {
15199       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15200         Offset += GA->getOffset();
15201         break;
15202       } else if (Op.getOpcode() == ISD::ADD) {
15203         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15204           Offset += C->getZExtValue();
15205           Op = Op.getOperand(0);
15206           continue;
15207         }
15208       } else if (Op.getOpcode() == ISD::SUB) {
15209         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15210           Offset += -C->getZExtValue();
15211           Op = Op.getOperand(0);
15212           continue;
15213         }
15214       }
15215
15216       // Otherwise, this isn't something we can handle, reject it.
15217       return;
15218     }
15219
15220     const GlobalValue *GV = GA->getGlobal();
15221     // If we require an extra load to get this address, as in PIC mode, we
15222     // can't accept it.
15223     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15224                                                         getTargetMachine())))
15225       return;
15226
15227     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15228                                         GA->getValueType(0), Offset);
15229     break;
15230   }
15231   }
15232
15233   if (Result.getNode()) {
15234     Ops.push_back(Result);
15235     return;
15236   }
15237   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15238 }
15239
15240 std::pair<unsigned, const TargetRegisterClass*>
15241 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15242                                                 EVT VT) const {
15243   // First, see if this is a constraint that directly corresponds to an LLVM
15244   // register class.
15245   if (Constraint.size() == 1) {
15246     // GCC Constraint Letters
15247     switch (Constraint[0]) {
15248     default: break;
15249       // TODO: Slight differences here in allocation order and leaving
15250       // RIP in the class. Do they matter any more here than they do
15251       // in the normal allocation?
15252     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15253       if (Subtarget->is64Bit()) {
15254         if (VT == MVT::i32 || VT == MVT::f32)
15255           return std::make_pair(0U, X86::GR32RegisterClass);
15256         else if (VT == MVT::i16)
15257           return std::make_pair(0U, X86::GR16RegisterClass);
15258         else if (VT == MVT::i8 || VT == MVT::i1)
15259           return std::make_pair(0U, X86::GR8RegisterClass);
15260         else if (VT == MVT::i64 || VT == MVT::f64)
15261           return std::make_pair(0U, X86::GR64RegisterClass);
15262         break;
15263       }
15264       // 32-bit fallthrough
15265     case 'Q':   // Q_REGS
15266       if (VT == MVT::i32 || VT == MVT::f32)
15267         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15268       else if (VT == MVT::i16)
15269         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15270       else if (VT == MVT::i8 || VT == MVT::i1)
15271         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15272       else if (VT == MVT::i64)
15273         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15274       break;
15275     case 'r':   // GENERAL_REGS
15276     case 'l':   // INDEX_REGS
15277       if (VT == MVT::i8 || VT == MVT::i1)
15278         return std::make_pair(0U, X86::GR8RegisterClass);
15279       if (VT == MVT::i16)
15280         return std::make_pair(0U, X86::GR16RegisterClass);
15281       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15282         return std::make_pair(0U, X86::GR32RegisterClass);
15283       return std::make_pair(0U, X86::GR64RegisterClass);
15284     case 'R':   // LEGACY_REGS
15285       if (VT == MVT::i8 || VT == MVT::i1)
15286         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15287       if (VT == MVT::i16)
15288         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15289       if (VT == MVT::i32 || !Subtarget->is64Bit())
15290         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15291       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15292     case 'f':  // FP Stack registers.
15293       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15294       // value to the correct fpstack register class.
15295       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15296         return std::make_pair(0U, X86::RFP32RegisterClass);
15297       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15298         return std::make_pair(0U, X86::RFP64RegisterClass);
15299       return std::make_pair(0U, X86::RFP80RegisterClass);
15300     case 'y':   // MMX_REGS if MMX allowed.
15301       if (!Subtarget->hasMMX()) break;
15302       return std::make_pair(0U, X86::VR64RegisterClass);
15303     case 'Y':   // SSE_REGS if SSE2 allowed
15304       if (!Subtarget->hasXMMInt()) break;
15305       // FALL THROUGH.
15306     case 'x':   // SSE_REGS if SSE1 allowed
15307       if (!Subtarget->hasXMM()) break;
15308
15309       switch (VT.getSimpleVT().SimpleTy) {
15310       default: break;
15311       // Scalar SSE types.
15312       case MVT::f32:
15313       case MVT::i32:
15314         return std::make_pair(0U, X86::FR32RegisterClass);
15315       case MVT::f64:
15316       case MVT::i64:
15317         return std::make_pair(0U, X86::FR64RegisterClass);
15318       // Vector types.
15319       case MVT::v16i8:
15320       case MVT::v8i16:
15321       case MVT::v4i32:
15322       case MVT::v2i64:
15323       case MVT::v4f32:
15324       case MVT::v2f64:
15325         return std::make_pair(0U, X86::VR128RegisterClass);
15326       }
15327       break;
15328     }
15329   }
15330
15331   // Use the default implementation in TargetLowering to convert the register
15332   // constraint into a member of a register class.
15333   std::pair<unsigned, const TargetRegisterClass*> Res;
15334   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15335
15336   // Not found as a standard register?
15337   if (Res.second == 0) {
15338     // Map st(0) -> st(7) -> ST0
15339     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15340         tolower(Constraint[1]) == 's' &&
15341         tolower(Constraint[2]) == 't' &&
15342         Constraint[3] == '(' &&
15343         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15344         Constraint[5] == ')' &&
15345         Constraint[6] == '}') {
15346
15347       Res.first = X86::ST0+Constraint[4]-'0';
15348       Res.second = X86::RFP80RegisterClass;
15349       return Res;
15350     }
15351
15352     // GCC allows "st(0)" to be called just plain "st".
15353     if (StringRef("{st}").equals_lower(Constraint)) {
15354       Res.first = X86::ST0;
15355       Res.second = X86::RFP80RegisterClass;
15356       return Res;
15357     }
15358
15359     // flags -> EFLAGS
15360     if (StringRef("{flags}").equals_lower(Constraint)) {
15361       Res.first = X86::EFLAGS;
15362       Res.second = X86::CCRRegisterClass;
15363       return Res;
15364     }
15365
15366     // 'A' means EAX + EDX.
15367     if (Constraint == "A") {
15368       Res.first = X86::EAX;
15369       Res.second = X86::GR32_ADRegisterClass;
15370       return Res;
15371     }
15372     return Res;
15373   }
15374
15375   // Otherwise, check to see if this is a register class of the wrong value
15376   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15377   // turn into {ax},{dx}.
15378   if (Res.second->hasType(VT))
15379     return Res;   // Correct type already, nothing to do.
15380
15381   // All of the single-register GCC register classes map their values onto
15382   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15383   // really want an 8-bit or 32-bit register, map to the appropriate register
15384   // class and return the appropriate register.
15385   if (Res.second == X86::GR16RegisterClass) {
15386     if (VT == MVT::i8) {
15387       unsigned DestReg = 0;
15388       switch (Res.first) {
15389       default: break;
15390       case X86::AX: DestReg = X86::AL; break;
15391       case X86::DX: DestReg = X86::DL; break;
15392       case X86::CX: DestReg = X86::CL; break;
15393       case X86::BX: DestReg = X86::BL; break;
15394       }
15395       if (DestReg) {
15396         Res.first = DestReg;
15397         Res.second = X86::GR8RegisterClass;
15398       }
15399     } else if (VT == MVT::i32) {
15400       unsigned DestReg = 0;
15401       switch (Res.first) {
15402       default: break;
15403       case X86::AX: DestReg = X86::EAX; break;
15404       case X86::DX: DestReg = X86::EDX; break;
15405       case X86::CX: DestReg = X86::ECX; break;
15406       case X86::BX: DestReg = X86::EBX; break;
15407       case X86::SI: DestReg = X86::ESI; break;
15408       case X86::DI: DestReg = X86::EDI; break;
15409       case X86::BP: DestReg = X86::EBP; break;
15410       case X86::SP: DestReg = X86::ESP; break;
15411       }
15412       if (DestReg) {
15413         Res.first = DestReg;
15414         Res.second = X86::GR32RegisterClass;
15415       }
15416     } else if (VT == MVT::i64) {
15417       unsigned DestReg = 0;
15418       switch (Res.first) {
15419       default: break;
15420       case X86::AX: DestReg = X86::RAX; break;
15421       case X86::DX: DestReg = X86::RDX; break;
15422       case X86::CX: DestReg = X86::RCX; break;
15423       case X86::BX: DestReg = X86::RBX; break;
15424       case X86::SI: DestReg = X86::RSI; break;
15425       case X86::DI: DestReg = X86::RDI; break;
15426       case X86::BP: DestReg = X86::RBP; break;
15427       case X86::SP: DestReg = X86::RSP; break;
15428       }
15429       if (DestReg) {
15430         Res.first = DestReg;
15431         Res.second = X86::GR64RegisterClass;
15432       }
15433     }
15434   } else if (Res.second == X86::FR32RegisterClass ||
15435              Res.second == X86::FR64RegisterClass ||
15436              Res.second == X86::VR128RegisterClass) {
15437     // Handle references to XMM physical registers that got mapped into the
15438     // wrong class.  This can happen with constraints like {xmm0} where the
15439     // target independent register mapper will just pick the first match it can
15440     // find, ignoring the required type.
15441     if (VT == MVT::f32)
15442       Res.second = X86::FR32RegisterClass;
15443     else if (VT == MVT::f64)
15444       Res.second = X86::FR64RegisterClass;
15445     else if (X86::VR128RegisterClass->hasType(VT))
15446       Res.second = X86::VR128RegisterClass;
15447   }
15448
15449   return Res;
15450 }