Rename getTypeForExtendedInteger() to getTypeForExtArgOrReturn().
[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/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.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 using namespace llvm;
54 using namespace dwarf;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue Insert128BitVector(SDValue Result,
63                                   SDValue Vec,
64                                   SDValue Idx,
65                                   SelectionDAG &DAG,
66                                   DebugLoc dl);
67
68 static SDValue Extract128BitVector(SDValue Vec,
69                                    SDValue Idx,
70                                    SelectionDAG &DAG,
71                                    DebugLoc dl);
72
73 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
74
75
76 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
77 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
78 /// simple subregister reference.  Idx is an index in the 128 bits we
79 /// want.  It need not be aligned to a 128-bit bounday.  That makes
80 /// lowering EXTRACT_VECTOR_ELT operations easier.
81 static SDValue Extract128BitVector(SDValue Vec,
82                                    SDValue Idx,
83                                    SelectionDAG &DAG,
84                                    DebugLoc dl) {
85   EVT VT = Vec.getValueType();
86   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
87
88   EVT ElVT = VT.getVectorElementType();
89
90   int Factor = VT.getSizeInBits() / 128;
91
92   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
93                                   ElVT,
94                                   VT.getVectorNumElements() / Factor);
95
96   // Extract from UNDEF is UNDEF.
97   if (Vec.getOpcode() == ISD::UNDEF)
98     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
99
100   if (isa<ConstantSDNode>(Idx)) {
101     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
102
103     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
104     // we can match to VEXTRACTF128.
105     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
106
107     // This is the index of the first element of the 128-bit chunk
108     // we want.
109     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
110                                  * ElemsPerChunk);
111
112     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
113
114     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
115                                  VecIdx);
116
117     return Result;
118   }
119
120   return SDValue();
121 }
122
123 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
124 /// sets things up to match to an AVX VINSERTF128 instruction or a
125 /// simple superregister reference.  Idx is an index in the 128 bits
126 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
127 /// lowering INSERT_VECTOR_ELT operations easier.
128 static SDValue Insert128BitVector(SDValue Result,
129                                   SDValue Vec,
130                                   SDValue Idx,
131                                   SelectionDAG &DAG,
132                                   DebugLoc dl) {
133   if (isa<ConstantSDNode>(Idx)) {
134     EVT VT = Vec.getValueType();
135     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
136
137     EVT ElVT = VT.getVectorElementType();
138
139     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
140
141     EVT ResultVT = Result.getValueType();
142
143     // Insert the relevant 128 bits.
144     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
145
146     // This is the index of the first element of the 128-bit chunk
147     // we want.
148     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
149                                  * ElemsPerChunk);
150
151     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
152
153     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                          VecIdx);
155     return Result;
156   }
157
158   return SDValue();
159 }
160
161 /// Given two vectors, concat them.
162 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
163   DebugLoc dl = Lower.getDebugLoc();
164
165   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
166
167   EVT VT = EVT::getVectorVT(*DAG.getContext(),
168                             Lower.getValueType().getVectorElementType(),
169                             Lower.getValueType().getVectorNumElements() * 2);
170
171   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
172   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
173
174   // Insert the upper subvector.
175   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
176                                    DAG.getConstant(
177                                      // This is half the length of the result
178                                      // vector.  Start inserting the upper 128
179                                      // bits here.
180                                      Lower.getValueType().getVectorNumElements(),
181                                      MVT::i32),
182                                    DAG, dl);
183
184   // Insert the lower subvector.
185   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
186   return Vec;
187 }
188
189 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
190   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
191   bool is64Bit = Subtarget->is64Bit();
192
193   if (Subtarget->isTargetEnvMacho()) {
194     if (is64Bit)
195       return new X8664_MachoTargetObjectFile();
196     return new TargetLoweringObjectFileMachO();
197   }
198
199   if (Subtarget->isTargetELF()) {
200     if (is64Bit)
201       return new X8664_ELFTargetObjectFile(TM);
202     return new X8632_ELFTargetObjectFile(TM);
203   }
204   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
205     return new TargetLoweringObjectFileCOFF();
206   llvm_unreachable("unknown subtarget type");
207 }
208
209 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
210   : TargetLowering(TM, createTLOF(TM)) {
211   Subtarget = &TM.getSubtarget<X86Subtarget>();
212   X86ScalarSSEf64 = Subtarget->hasXMMInt();
213   X86ScalarSSEf32 = Subtarget->hasXMM();
214   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
215
216   RegInfo = TM.getRegisterInfo();
217   TD = getTargetData();
218
219   // Set up the TargetLowering object.
220   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
221
222   // X86 is weird, it always uses i8 for shift amounts and setcc results.
223   setBooleanContents(ZeroOrOneBooleanContent);
224     
225   // For 64-bit since we have so many registers use the ILP scheduler, for
226   // 32-bit code use the register pressure specific scheduling.
227   if (Subtarget->is64Bit())
228     setSchedulingPreference(Sched::ILP);
229   else
230     setSchedulingPreference(Sched::RegPressure);
231   setStackPointerRegisterToSaveRestore(X86StackPtr);
232
233   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
234     // Setup Windows compiler runtime calls.
235     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
236     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
237     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
238     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
239     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
240     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
243   }
244
245   if (Subtarget->isTargetDarwin()) {
246     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
247     setUseUnderscoreSetJmp(false);
248     setUseUnderscoreLongJmp(false);
249   } else if (Subtarget->isTargetMingw()) {
250     // MS runtime is weird: it exports _setjmp, but longjmp!
251     setUseUnderscoreSetJmp(true);
252     setUseUnderscoreLongJmp(false);
253   } else {
254     setUseUnderscoreSetJmp(true);
255     setUseUnderscoreLongJmp(true);
256   }
257
258   // Set up the register classes.
259   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
260   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
261   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
262   if (Subtarget->is64Bit())
263     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
264
265   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
266
267   // We don't accept any truncstore of integer registers.
268   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
269   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
271   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
272   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
273   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
274
275   // SETOEQ and SETUNE require checking two conditions.
276   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
277   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
279   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
282
283   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
284   // operation.
285   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
288
289   if (Subtarget->is64Bit()) {
290     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
292   } else if (!UseSoftFloat) {
293     // We have an algorithm for SSE2->double, and we turn this into a
294     // 64-bit FILD followed by conditional FADD for other targets.
295     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
296     // We have an algorithm for SSE2, and we turn this into a 64-bit
297     // FILD for other targets.
298     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
299   }
300
301   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
302   // this operation.
303   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
305
306   if (!UseSoftFloat) {
307     // SSE has no i16 to fp conversion, only i32
308     if (X86ScalarSSEf32) {
309       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
310       // f32 and f64 cases are Legal, f80 case is not
311       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
312     } else {
313       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
315     }
316   } else {
317     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
319   }
320
321   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
322   // are Legal, f80 is custom lowered.
323   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
324   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
325
326   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
327   // this operation.
328   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
330
331   if (X86ScalarSSEf32) {
332     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
333     // f32 and f64 cases are Legal, f80 case is not
334     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
335   } else {
336     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
338   }
339
340   // Handle FP_TO_UINT by promoting the destination to a larger signed
341   // conversion.
342   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
345
346   if (Subtarget->is64Bit()) {
347     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
349   } else if (!UseSoftFloat) {
350     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
351       // Expand FP_TO_UINT into a select.
352       // FIXME: We would like to use a Custom expander here eventually to do
353       // the optimal thing for SSE vs. the default expansion in the legalizer.
354       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
355     else
356       // With SSE3 we can use fisttpll to convert to a signed i64; without
357       // SSE, we're stuck with a fistpll.
358       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
359   }
360
361   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
362   if (!X86ScalarSSEf64) {
363     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
364     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
365     if (Subtarget->is64Bit()) {
366       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
367       // Without SSE, i64->f64 goes through memory.
368       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
369     }
370   }
371
372   // Scalar integer divide and remainder are lowered to use operations that
373   // produce two results, to match the available instructions. This exposes
374   // the two-result form to trivial CSE, which is able to combine x/y and x%y
375   // into a single instruction.
376   //
377   // Scalar integer multiply-high is also lowered to use two-result
378   // operations, to match the available instructions. However, plain multiply
379   // (low) operations are left as Legal, as there are single-result
380   // instructions for this in x86. Using the two-result multiply instructions
381   // when both high and low results are needed must be arranged by dagcombine.
382   for (unsigned i = 0, e = 4; i != e; ++i) {
383     MVT VT = IntVTs[i];
384     setOperationAction(ISD::MULHS, VT, Expand);
385     setOperationAction(ISD::MULHU, VT, Expand);
386     setOperationAction(ISD::SDIV, VT, Expand);
387     setOperationAction(ISD::UDIV, VT, Expand);
388     setOperationAction(ISD::SREM, VT, Expand);
389     setOperationAction(ISD::UREM, VT, Expand);
390
391     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
392     setOperationAction(ISD::ADDC, VT, Custom);
393     setOperationAction(ISD::ADDE, VT, Custom);
394     setOperationAction(ISD::SUBC, VT, Custom);
395     setOperationAction(ISD::SUBE, VT, Custom);
396   }
397
398   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
399   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
400   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
401   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
402   if (Subtarget->is64Bit())
403     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
404   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
407   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
408   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
411   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
412
413   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
414   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
416   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
418   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
421     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
422   }
423
424   if (Subtarget->hasPOPCNT()) {
425     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
426   } else {
427     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
428     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
430     if (Subtarget->is64Bit())
431       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
432   }
433
434   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
435   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
436
437   // These should be promoted to a larger select which is supported.
438   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
439   // X86 wants to expand cmov itself.
440   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
441   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
452   if (Subtarget->is64Bit()) {
453     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
454     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
455   }
456   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
457
458   // Darwin ABI issue.
459   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
460   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
461   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
463   if (Subtarget->is64Bit())
464     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
465   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
466   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
467   if (Subtarget->is64Bit()) {
468     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
469     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
470     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
471     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
472     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
473   }
474   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
475   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
476   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
478   if (Subtarget->is64Bit()) {
479     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
480     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
482   }
483
484   if (Subtarget->hasXMM())
485     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
486
487   // We may not have a libcall for MEMBARRIER so we should lower this.
488   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
489
490   // On X86 and X86-64, atomic operations are lowered to locked instructions.
491   // Locked instructions, in turn, have implicit fence semantics (all memory
492   // operations are flushed before issuing the locked instruction, and they
493   // are not buffered), so we can fold away the common pattern of
494   // fence-atomic-fence.
495   setShouldFoldAtomicFences(true);
496
497   // Expand certain atomics
498   for (unsigned i = 0, e = 4; i != e; ++i) {
499     MVT VT = IntVTs[i];
500     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
502   }
503
504   if (!Subtarget->is64Bit()) {
505     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
512   }
513
514   // FIXME - use subtarget debug flags
515   if (!Subtarget->isTargetDarwin() &&
516       !Subtarget->isTargetELF() &&
517       !Subtarget->isTargetCygMing()) {
518     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
519   }
520
521   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
522   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
523   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
524   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
525   if (Subtarget->is64Bit()) {
526     setExceptionPointerRegister(X86::RAX);
527     setExceptionSelectorRegister(X86::RDX);
528   } else {
529     setExceptionPointerRegister(X86::EAX);
530     setExceptionSelectorRegister(X86::EDX);
531   }
532   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
534
535   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
536
537   setOperationAction(ISD::TRAP, MVT::Other, Legal);
538
539   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
541   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
544     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
545   } else {
546     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
547     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
548   }
549
550   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
551   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
552   if (Subtarget->is64Bit())
553     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
554   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
555     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
556   else
557     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
558
559   if (!UseSoftFloat && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565     // Use ANDPD to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f64, Custom);
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f64, Custom);
571     setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573     // Use ANDPD and ORPD to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN , MVT::f64, Expand);
579     setOperationAction(ISD::FCOS , MVT::f64, Expand);
580     setOperationAction(ISD::FSIN , MVT::f32, Expand);
581     setOperationAction(ISD::FCOS , MVT::f32, Expand);
582
583     // Expand FP immediates into loads from the stack, except for the special
584     // cases we handle.
585     addLegalFPImmediate(APFloat(+0.0)); // xorpd
586     addLegalFPImmediate(APFloat(+0.0f)); // xorps
587   } else if (!UseSoftFloat && X86ScalarSSEf32) {
588     // Use SSE for f32, x87 for f64.
589     // Set up the FP register classes.
590     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592
593     // Use ANDPS to simulate FABS.
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
600
601     // Use ANDPS and ORPS to simulate FCOPYSIGN.
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604
605     // We don't support sin/cos/fmod
606     setOperationAction(ISD::FSIN , MVT::f32, Expand);
607     setOperationAction(ISD::FCOS , MVT::f32, Expand);
608
609     // Special cases we handle for FP constants.
610     addLegalFPImmediate(APFloat(+0.0f)); // xorps
611     addLegalFPImmediate(APFloat(+0.0)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
615
616     if (!UnsafeFPMath) {
617       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
618       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
619     }
620   } else if (!UseSoftFloat) {
621     // f32 and f64 in x87.
622     // Set up the FP register classes.
623     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
625
626     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
627     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
630
631     if (!UnsafeFPMath) {
632       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
633       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
634     }
635     addLegalFPImmediate(APFloat(+0.0)); // FLD0
636     addLegalFPImmediate(APFloat(+1.0)); // FLD1
637     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
643   }
644
645   // Long double always uses X87.
646   if (!UseSoftFloat) {
647     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
649     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
650     {
651       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652       addLegalFPImmediate(TmpFlt);  // FLD0
653       TmpFlt.changeSign();
654       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
655
656       bool ignored;
657       APFloat TmpFlt2(+1.0);
658       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
659                       &ignored);
660       addLegalFPImmediate(TmpFlt2);  // FLD1
661       TmpFlt2.changeSign();
662       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
663     }
664
665     if (!UnsafeFPMath) {
666       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
667       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
668     }
669   }
670
671   // Always use a library call for pow.
672   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
674   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
675
676   setOperationAction(ISD::FLOG, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP, MVT::f80, Expand);
680   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
681
682   // First set operation action for all vector types to either promote
683   // (for widening) or expand (for scalarization). Then we will selectively
684   // turn on ones that can be effectively codegen'd.
685   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
834     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
835     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
836     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     // i8 and i16 vectors are custom , because the source register and source
932     // source memory operand types are not the same width.  f32 vectors are
933     // custom since the immediate controlling the insert encodes additional
934     // information.
935     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
939
940     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
944
945     if (Subtarget->is64Bit()) {
946       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
947       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
948     }
949   }
950
951   if (Subtarget->hasSSE42())
952     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
953
954   if (!UseSoftFloat && Subtarget->hasAVX()) {
955     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
956     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
957     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
958     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
959     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
960
961     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
962     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
963     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
964     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
965
966     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
967     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
968     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
969     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
970     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
971     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
972
973     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
974     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
975     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
976     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
977     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
978     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
979
980     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
981     // insert_vector_elt extract_subvector and extract_vector_elt for
982     // 256-bit types.
983     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
984          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
985          ++i) {
986       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
987       // Do not attempt to custom lower non-256-bit vectors
988       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
989           || (MVT(VT).getSizeInBits() < 256))
990         continue;
991       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
992       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
993       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
994       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
995       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
996     }
997     // Custom-lower insert_subvector and extract_subvector based on
998     // the result type.
999     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1000          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1001          ++i) {
1002       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-256-bit vectors
1004       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1005         continue;
1006
1007       if (MVT(VT).getSizeInBits() == 128) {
1008         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1009       }
1010       else if (MVT(VT).getSizeInBits() == 256) {
1011         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1012       }
1013     }
1014
1015     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1016     // Don't promote loads because we need them for VPERM vector index versions.
1017
1018     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1019          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1020          VT++) {
1021       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1022           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1023         continue;
1024       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1025       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1026       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1027       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1028       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1029       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1030       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1031       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1032       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1033       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1034     }
1035   }
1036
1037   // We want to custom lower some of our intrinsics.
1038   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1039
1040
1041   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1042   // handle type legalization for these operations here.
1043   //
1044   // FIXME: We really should do custom legalization for addition and
1045   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1046   // than generic legalization for 64-bit multiplication-with-overflow, though.
1047   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1048     // Add/Sub/Mul with overflow operations are custom lowered.
1049     MVT VT = IntVTs[i];
1050     setOperationAction(ISD::SADDO, VT, Custom);
1051     setOperationAction(ISD::UADDO, VT, Custom);
1052     setOperationAction(ISD::SSUBO, VT, Custom);
1053     setOperationAction(ISD::USUBO, VT, Custom);
1054     setOperationAction(ISD::SMULO, VT, Custom);
1055     setOperationAction(ISD::UMULO, VT, Custom);
1056   }
1057
1058   // There are no 8-bit 3-address imul/mul instructions
1059   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1060   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1061
1062   if (!Subtarget->is64Bit()) {
1063     // These libcalls are not available in 32-bit.
1064     setLibcallName(RTLIB::SHL_I128, 0);
1065     setLibcallName(RTLIB::SRL_I128, 0);
1066     setLibcallName(RTLIB::SRA_I128, 0);
1067   }
1068
1069   // We have target-specific dag combine patterns for the following nodes:
1070   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1071   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1072   setTargetDAGCombine(ISD::BUILD_VECTOR);
1073   setTargetDAGCombine(ISD::SELECT);
1074   setTargetDAGCombine(ISD::SHL);
1075   setTargetDAGCombine(ISD::SRA);
1076   setTargetDAGCombine(ISD::SRL);
1077   setTargetDAGCombine(ISD::OR);
1078   setTargetDAGCombine(ISD::AND);
1079   setTargetDAGCombine(ISD::ADD);
1080   setTargetDAGCombine(ISD::SUB);
1081   setTargetDAGCombine(ISD::STORE);
1082   setTargetDAGCombine(ISD::ZERO_EXTEND);
1083   if (Subtarget->is64Bit())
1084     setTargetDAGCombine(ISD::MUL);
1085
1086   computeRegisterProperties();
1087
1088   // On Darwin, -Os means optimize for size without hurting performance,
1089   // do not reduce the limit.
1090   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1091   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1092   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1093   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1094   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1095   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1096   setPrefLoopAlignment(16);
1097   benefitFromCodePlacementOpt = true;
1098 }
1099
1100
1101 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1102   return MVT::i8;
1103 }
1104
1105
1106 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1107 /// the desired ByVal argument alignment.
1108 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1109   if (MaxAlign == 16)
1110     return;
1111   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1112     if (VTy->getBitWidth() == 128)
1113       MaxAlign = 16;
1114   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1115     unsigned EltAlign = 0;
1116     getMaxByValAlign(ATy->getElementType(), EltAlign);
1117     if (EltAlign > MaxAlign)
1118       MaxAlign = EltAlign;
1119   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1120     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1121       unsigned EltAlign = 0;
1122       getMaxByValAlign(STy->getElementType(i), EltAlign);
1123       if (EltAlign > MaxAlign)
1124         MaxAlign = EltAlign;
1125       if (MaxAlign == 16)
1126         break;
1127     }
1128   }
1129   return;
1130 }
1131
1132 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1133 /// function arguments in the caller parameter area. For X86, aggregates
1134 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1135 /// are at 4-byte boundaries.
1136 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1137   if (Subtarget->is64Bit()) {
1138     // Max of 8 and alignment of type.
1139     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1140     if (TyAlign > 8)
1141       return TyAlign;
1142     return 8;
1143   }
1144
1145   unsigned Align = 4;
1146   if (Subtarget->hasXMM())
1147     getMaxByValAlign(Ty, Align);
1148   return Align;
1149 }
1150
1151 /// getOptimalMemOpType - Returns the target specific optimal type for load
1152 /// and store operations as a result of memset, memcpy, and memmove
1153 /// lowering. If DstAlign is zero that means it's safe to destination
1154 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1155 /// means there isn't a need to check it against alignment requirement,
1156 /// probably because the source does not need to be loaded. If
1157 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1158 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1159 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1160 /// constant so it does not need to be loaded.
1161 /// It returns EVT::Other if the type should be determined using generic
1162 /// target-independent logic.
1163 EVT
1164 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1165                                        unsigned DstAlign, unsigned SrcAlign,
1166                                        bool NonScalarIntSafe,
1167                                        bool MemcpyStrSrc,
1168                                        MachineFunction &MF) const {
1169   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1170   // linux.  This is because the stack realignment code can't handle certain
1171   // cases like PR2962.  This should be removed when PR2962 is fixed.
1172   const Function *F = MF.getFunction();
1173   if (NonScalarIntSafe &&
1174       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1175     if (Size >= 16 &&
1176         (Subtarget->isUnalignedMemAccessFast() ||
1177          ((DstAlign == 0 || DstAlign >= 16) &&
1178           (SrcAlign == 0 || SrcAlign >= 16))) &&
1179         Subtarget->getStackAlignment() >= 16) {
1180       if (Subtarget->hasSSE2())
1181         return MVT::v4i32;
1182       if (Subtarget->hasSSE1())
1183         return MVT::v4f32;
1184     } else if (!MemcpyStrSrc && Size >= 8 &&
1185                !Subtarget->is64Bit() &&
1186                Subtarget->getStackAlignment() >= 8 &&
1187                Subtarget->hasXMMInt()) {
1188       // Do not use f64 to lower memcpy if source is string constant. It's
1189       // better to use i32 to avoid the loads.
1190       return MVT::f64;
1191     }
1192   }
1193   if (Subtarget->is64Bit() && Size >= 8)
1194     return MVT::i64;
1195   return MVT::i32;
1196 }
1197
1198 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1199 /// current function.  The returned value is a member of the
1200 /// MachineJumpTableInfo::JTEntryKind enum.
1201 unsigned X86TargetLowering::getJumpTableEncoding() const {
1202   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1203   // symbol.
1204   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1205       Subtarget->isPICStyleGOT())
1206     return MachineJumpTableInfo::EK_Custom32;
1207
1208   // Otherwise, use the normal jump table encoding heuristics.
1209   return TargetLowering::getJumpTableEncoding();
1210 }
1211
1212 const MCExpr *
1213 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1214                                              const MachineBasicBlock *MBB,
1215                                              unsigned uid,MCContext &Ctx) const{
1216   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1217          Subtarget->isPICStyleGOT());
1218   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1219   // entries.
1220   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1221                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1222 }
1223
1224 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1225 /// jumptable.
1226 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1227                                                     SelectionDAG &DAG) const {
1228   if (!Subtarget->is64Bit())
1229     // This doesn't have DebugLoc associated with it, but is not really the
1230     // same as a Register.
1231     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1232   return Table;
1233 }
1234
1235 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1236 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1237 /// MCExpr.
1238 const MCExpr *X86TargetLowering::
1239 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1240                              MCContext &Ctx) const {
1241   // X86-64 uses RIP relative addressing based on the jump table label.
1242   if (Subtarget->isPICStyleRIPRel())
1243     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1244
1245   // Otherwise, the reference is relative to the PIC base.
1246   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1247 }
1248
1249 /// getFunctionAlignment - Return the Log2 alignment of this function.
1250 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1251   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1252 }
1253
1254 // FIXME: Why this routine is here? Move to RegInfo!
1255 std::pair<const TargetRegisterClass*, uint8_t>
1256 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1257   const TargetRegisterClass *RRC = 0;
1258   uint8_t Cost = 1;
1259   switch (VT.getSimpleVT().SimpleTy) {
1260   default:
1261     return TargetLowering::findRepresentativeClass(VT);
1262   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1263     RRC = (Subtarget->is64Bit()
1264            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1265     break;
1266   case MVT::x86mmx:
1267     RRC = X86::VR64RegisterClass;
1268     break;
1269   case MVT::f32: case MVT::f64:
1270   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1271   case MVT::v4f32: case MVT::v2f64:
1272   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1273   case MVT::v4f64:
1274     RRC = X86::VR128RegisterClass;
1275     break;
1276   }
1277   return std::make_pair(RRC, Cost);
1278 }
1279
1280 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1281                                                unsigned &Offset) const {
1282   if (!Subtarget->isTargetLinux())
1283     return false;
1284
1285   if (Subtarget->is64Bit()) {
1286     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1287     Offset = 0x28;
1288     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1289       AddressSpace = 256;
1290     else
1291       AddressSpace = 257;
1292   } else {
1293     // %gs:0x14 on i386
1294     Offset = 0x14;
1295     AddressSpace = 256;
1296   }
1297   return true;
1298 }
1299
1300
1301 //===----------------------------------------------------------------------===//
1302 //               Return Value Calling Convention Implementation
1303 //===----------------------------------------------------------------------===//
1304
1305 #include "X86GenCallingConv.inc"
1306
1307 bool
1308 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1309                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1310                         LLVMContext &Context) const {
1311   SmallVector<CCValAssign, 16> RVLocs;
1312   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1313                  RVLocs, Context);
1314   return CCInfo.CheckReturn(Outs, RetCC_X86);
1315 }
1316
1317 SDValue
1318 X86TargetLowering::LowerReturn(SDValue Chain,
1319                                CallingConv::ID CallConv, bool isVarArg,
1320                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1321                                const SmallVectorImpl<SDValue> &OutVals,
1322                                DebugLoc dl, SelectionDAG &DAG) const {
1323   MachineFunction &MF = DAG.getMachineFunction();
1324   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1325
1326   SmallVector<CCValAssign, 16> RVLocs;
1327   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1328                  RVLocs, *DAG.getContext());
1329   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1330
1331   // Add the regs to the liveout set for the function.
1332   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1333   for (unsigned i = 0; i != RVLocs.size(); ++i)
1334     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1335       MRI.addLiveOut(RVLocs[i].getLocReg());
1336
1337   SDValue Flag;
1338
1339   SmallVector<SDValue, 6> RetOps;
1340   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1341   // Operand #1 = Bytes To Pop
1342   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1343                    MVT::i16));
1344
1345   // Copy the result values into the output registers.
1346   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1347     CCValAssign &VA = RVLocs[i];
1348     assert(VA.isRegLoc() && "Can only return in registers!");
1349     SDValue ValToCopy = OutVals[i];
1350     EVT ValVT = ValToCopy.getValueType();
1351
1352     // If this is x86-64, and we disabled SSE, we can't return FP values,
1353     // or SSE or MMX vectors.
1354     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1355          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1356           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1357       report_fatal_error("SSE register return with SSE disabled");
1358     }
1359     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1360     // llvm-gcc has never done it right and no one has noticed, so this
1361     // should be OK for now.
1362     if (ValVT == MVT::f64 &&
1363         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1364       report_fatal_error("SSE2 register return with SSE2 disabled");
1365
1366     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1367     // the RET instruction and handled by the FP Stackifier.
1368     if (VA.getLocReg() == X86::ST0 ||
1369         VA.getLocReg() == X86::ST1) {
1370       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1371       // change the value to the FP stack register class.
1372       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1373         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1374       RetOps.push_back(ValToCopy);
1375       // Don't emit a copytoreg.
1376       continue;
1377     }
1378
1379     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1380     // which is returned in RAX / RDX.
1381     if (Subtarget->is64Bit()) {
1382       if (ValVT == MVT::x86mmx) {
1383         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1384           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1385           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1386                                   ValToCopy);
1387           // If we don't have SSE2 available, convert to v4f32 so the generated
1388           // register is legal.
1389           if (!Subtarget->hasSSE2())
1390             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1391         }
1392       }
1393     }
1394
1395     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1396     Flag = Chain.getValue(1);
1397   }
1398
1399   // The x86-64 ABI for returning structs by value requires that we copy
1400   // the sret argument into %rax for the return. We saved the argument into
1401   // a virtual register in the entry block, so now we copy the value out
1402   // and into %rax.
1403   if (Subtarget->is64Bit() &&
1404       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1405     MachineFunction &MF = DAG.getMachineFunction();
1406     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1407     unsigned Reg = FuncInfo->getSRetReturnReg();
1408     assert(Reg &&
1409            "SRetReturnReg should have been set in LowerFormalArguments().");
1410     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1411
1412     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1413     Flag = Chain.getValue(1);
1414
1415     // RAX now acts like a return value.
1416     MRI.addLiveOut(X86::RAX);
1417   }
1418
1419   RetOps[0] = Chain;  // Update chain.
1420
1421   // Add the flag if we have it.
1422   if (Flag.getNode())
1423     RetOps.push_back(Flag);
1424
1425   return DAG.getNode(X86ISD::RET_FLAG, dl,
1426                      MVT::Other, &RetOps[0], RetOps.size());
1427 }
1428
1429 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1430   if (N->getNumValues() != 1)
1431     return false;
1432   if (!N->hasNUsesOfValue(1, 0))
1433     return false;
1434
1435   SDNode *Copy = *N->use_begin();
1436   if (Copy->getOpcode() != ISD::CopyToReg &&
1437       Copy->getOpcode() != ISD::FP_EXTEND)
1438     return false;
1439
1440   bool HasRet = false;
1441   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1442        UI != UE; ++UI) {
1443     if (UI->getOpcode() != X86ISD::RET_FLAG)
1444       return false;
1445     HasRet = true;
1446   }
1447
1448   return HasRet;
1449 }
1450
1451 MVT
1452 X86TargetLowering::getTypeForExtArgOrReturn(EVT VT,
1453                                             ISD::NodeType ExtendKind) const {
1454   // TODO: Is this also valid on 32-bit?
1455   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1456     return MVT::i8;
1457   return MVT::i32;
1458 }
1459
1460 /// LowerCallResult - Lower the result values of a call into the
1461 /// appropriate copies out of appropriate physical registers.
1462 ///
1463 SDValue
1464 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1465                                    CallingConv::ID CallConv, bool isVarArg,
1466                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1467                                    DebugLoc dl, SelectionDAG &DAG,
1468                                    SmallVectorImpl<SDValue> &InVals) const {
1469
1470   // Assign locations to each value returned by this call.
1471   SmallVector<CCValAssign, 16> RVLocs;
1472   bool Is64Bit = Subtarget->is64Bit();
1473   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1474                  RVLocs, *DAG.getContext());
1475   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1476
1477   // Copy all of the result registers out of their specified physreg.
1478   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1479     CCValAssign &VA = RVLocs[i];
1480     EVT CopyVT = VA.getValVT();
1481
1482     // If this is x86-64, and we disabled SSE, we can't return FP values
1483     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1484         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1485       report_fatal_error("SSE register return with SSE disabled");
1486     }
1487
1488     SDValue Val;
1489
1490     // If this is a call to a function that returns an fp value on the floating
1491     // point stack, we must guarantee the the value is popped from the stack, so
1492     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1493     // if the return value is not used. We use the FpGET_ST0 instructions
1494     // instead.
1495     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1496       // If we prefer to use the value in xmm registers, copy it out as f80 and
1497       // use a truncate to move it from fp stack reg to xmm reg.
1498       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1499       bool isST0 = VA.getLocReg() == X86::ST0;
1500       unsigned Opc = 0;
1501       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1502       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1503       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1504       SDValue Ops[] = { Chain, InFlag };
1505       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1506                                          Ops, 2), 1);
1507       Val = Chain.getValue(0);
1508
1509       // Round the f80 to the right size, which also moves it to the appropriate
1510       // xmm register.
1511       if (CopyVT != VA.getValVT())
1512         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1513                           // This truncation won't change the value.
1514                           DAG.getIntPtrConstant(1));
1515     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1516       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1517       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1518         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1519                                    MVT::v2i64, InFlag).getValue(1);
1520         Val = Chain.getValue(0);
1521         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1522                           Val, DAG.getConstant(0, MVT::i64));
1523       } else {
1524         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1525                                    MVT::i64, InFlag).getValue(1);
1526         Val = Chain.getValue(0);
1527       }
1528       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1529     } else {
1530       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1531                                  CopyVT, InFlag).getValue(1);
1532       Val = Chain.getValue(0);
1533     }
1534     InFlag = Chain.getValue(2);
1535     InVals.push_back(Val);
1536   }
1537
1538   return Chain;
1539 }
1540
1541
1542 //===----------------------------------------------------------------------===//
1543 //                C & StdCall & Fast Calling Convention implementation
1544 //===----------------------------------------------------------------------===//
1545 //  StdCall calling convention seems to be standard for many Windows' API
1546 //  routines and around. It differs from C calling convention just a little:
1547 //  callee should clean up the stack, not caller. Symbols should be also
1548 //  decorated in some fancy way :) It doesn't support any vector arguments.
1549 //  For info on fast calling convention see Fast Calling Convention (tail call)
1550 //  implementation LowerX86_32FastCCCallTo.
1551
1552 /// CallIsStructReturn - Determines whether a call uses struct return
1553 /// semantics.
1554 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1555   if (Outs.empty())
1556     return false;
1557
1558   return Outs[0].Flags.isSRet();
1559 }
1560
1561 /// ArgsAreStructReturn - Determines whether a function uses struct
1562 /// return semantics.
1563 static bool
1564 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1565   if (Ins.empty())
1566     return false;
1567
1568   return Ins[0].Flags.isSRet();
1569 }
1570
1571 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1572 /// by "Src" to address "Dst" with size and alignment information specified by
1573 /// the specific parameter attribute. The copy will be passed as a byval
1574 /// function parameter.
1575 static SDValue
1576 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1577                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1578                           DebugLoc dl) {
1579   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1580
1581   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1582                        /*isVolatile*/false, /*AlwaysInline=*/true,
1583                        MachinePointerInfo(), MachinePointerInfo());
1584 }
1585
1586 /// IsTailCallConvention - Return true if the calling convention is one that
1587 /// supports tail call optimization.
1588 static bool IsTailCallConvention(CallingConv::ID CC) {
1589   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1590 }
1591
1592 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1593 /// a tailcall target by changing its ABI.
1594 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1595   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1596 }
1597
1598 SDValue
1599 X86TargetLowering::LowerMemArgument(SDValue Chain,
1600                                     CallingConv::ID CallConv,
1601                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1602                                     DebugLoc dl, SelectionDAG &DAG,
1603                                     const CCValAssign &VA,
1604                                     MachineFrameInfo *MFI,
1605                                     unsigned i) const {
1606   // Create the nodes corresponding to a load from this parameter slot.
1607   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1608   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1609   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1610   EVT ValVT;
1611
1612   // If value is passed by pointer we have address passed instead of the value
1613   // itself.
1614   if (VA.getLocInfo() == CCValAssign::Indirect)
1615     ValVT = VA.getLocVT();
1616   else
1617     ValVT = VA.getValVT();
1618
1619   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1620   // changed with more analysis.
1621   // In case of tail call optimization mark all arguments mutable. Since they
1622   // could be overwritten by lowering of arguments in case of a tail call.
1623   if (Flags.isByVal()) {
1624     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1625                                     VA.getLocMemOffset(), isImmutable);
1626     return DAG.getFrameIndex(FI, getPointerTy());
1627   } else {
1628     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1629                                     VA.getLocMemOffset(), isImmutable);
1630     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1631     return DAG.getLoad(ValVT, dl, Chain, FIN,
1632                        MachinePointerInfo::getFixedStack(FI),
1633                        false, false, 0);
1634   }
1635 }
1636
1637 SDValue
1638 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1639                                         CallingConv::ID CallConv,
1640                                         bool isVarArg,
1641                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1642                                         DebugLoc dl,
1643                                         SelectionDAG &DAG,
1644                                         SmallVectorImpl<SDValue> &InVals)
1645                                           const {
1646   MachineFunction &MF = DAG.getMachineFunction();
1647   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1648
1649   const Function* Fn = MF.getFunction();
1650   if (Fn->hasExternalLinkage() &&
1651       Subtarget->isTargetCygMing() &&
1652       Fn->getName() == "main")
1653     FuncInfo->setForceFramePointer(true);
1654
1655   MachineFrameInfo *MFI = MF.getFrameInfo();
1656   bool Is64Bit = Subtarget->is64Bit();
1657   bool IsWin64 = Subtarget->isTargetWin64();
1658
1659   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1660          "Var args not supported with calling convention fastcc or ghc");
1661
1662   // Assign locations to all of the incoming arguments.
1663   SmallVector<CCValAssign, 16> ArgLocs;
1664   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1665                  ArgLocs, *DAG.getContext());
1666
1667   // Allocate shadow area for Win64
1668   if (IsWin64) {
1669     CCInfo.AllocateStack(32, 8);
1670   }
1671
1672   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1673
1674   unsigned LastVal = ~0U;
1675   SDValue ArgValue;
1676   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1677     CCValAssign &VA = ArgLocs[i];
1678     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1679     // places.
1680     assert(VA.getValNo() != LastVal &&
1681            "Don't support value assigned to multiple locs yet");
1682     LastVal = VA.getValNo();
1683
1684     if (VA.isRegLoc()) {
1685       EVT RegVT = VA.getLocVT();
1686       TargetRegisterClass *RC = NULL;
1687       if (RegVT == MVT::i32)
1688         RC = X86::GR32RegisterClass;
1689       else if (Is64Bit && RegVT == MVT::i64)
1690         RC = X86::GR64RegisterClass;
1691       else if (RegVT == MVT::f32)
1692         RC = X86::FR32RegisterClass;
1693       else if (RegVT == MVT::f64)
1694         RC = X86::FR64RegisterClass;
1695       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1696         RC = X86::VR256RegisterClass;
1697       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1698         RC = X86::VR128RegisterClass;
1699       else if (RegVT == MVT::x86mmx)
1700         RC = X86::VR64RegisterClass;
1701       else
1702         llvm_unreachable("Unknown argument type!");
1703
1704       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1705       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1706
1707       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1708       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1709       // right size.
1710       if (VA.getLocInfo() == CCValAssign::SExt)
1711         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1712                                DAG.getValueType(VA.getValVT()));
1713       else if (VA.getLocInfo() == CCValAssign::ZExt)
1714         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1715                                DAG.getValueType(VA.getValVT()));
1716       else if (VA.getLocInfo() == CCValAssign::BCvt)
1717         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1718
1719       if (VA.isExtInLoc()) {
1720         // Handle MMX values passed in XMM regs.
1721         if (RegVT.isVector()) {
1722           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1723                                  ArgValue);
1724         } else
1725           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1726       }
1727     } else {
1728       assert(VA.isMemLoc());
1729       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1730     }
1731
1732     // If value is passed via pointer - do a load.
1733     if (VA.getLocInfo() == CCValAssign::Indirect)
1734       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1735                              MachinePointerInfo(), false, false, 0);
1736
1737     InVals.push_back(ArgValue);
1738   }
1739
1740   // The x86-64 ABI for returning structs by value requires that we copy
1741   // the sret argument into %rax for the return. Save the argument into
1742   // a virtual register so that we can access it from the return points.
1743   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1744     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1745     unsigned Reg = FuncInfo->getSRetReturnReg();
1746     if (!Reg) {
1747       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1748       FuncInfo->setSRetReturnReg(Reg);
1749     }
1750     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1751     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1752   }
1753
1754   unsigned StackSize = CCInfo.getNextStackOffset();
1755   // Align stack specially for tail calls.
1756   if (FuncIsMadeTailCallSafe(CallConv))
1757     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1758
1759   // If the function takes variable number of arguments, make a frame index for
1760   // the start of the first vararg value... for expansion of llvm.va_start.
1761   if (isVarArg) {
1762     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1763                     CallConv != CallingConv::X86_ThisCall)) {
1764       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1765     }
1766     if (Is64Bit) {
1767       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1768
1769       // FIXME: We should really autogenerate these arrays
1770       static const unsigned GPR64ArgRegsWin64[] = {
1771         X86::RCX, X86::RDX, X86::R8,  X86::R9
1772       };
1773       static const unsigned GPR64ArgRegs64Bit[] = {
1774         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1775       };
1776       static const unsigned XMMArgRegs64Bit[] = {
1777         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1778         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1779       };
1780       const unsigned *GPR64ArgRegs;
1781       unsigned NumXMMRegs = 0;
1782
1783       if (IsWin64) {
1784         // The XMM registers which might contain var arg parameters are shadowed
1785         // in their paired GPR.  So we only need to save the GPR to their home
1786         // slots.
1787         TotalNumIntRegs = 4;
1788         GPR64ArgRegs = GPR64ArgRegsWin64;
1789       } else {
1790         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1791         GPR64ArgRegs = GPR64ArgRegs64Bit;
1792
1793         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1794       }
1795       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1796                                                        TotalNumIntRegs);
1797
1798       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1799       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1800              "SSE register cannot be used when SSE is disabled!");
1801       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1802              "SSE register cannot be used when SSE is disabled!");
1803       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1804         // Kernel mode asks for SSE to be disabled, so don't push them
1805         // on the stack.
1806         TotalNumXMMRegs = 0;
1807
1808       if (IsWin64) {
1809         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1810         // Get to the caller-allocated home save location.  Add 8 to account
1811         // for the return address.
1812         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1813         FuncInfo->setRegSaveFrameIndex(
1814           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1815         // Fixup to set vararg frame on shadow area (4 x i64).
1816         if (NumIntRegs < 4)
1817           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1818       } else {
1819         // For X86-64, if there are vararg parameters that are passed via
1820         // registers, then we must store them to their spots on the stack so they
1821         // may be loaded by deferencing the result of va_next.
1822         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1823         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1824         FuncInfo->setRegSaveFrameIndex(
1825           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1826                                false));
1827       }
1828
1829       // Store the integer parameter registers.
1830       SmallVector<SDValue, 8> MemOps;
1831       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1832                                         getPointerTy());
1833       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1834       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1835         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1836                                   DAG.getIntPtrConstant(Offset));
1837         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1838                                      X86::GR64RegisterClass);
1839         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1840         SDValue Store =
1841           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1842                        MachinePointerInfo::getFixedStack(
1843                          FuncInfo->getRegSaveFrameIndex(), Offset),
1844                        false, false, 0);
1845         MemOps.push_back(Store);
1846         Offset += 8;
1847       }
1848
1849       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1850         // Now store the XMM (fp + vector) parameter registers.
1851         SmallVector<SDValue, 11> SaveXMMOps;
1852         SaveXMMOps.push_back(Chain);
1853
1854         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1855         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1856         SaveXMMOps.push_back(ALVal);
1857
1858         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1859                                FuncInfo->getRegSaveFrameIndex()));
1860         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1861                                FuncInfo->getVarArgsFPOffset()));
1862
1863         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1864           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1865                                        X86::VR128RegisterClass);
1866           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1867           SaveXMMOps.push_back(Val);
1868         }
1869         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1870                                      MVT::Other,
1871                                      &SaveXMMOps[0], SaveXMMOps.size()));
1872       }
1873
1874       if (!MemOps.empty())
1875         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1876                             &MemOps[0], MemOps.size());
1877     }
1878   }
1879
1880   // Some CCs need callee pop.
1881   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1882     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1883   } else {
1884     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1885     // If this is an sret function, the return should pop the hidden pointer.
1886     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1887       FuncInfo->setBytesToPopOnReturn(4);
1888   }
1889
1890   if (!Is64Bit) {
1891     // RegSaveFrameIndex is X86-64 only.
1892     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1893     if (CallConv == CallingConv::X86_FastCall ||
1894         CallConv == CallingConv::X86_ThisCall)
1895       // fastcc functions can't have varargs.
1896       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1897   }
1898
1899   return Chain;
1900 }
1901
1902 SDValue
1903 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1904                                     SDValue StackPtr, SDValue Arg,
1905                                     DebugLoc dl, SelectionDAG &DAG,
1906                                     const CCValAssign &VA,
1907                                     ISD::ArgFlagsTy Flags) const {
1908   unsigned LocMemOffset = VA.getLocMemOffset();
1909   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1910   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1911   if (Flags.isByVal())
1912     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1913
1914   return DAG.getStore(Chain, dl, Arg, PtrOff,
1915                       MachinePointerInfo::getStack(LocMemOffset),
1916                       false, false, 0);
1917 }
1918
1919 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1920 /// optimization is performed and it is required.
1921 SDValue
1922 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1923                                            SDValue &OutRetAddr, SDValue Chain,
1924                                            bool IsTailCall, bool Is64Bit,
1925                                            int FPDiff, DebugLoc dl) const {
1926   // Adjust the Return address stack slot.
1927   EVT VT = getPointerTy();
1928   OutRetAddr = getReturnAddressFrameIndex(DAG);
1929
1930   // Load the "old" Return address.
1931   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1932                            false, false, 0);
1933   return SDValue(OutRetAddr.getNode(), 1);
1934 }
1935
1936 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1937 /// optimization is performed and it is required (FPDiff!=0).
1938 static SDValue
1939 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1940                          SDValue Chain, SDValue RetAddrFrIdx,
1941                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1942   // Store the return address to the appropriate stack slot.
1943   if (!FPDiff) return Chain;
1944   // Calculate the new stack slot for the return address.
1945   int SlotSize = Is64Bit ? 8 : 4;
1946   int NewReturnAddrFI =
1947     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1948   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1949   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1950   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1951                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1952                        false, false, 0);
1953   return Chain;
1954 }
1955
1956 SDValue
1957 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1958                              CallingConv::ID CallConv, bool isVarArg,
1959                              bool &isTailCall,
1960                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1961                              const SmallVectorImpl<SDValue> &OutVals,
1962                              const SmallVectorImpl<ISD::InputArg> &Ins,
1963                              DebugLoc dl, SelectionDAG &DAG,
1964                              SmallVectorImpl<SDValue> &InVals) const {
1965   MachineFunction &MF = DAG.getMachineFunction();
1966   bool Is64Bit        = Subtarget->is64Bit();
1967   bool IsWin64        = Subtarget->isTargetWin64();
1968   bool IsStructRet    = CallIsStructReturn(Outs);
1969   bool IsSibcall      = false;
1970
1971   if (isTailCall) {
1972     // Check if it's really possible to do a tail call.
1973     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1974                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1975                                                    Outs, OutVals, Ins, DAG);
1976
1977     // Sibcalls are automatically detected tailcalls which do not require
1978     // ABI changes.
1979     if (!GuaranteedTailCallOpt && isTailCall)
1980       IsSibcall = true;
1981
1982     if (isTailCall)
1983       ++NumTailCalls;
1984   }
1985
1986   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1987          "Var args not supported with calling convention fastcc or ghc");
1988
1989   // Analyze operands of the call, assigning locations to each operand.
1990   SmallVector<CCValAssign, 16> ArgLocs;
1991   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1992                  ArgLocs, *DAG.getContext());
1993
1994   // Allocate shadow area for Win64
1995   if (IsWin64) {
1996     CCInfo.AllocateStack(32, 8);
1997   }
1998
1999   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2000
2001   // Get a count of how many bytes are to be pushed on the stack.
2002   unsigned NumBytes = CCInfo.getNextStackOffset();
2003   if (IsSibcall)
2004     // This is a sibcall. The memory operands are available in caller's
2005     // own caller's stack.
2006     NumBytes = 0;
2007   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2008     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2009
2010   int FPDiff = 0;
2011   if (isTailCall && !IsSibcall) {
2012     // Lower arguments at fp - stackoffset + fpdiff.
2013     unsigned NumBytesCallerPushed =
2014       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2015     FPDiff = NumBytesCallerPushed - NumBytes;
2016
2017     // Set the delta of movement of the returnaddr stackslot.
2018     // But only set if delta is greater than previous delta.
2019     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2020       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2021   }
2022
2023   if (!IsSibcall)
2024     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2025
2026   SDValue RetAddrFrIdx;
2027   // Load return adress for tail calls.
2028   if (isTailCall && FPDiff)
2029     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2030                                     Is64Bit, FPDiff, dl);
2031
2032   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2033   SmallVector<SDValue, 8> MemOpChains;
2034   SDValue StackPtr;
2035
2036   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2037   // of tail call optimization arguments are handle later.
2038   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2039     CCValAssign &VA = ArgLocs[i];
2040     EVT RegVT = VA.getLocVT();
2041     SDValue Arg = OutVals[i];
2042     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2043     bool isByVal = Flags.isByVal();
2044
2045     // Promote the value if needed.
2046     switch (VA.getLocInfo()) {
2047     default: llvm_unreachable("Unknown loc info!");
2048     case CCValAssign::Full: break;
2049     case CCValAssign::SExt:
2050       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2051       break;
2052     case CCValAssign::ZExt:
2053       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2054       break;
2055     case CCValAssign::AExt:
2056       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2057         // Special case: passing MMX values in XMM registers.
2058         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2059         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2060         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2061       } else
2062         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2063       break;
2064     case CCValAssign::BCvt:
2065       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2066       break;
2067     case CCValAssign::Indirect: {
2068       // Store the argument.
2069       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2070       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2071       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2072                            MachinePointerInfo::getFixedStack(FI),
2073                            false, false, 0);
2074       Arg = SpillSlot;
2075       break;
2076     }
2077     }
2078
2079     if (VA.isRegLoc()) {
2080       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2081       if (isVarArg && IsWin64) {
2082         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2083         // shadow reg if callee is a varargs function.
2084         unsigned ShadowReg = 0;
2085         switch (VA.getLocReg()) {
2086         case X86::XMM0: ShadowReg = X86::RCX; break;
2087         case X86::XMM1: ShadowReg = X86::RDX; break;
2088         case X86::XMM2: ShadowReg = X86::R8; break;
2089         case X86::XMM3: ShadowReg = X86::R9; break;
2090         }
2091         if (ShadowReg)
2092           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2093       }
2094     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2095       assert(VA.isMemLoc());
2096       if (StackPtr.getNode() == 0)
2097         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2098       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2099                                              dl, DAG, VA, Flags));
2100     }
2101   }
2102
2103   if (!MemOpChains.empty())
2104     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2105                         &MemOpChains[0], MemOpChains.size());
2106
2107   // Build a sequence of copy-to-reg nodes chained together with token chain
2108   // and flag operands which copy the outgoing args into registers.
2109   SDValue InFlag;
2110   // Tail call byval lowering might overwrite argument registers so in case of
2111   // tail call optimization the copies to registers are lowered later.
2112   if (!isTailCall)
2113     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2114       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2115                                RegsToPass[i].second, InFlag);
2116       InFlag = Chain.getValue(1);
2117     }
2118
2119   if (Subtarget->isPICStyleGOT()) {
2120     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2121     // GOT pointer.
2122     if (!isTailCall) {
2123       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2124                                DAG.getNode(X86ISD::GlobalBaseReg,
2125                                            DebugLoc(), getPointerTy()),
2126                                InFlag);
2127       InFlag = Chain.getValue(1);
2128     } else {
2129       // If we are tail calling and generating PIC/GOT style code load the
2130       // address of the callee into ECX. The value in ecx is used as target of
2131       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2132       // for tail calls on PIC/GOT architectures. Normally we would just put the
2133       // address of GOT into ebx and then call target@PLT. But for tail calls
2134       // ebx would be restored (since ebx is callee saved) before jumping to the
2135       // target@PLT.
2136
2137       // Note: The actual moving to ECX is done further down.
2138       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2139       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2140           !G->getGlobal()->hasProtectedVisibility())
2141         Callee = LowerGlobalAddress(Callee, DAG);
2142       else if (isa<ExternalSymbolSDNode>(Callee))
2143         Callee = LowerExternalSymbol(Callee, DAG);
2144     }
2145   }
2146
2147   if (Is64Bit && isVarArg && !IsWin64) {
2148     // From AMD64 ABI document:
2149     // For calls that may call functions that use varargs or stdargs
2150     // (prototype-less calls or calls to functions containing ellipsis (...) in
2151     // the declaration) %al is used as hidden argument to specify the number
2152     // of SSE registers used. The contents of %al do not need to match exactly
2153     // the number of registers, but must be an ubound on the number of SSE
2154     // registers used and is in the range 0 - 8 inclusive.
2155
2156     // Count the number of XMM registers allocated.
2157     static const unsigned XMMArgRegs[] = {
2158       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2159       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2160     };
2161     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2162     assert((Subtarget->hasXMM() || !NumXMMRegs)
2163            && "SSE registers cannot be used when SSE is disabled");
2164
2165     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2166                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2167     InFlag = Chain.getValue(1);
2168   }
2169
2170
2171   // For tail calls lower the arguments to the 'real' stack slot.
2172   if (isTailCall) {
2173     // Force all the incoming stack arguments to be loaded from the stack
2174     // before any new outgoing arguments are stored to the stack, because the
2175     // outgoing stack slots may alias the incoming argument stack slots, and
2176     // the alias isn't otherwise explicit. This is slightly more conservative
2177     // than necessary, because it means that each store effectively depends
2178     // on every argument instead of just those arguments it would clobber.
2179     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2180
2181     SmallVector<SDValue, 8> MemOpChains2;
2182     SDValue FIN;
2183     int FI = 0;
2184     // Do not flag preceeding copytoreg stuff together with the following stuff.
2185     InFlag = SDValue();
2186     if (GuaranteedTailCallOpt) {
2187       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2188         CCValAssign &VA = ArgLocs[i];
2189         if (VA.isRegLoc())
2190           continue;
2191         assert(VA.isMemLoc());
2192         SDValue Arg = OutVals[i];
2193         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2194         // Create frame index.
2195         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2196         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2197         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2198         FIN = DAG.getFrameIndex(FI, getPointerTy());
2199
2200         if (Flags.isByVal()) {
2201           // Copy relative to framepointer.
2202           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2203           if (StackPtr.getNode() == 0)
2204             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2205                                           getPointerTy());
2206           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2207
2208           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2209                                                            ArgChain,
2210                                                            Flags, DAG, dl));
2211         } else {
2212           // Store relative to framepointer.
2213           MemOpChains2.push_back(
2214             DAG.getStore(ArgChain, dl, Arg, FIN,
2215                          MachinePointerInfo::getFixedStack(FI),
2216                          false, false, 0));
2217         }
2218       }
2219     }
2220
2221     if (!MemOpChains2.empty())
2222       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2223                           &MemOpChains2[0], MemOpChains2.size());
2224
2225     // Copy arguments to their registers.
2226     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2227       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2228                                RegsToPass[i].second, InFlag);
2229       InFlag = Chain.getValue(1);
2230     }
2231     InFlag =SDValue();
2232
2233     // Store the return address to the appropriate stack slot.
2234     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2235                                      FPDiff, dl);
2236   }
2237
2238   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2239     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2240     // In the 64-bit large code model, we have to make all calls
2241     // through a register, since the call instruction's 32-bit
2242     // pc-relative offset may not be large enough to hold the whole
2243     // address.
2244   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2245     // If the callee is a GlobalAddress node (quite common, every direct call
2246     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2247     // it.
2248
2249     // We should use extra load for direct calls to dllimported functions in
2250     // non-JIT mode.
2251     const GlobalValue *GV = G->getGlobal();
2252     if (!GV->hasDLLImportLinkage()) {
2253       unsigned char OpFlags = 0;
2254
2255       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2256       // external symbols most go through the PLT in PIC mode.  If the symbol
2257       // has hidden or protected visibility, or if it is static or local, then
2258       // we don't need to use the PLT - we can directly call it.
2259       if (Subtarget->isTargetELF() &&
2260           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2261           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2262         OpFlags = X86II::MO_PLT;
2263       } else if (Subtarget->isPICStyleStubAny() &&
2264                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2265                  Subtarget->getDarwinVers() < 9) {
2266         // PC-relative references to external symbols should go through $stub,
2267         // unless we're building with the leopard linker or later, which
2268         // automatically synthesizes these stubs.
2269         OpFlags = X86II::MO_DARWIN_STUB;
2270       }
2271
2272       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2273                                           G->getOffset(), OpFlags);
2274     }
2275   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2276     unsigned char OpFlags = 0;
2277
2278     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2279     // external symbols should go through the PLT.
2280     if (Subtarget->isTargetELF() &&
2281         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2282       OpFlags = X86II::MO_PLT;
2283     } else if (Subtarget->isPICStyleStubAny() &&
2284                Subtarget->getDarwinVers() < 9) {
2285       // PC-relative references to external symbols should go through $stub,
2286       // unless we're building with the leopard linker or later, which
2287       // automatically synthesizes these stubs.
2288       OpFlags = X86II::MO_DARWIN_STUB;
2289     }
2290
2291     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2292                                          OpFlags);
2293   }
2294
2295   // Returns a chain & a flag for retval copy to use.
2296   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2297   SmallVector<SDValue, 8> Ops;
2298
2299   if (!IsSibcall && isTailCall) {
2300     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2301                            DAG.getIntPtrConstant(0, true), InFlag);
2302     InFlag = Chain.getValue(1);
2303   }
2304
2305   Ops.push_back(Chain);
2306   Ops.push_back(Callee);
2307
2308   if (isTailCall)
2309     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2310
2311   // Add argument registers to the end of the list so that they are known live
2312   // into the call.
2313   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2314     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2315                                   RegsToPass[i].second.getValueType()));
2316
2317   // Add an implicit use GOT pointer in EBX.
2318   if (!isTailCall && Subtarget->isPICStyleGOT())
2319     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2320
2321   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2322   if (Is64Bit && isVarArg && !IsWin64)
2323     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2324
2325   if (InFlag.getNode())
2326     Ops.push_back(InFlag);
2327
2328   if (isTailCall) {
2329     // We used to do:
2330     //// If this is the first return lowered for this function, add the regs
2331     //// to the liveout set for the function.
2332     // This isn't right, although it's probably harmless on x86; liveouts
2333     // should be computed from returns not tail calls.  Consider a void
2334     // function making a tail call to a function returning int.
2335     return DAG.getNode(X86ISD::TC_RETURN, dl,
2336                        NodeTys, &Ops[0], Ops.size());
2337   }
2338
2339   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2340   InFlag = Chain.getValue(1);
2341
2342   // Create the CALLSEQ_END node.
2343   unsigned NumBytesForCalleeToPush;
2344   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2345     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2346   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2347     // If this is a call to a struct-return function, the callee
2348     // pops the hidden struct pointer, so we have to push it back.
2349     // This is common for Darwin/X86, Linux & Mingw32 targets.
2350     NumBytesForCalleeToPush = 4;
2351   else
2352     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2353
2354   // Returns a flag for retval copy to use.
2355   if (!IsSibcall) {
2356     Chain = DAG.getCALLSEQ_END(Chain,
2357                                DAG.getIntPtrConstant(NumBytes, true),
2358                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2359                                                      true),
2360                                InFlag);
2361     InFlag = Chain.getValue(1);
2362   }
2363
2364   // Handle result values, copying them out of physregs into vregs that we
2365   // return.
2366   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2367                          Ins, dl, DAG, InVals);
2368 }
2369
2370
2371 //===----------------------------------------------------------------------===//
2372 //                Fast Calling Convention (tail call) implementation
2373 //===----------------------------------------------------------------------===//
2374
2375 //  Like std call, callee cleans arguments, convention except that ECX is
2376 //  reserved for storing the tail called function address. Only 2 registers are
2377 //  free for argument passing (inreg). Tail call optimization is performed
2378 //  provided:
2379 //                * tailcallopt is enabled
2380 //                * caller/callee are fastcc
2381 //  On X86_64 architecture with GOT-style position independent code only local
2382 //  (within module) calls are supported at the moment.
2383 //  To keep the stack aligned according to platform abi the function
2384 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2385 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2386 //  If a tail called function callee has more arguments than the caller the
2387 //  caller needs to make sure that there is room to move the RETADDR to. This is
2388 //  achieved by reserving an area the size of the argument delta right after the
2389 //  original REtADDR, but before the saved framepointer or the spilled registers
2390 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2391 //  stack layout:
2392 //    arg1
2393 //    arg2
2394 //    RETADDR
2395 //    [ new RETADDR
2396 //      move area ]
2397 //    (possible EBP)
2398 //    ESI
2399 //    EDI
2400 //    local1 ..
2401
2402 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2403 /// for a 16 byte align requirement.
2404 unsigned
2405 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2406                                                SelectionDAG& DAG) const {
2407   MachineFunction &MF = DAG.getMachineFunction();
2408   const TargetMachine &TM = MF.getTarget();
2409   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2410   unsigned StackAlignment = TFI.getStackAlignment();
2411   uint64_t AlignMask = StackAlignment - 1;
2412   int64_t Offset = StackSize;
2413   uint64_t SlotSize = TD->getPointerSize();
2414   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2415     // Number smaller than 12 so just add the difference.
2416     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2417   } else {
2418     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2419     Offset = ((~AlignMask) & Offset) + StackAlignment +
2420       (StackAlignment-SlotSize);
2421   }
2422   return Offset;
2423 }
2424
2425 /// MatchingStackOffset - Return true if the given stack call argument is
2426 /// already available in the same position (relatively) of the caller's
2427 /// incoming argument stack.
2428 static
2429 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2430                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2431                          const X86InstrInfo *TII) {
2432   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2433   int FI = INT_MAX;
2434   if (Arg.getOpcode() == ISD::CopyFromReg) {
2435     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2436     if (!TargetRegisterInfo::isVirtualRegister(VR))
2437       return false;
2438     MachineInstr *Def = MRI->getVRegDef(VR);
2439     if (!Def)
2440       return false;
2441     if (!Flags.isByVal()) {
2442       if (!TII->isLoadFromStackSlot(Def, FI))
2443         return false;
2444     } else {
2445       unsigned Opcode = Def->getOpcode();
2446       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2447           Def->getOperand(1).isFI()) {
2448         FI = Def->getOperand(1).getIndex();
2449         Bytes = Flags.getByValSize();
2450       } else
2451         return false;
2452     }
2453   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2454     if (Flags.isByVal())
2455       // ByVal argument is passed in as a pointer but it's now being
2456       // dereferenced. e.g.
2457       // define @foo(%struct.X* %A) {
2458       //   tail call @bar(%struct.X* byval %A)
2459       // }
2460       return false;
2461     SDValue Ptr = Ld->getBasePtr();
2462     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2463     if (!FINode)
2464       return false;
2465     FI = FINode->getIndex();
2466   } else
2467     return false;
2468
2469   assert(FI != INT_MAX);
2470   if (!MFI->isFixedObjectIndex(FI))
2471     return false;
2472   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2473 }
2474
2475 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2476 /// for tail call optimization. Targets which want to do tail call
2477 /// optimization should implement this function.
2478 bool
2479 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2480                                                      CallingConv::ID CalleeCC,
2481                                                      bool isVarArg,
2482                                                      bool isCalleeStructRet,
2483                                                      bool isCallerStructRet,
2484                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2485                                     const SmallVectorImpl<SDValue> &OutVals,
2486                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2487                                                      SelectionDAG& DAG) const {
2488   if (!IsTailCallConvention(CalleeCC) &&
2489       CalleeCC != CallingConv::C)
2490     return false;
2491
2492   // If -tailcallopt is specified, make fastcc functions tail-callable.
2493   const MachineFunction &MF = DAG.getMachineFunction();
2494   const Function *CallerF = DAG.getMachineFunction().getFunction();
2495   CallingConv::ID CallerCC = CallerF->getCallingConv();
2496   bool CCMatch = CallerCC == CalleeCC;
2497
2498   if (GuaranteedTailCallOpt) {
2499     if (IsTailCallConvention(CalleeCC) && CCMatch)
2500       return true;
2501     return false;
2502   }
2503
2504   // Look for obvious safe cases to perform tail call optimization that do not
2505   // require ABI changes. This is what gcc calls sibcall.
2506
2507   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2508   // emit a special epilogue.
2509   if (RegInfo->needsStackRealignment(MF))
2510     return false;
2511
2512   // Do not sibcall optimize vararg calls unless the call site is not passing
2513   // any arguments.
2514   if (isVarArg && !Outs.empty())
2515     return false;
2516
2517   // Also avoid sibcall optimization if either caller or callee uses struct
2518   // return semantics.
2519   if (isCalleeStructRet || isCallerStructRet)
2520     return false;
2521
2522   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2523   // Therefore if it's not used by the call it is not safe to optimize this into
2524   // a sibcall.
2525   bool Unused = false;
2526   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2527     if (!Ins[i].Used) {
2528       Unused = true;
2529       break;
2530     }
2531   }
2532   if (Unused) {
2533     SmallVector<CCValAssign, 16> RVLocs;
2534     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2535                    RVLocs, *DAG.getContext());
2536     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2537     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2538       CCValAssign &VA = RVLocs[i];
2539       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2540         return false;
2541     }
2542   }
2543
2544   // If the calling conventions do not match, then we'd better make sure the
2545   // results are returned in the same way as what the caller expects.
2546   if (!CCMatch) {
2547     SmallVector<CCValAssign, 16> RVLocs1;
2548     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2549                     RVLocs1, *DAG.getContext());
2550     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2551
2552     SmallVector<CCValAssign, 16> RVLocs2;
2553     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2554                     RVLocs2, *DAG.getContext());
2555     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2556
2557     if (RVLocs1.size() != RVLocs2.size())
2558       return false;
2559     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2560       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2561         return false;
2562       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2563         return false;
2564       if (RVLocs1[i].isRegLoc()) {
2565         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2566           return false;
2567       } else {
2568         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2569           return false;
2570       }
2571     }
2572   }
2573
2574   // If the callee takes no arguments then go on to check the results of the
2575   // call.
2576   if (!Outs.empty()) {
2577     // Check if stack adjustment is needed. For now, do not do this if any
2578     // argument is passed on the stack.
2579     SmallVector<CCValAssign, 16> ArgLocs;
2580     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2581                    ArgLocs, *DAG.getContext());
2582
2583     // Allocate shadow area for Win64
2584     if (Subtarget->isTargetWin64()) {
2585       CCInfo.AllocateStack(32, 8);
2586     }
2587
2588     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2589     if (CCInfo.getNextStackOffset()) {
2590       MachineFunction &MF = DAG.getMachineFunction();
2591       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2592         return false;
2593
2594       // Check if the arguments are already laid out in the right way as
2595       // the caller's fixed stack objects.
2596       MachineFrameInfo *MFI = MF.getFrameInfo();
2597       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2598       const X86InstrInfo *TII =
2599         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2600       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2601         CCValAssign &VA = ArgLocs[i];
2602         SDValue Arg = OutVals[i];
2603         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2604         if (VA.getLocInfo() == CCValAssign::Indirect)
2605           return false;
2606         if (!VA.isRegLoc()) {
2607           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2608                                    MFI, MRI, TII))
2609             return false;
2610         }
2611       }
2612     }
2613
2614     // If the tailcall address may be in a register, then make sure it's
2615     // possible to register allocate for it. In 32-bit, the call address can
2616     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2617     // callee-saved registers are restored. These happen to be the same
2618     // registers used to pass 'inreg' arguments so watch out for those.
2619     if (!Subtarget->is64Bit() &&
2620         !isa<GlobalAddressSDNode>(Callee) &&
2621         !isa<ExternalSymbolSDNode>(Callee)) {
2622       unsigned NumInRegs = 0;
2623       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2624         CCValAssign &VA = ArgLocs[i];
2625         if (!VA.isRegLoc())
2626           continue;
2627         unsigned Reg = VA.getLocReg();
2628         switch (Reg) {
2629         default: break;
2630         case X86::EAX: case X86::EDX: case X86::ECX:
2631           if (++NumInRegs == 3)
2632             return false;
2633           break;
2634         }
2635       }
2636     }
2637   }
2638
2639   // An stdcall caller is expected to clean up its arguments; the callee
2640   // isn't going to do that.
2641   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2642     return false;
2643
2644   return true;
2645 }
2646
2647 FastISel *
2648 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2649   return X86::createFastISel(funcInfo);
2650 }
2651
2652
2653 //===----------------------------------------------------------------------===//
2654 //                           Other Lowering Hooks
2655 //===----------------------------------------------------------------------===//
2656
2657 static bool MayFoldLoad(SDValue Op) {
2658   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2659 }
2660
2661 static bool MayFoldIntoStore(SDValue Op) {
2662   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2663 }
2664
2665 static bool isTargetShuffle(unsigned Opcode) {
2666   switch(Opcode) {
2667   default: return false;
2668   case X86ISD::PSHUFD:
2669   case X86ISD::PSHUFHW:
2670   case X86ISD::PSHUFLW:
2671   case X86ISD::SHUFPD:
2672   case X86ISD::PALIGN:
2673   case X86ISD::SHUFPS:
2674   case X86ISD::MOVLHPS:
2675   case X86ISD::MOVLHPD:
2676   case X86ISD::MOVHLPS:
2677   case X86ISD::MOVLPS:
2678   case X86ISD::MOVLPD:
2679   case X86ISD::MOVSHDUP:
2680   case X86ISD::MOVSLDUP:
2681   case X86ISD::MOVDDUP:
2682   case X86ISD::MOVSS:
2683   case X86ISD::MOVSD:
2684   case X86ISD::UNPCKLPS:
2685   case X86ISD::UNPCKLPD:
2686   case X86ISD::VUNPCKLPS:
2687   case X86ISD::VUNPCKLPD:
2688   case X86ISD::VUNPCKLPSY:
2689   case X86ISD::VUNPCKLPDY:
2690   case X86ISD::PUNPCKLWD:
2691   case X86ISD::PUNPCKLBW:
2692   case X86ISD::PUNPCKLDQ:
2693   case X86ISD::PUNPCKLQDQ:
2694   case X86ISD::UNPCKHPS:
2695   case X86ISD::UNPCKHPD:
2696   case X86ISD::PUNPCKHWD:
2697   case X86ISD::PUNPCKHBW:
2698   case X86ISD::PUNPCKHDQ:
2699   case X86ISD::PUNPCKHQDQ:
2700     return true;
2701   }
2702   return false;
2703 }
2704
2705 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2706                                                SDValue V1, SelectionDAG &DAG) {
2707   switch(Opc) {
2708   default: llvm_unreachable("Unknown x86 shuffle node");
2709   case X86ISD::MOVSHDUP:
2710   case X86ISD::MOVSLDUP:
2711   case X86ISD::MOVDDUP:
2712     return DAG.getNode(Opc, dl, VT, V1);
2713   }
2714
2715   return SDValue();
2716 }
2717
2718 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2719                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2720   switch(Opc) {
2721   default: llvm_unreachable("Unknown x86 shuffle node");
2722   case X86ISD::PSHUFD:
2723   case X86ISD::PSHUFHW:
2724   case X86ISD::PSHUFLW:
2725     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2726   }
2727
2728   return SDValue();
2729 }
2730
2731 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2732                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2733   switch(Opc) {
2734   default: llvm_unreachable("Unknown x86 shuffle node");
2735   case X86ISD::PALIGN:
2736   case X86ISD::SHUFPD:
2737   case X86ISD::SHUFPS:
2738     return DAG.getNode(Opc, dl, VT, V1, V2,
2739                        DAG.getConstant(TargetMask, MVT::i8));
2740   }
2741   return SDValue();
2742 }
2743
2744 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2745                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2746   switch(Opc) {
2747   default: llvm_unreachable("Unknown x86 shuffle node");
2748   case X86ISD::MOVLHPS:
2749   case X86ISD::MOVLHPD:
2750   case X86ISD::MOVHLPS:
2751   case X86ISD::MOVLPS:
2752   case X86ISD::MOVLPD:
2753   case X86ISD::MOVSS:
2754   case X86ISD::MOVSD:
2755   case X86ISD::UNPCKLPS:
2756   case X86ISD::UNPCKLPD:
2757   case X86ISD::VUNPCKLPS:
2758   case X86ISD::VUNPCKLPD:
2759   case X86ISD::VUNPCKLPSY:
2760   case X86ISD::VUNPCKLPDY:
2761   case X86ISD::PUNPCKLWD:
2762   case X86ISD::PUNPCKLBW:
2763   case X86ISD::PUNPCKLDQ:
2764   case X86ISD::PUNPCKLQDQ:
2765   case X86ISD::UNPCKHPS:
2766   case X86ISD::UNPCKHPD:
2767   case X86ISD::PUNPCKHWD:
2768   case X86ISD::PUNPCKHBW:
2769   case X86ISD::PUNPCKHDQ:
2770   case X86ISD::PUNPCKHQDQ:
2771     return DAG.getNode(Opc, dl, VT, V1, V2);
2772   }
2773   return SDValue();
2774 }
2775
2776 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2777   MachineFunction &MF = DAG.getMachineFunction();
2778   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2779   int ReturnAddrIndex = FuncInfo->getRAIndex();
2780
2781   if (ReturnAddrIndex == 0) {
2782     // Set up a frame object for the return address.
2783     uint64_t SlotSize = TD->getPointerSize();
2784     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2785                                                            false);
2786     FuncInfo->setRAIndex(ReturnAddrIndex);
2787   }
2788
2789   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2790 }
2791
2792
2793 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2794                                        bool hasSymbolicDisplacement) {
2795   // Offset should fit into 32 bit immediate field.
2796   if (!isInt<32>(Offset))
2797     return false;
2798
2799   // If we don't have a symbolic displacement - we don't have any extra
2800   // restrictions.
2801   if (!hasSymbolicDisplacement)
2802     return true;
2803
2804   // FIXME: Some tweaks might be needed for medium code model.
2805   if (M != CodeModel::Small && M != CodeModel::Kernel)
2806     return false;
2807
2808   // For small code model we assume that latest object is 16MB before end of 31
2809   // bits boundary. We may also accept pretty large negative constants knowing
2810   // that all objects are in the positive half of address space.
2811   if (M == CodeModel::Small && Offset < 16*1024*1024)
2812     return true;
2813
2814   // For kernel code model we know that all object resist in the negative half
2815   // of 32bits address space. We may not accept negative offsets, since they may
2816   // be just off and we may accept pretty large positive ones.
2817   if (M == CodeModel::Kernel && Offset > 0)
2818     return true;
2819
2820   return false;
2821 }
2822
2823 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2824 /// specific condition code, returning the condition code and the LHS/RHS of the
2825 /// comparison to make.
2826 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2827                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2828   if (!isFP) {
2829     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2830       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2831         // X > -1   -> X == 0, jump !sign.
2832         RHS = DAG.getConstant(0, RHS.getValueType());
2833         return X86::COND_NS;
2834       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2835         // X < 0   -> X == 0, jump on sign.
2836         return X86::COND_S;
2837       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2838         // X < 1   -> X <= 0
2839         RHS = DAG.getConstant(0, RHS.getValueType());
2840         return X86::COND_LE;
2841       }
2842     }
2843
2844     switch (SetCCOpcode) {
2845     default: llvm_unreachable("Invalid integer condition!");
2846     case ISD::SETEQ:  return X86::COND_E;
2847     case ISD::SETGT:  return X86::COND_G;
2848     case ISD::SETGE:  return X86::COND_GE;
2849     case ISD::SETLT:  return X86::COND_L;
2850     case ISD::SETLE:  return X86::COND_LE;
2851     case ISD::SETNE:  return X86::COND_NE;
2852     case ISD::SETULT: return X86::COND_B;
2853     case ISD::SETUGT: return X86::COND_A;
2854     case ISD::SETULE: return X86::COND_BE;
2855     case ISD::SETUGE: return X86::COND_AE;
2856     }
2857   }
2858
2859   // First determine if it is required or is profitable to flip the operands.
2860
2861   // If LHS is a foldable load, but RHS is not, flip the condition.
2862   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2863       !ISD::isNON_EXTLoad(RHS.getNode())) {
2864     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2865     std::swap(LHS, RHS);
2866   }
2867
2868   switch (SetCCOpcode) {
2869   default: break;
2870   case ISD::SETOLT:
2871   case ISD::SETOLE:
2872   case ISD::SETUGT:
2873   case ISD::SETUGE:
2874     std::swap(LHS, RHS);
2875     break;
2876   }
2877
2878   // On a floating point condition, the flags are set as follows:
2879   // ZF  PF  CF   op
2880   //  0 | 0 | 0 | X > Y
2881   //  0 | 0 | 1 | X < Y
2882   //  1 | 0 | 0 | X == Y
2883   //  1 | 1 | 1 | unordered
2884   switch (SetCCOpcode) {
2885   default: llvm_unreachable("Condcode should be pre-legalized away");
2886   case ISD::SETUEQ:
2887   case ISD::SETEQ:   return X86::COND_E;
2888   case ISD::SETOLT:              // flipped
2889   case ISD::SETOGT:
2890   case ISD::SETGT:   return X86::COND_A;
2891   case ISD::SETOLE:              // flipped
2892   case ISD::SETOGE:
2893   case ISD::SETGE:   return X86::COND_AE;
2894   case ISD::SETUGT:              // flipped
2895   case ISD::SETULT:
2896   case ISD::SETLT:   return X86::COND_B;
2897   case ISD::SETUGE:              // flipped
2898   case ISD::SETULE:
2899   case ISD::SETLE:   return X86::COND_BE;
2900   case ISD::SETONE:
2901   case ISD::SETNE:   return X86::COND_NE;
2902   case ISD::SETUO:   return X86::COND_P;
2903   case ISD::SETO:    return X86::COND_NP;
2904   case ISD::SETOEQ:
2905   case ISD::SETUNE:  return X86::COND_INVALID;
2906   }
2907 }
2908
2909 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2910 /// code. Current x86 isa includes the following FP cmov instructions:
2911 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2912 static bool hasFPCMov(unsigned X86CC) {
2913   switch (X86CC) {
2914   default:
2915     return false;
2916   case X86::COND_B:
2917   case X86::COND_BE:
2918   case X86::COND_E:
2919   case X86::COND_P:
2920   case X86::COND_A:
2921   case X86::COND_AE:
2922   case X86::COND_NE:
2923   case X86::COND_NP:
2924     return true;
2925   }
2926 }
2927
2928 /// isFPImmLegal - Returns true if the target can instruction select the
2929 /// specified FP immediate natively. If false, the legalizer will
2930 /// materialize the FP immediate as a load from a constant pool.
2931 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2932   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2933     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2934       return true;
2935   }
2936   return false;
2937 }
2938
2939 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2940 /// the specified range (L, H].
2941 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2942   return (Val < 0) || (Val >= Low && Val < Hi);
2943 }
2944
2945 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2946 /// specified value.
2947 static bool isUndefOrEqual(int Val, int CmpVal) {
2948   if (Val < 0 || Val == CmpVal)
2949     return true;
2950   return false;
2951 }
2952
2953 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2954 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2955 /// the second operand.
2956 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2957   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2958     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2959   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2960     return (Mask[0] < 2 && Mask[1] < 2);
2961   return false;
2962 }
2963
2964 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2965   SmallVector<int, 8> M;
2966   N->getMask(M);
2967   return ::isPSHUFDMask(M, N->getValueType(0));
2968 }
2969
2970 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2971 /// is suitable for input to PSHUFHW.
2972 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2973   if (VT != MVT::v8i16)
2974     return false;
2975
2976   // Lower quadword copied in order or undef.
2977   for (int i = 0; i != 4; ++i)
2978     if (Mask[i] >= 0 && Mask[i] != i)
2979       return false;
2980
2981   // Upper quadword shuffled.
2982   for (int i = 4; i != 8; ++i)
2983     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2984       return false;
2985
2986   return true;
2987 }
2988
2989 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2990   SmallVector<int, 8> M;
2991   N->getMask(M);
2992   return ::isPSHUFHWMask(M, N->getValueType(0));
2993 }
2994
2995 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2996 /// is suitable for input to PSHUFLW.
2997 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2998   if (VT != MVT::v8i16)
2999     return false;
3000
3001   // Upper quadword copied in order.
3002   for (int i = 4; i != 8; ++i)
3003     if (Mask[i] >= 0 && Mask[i] != i)
3004       return false;
3005
3006   // Lower quadword shuffled.
3007   for (int i = 0; i != 4; ++i)
3008     if (Mask[i] >= 4)
3009       return false;
3010
3011   return true;
3012 }
3013
3014 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3015   SmallVector<int, 8> M;
3016   N->getMask(M);
3017   return ::isPSHUFLWMask(M, N->getValueType(0));
3018 }
3019
3020 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3021 /// is suitable for input to PALIGNR.
3022 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3023                           bool hasSSSE3) {
3024   int i, e = VT.getVectorNumElements();
3025
3026   // Do not handle v2i64 / v2f64 shuffles with palignr.
3027   if (e < 4 || !hasSSSE3)
3028     return false;
3029
3030   for (i = 0; i != e; ++i)
3031     if (Mask[i] >= 0)
3032       break;
3033
3034   // All undef, not a palignr.
3035   if (i == e)
3036     return false;
3037
3038   // Determine if it's ok to perform a palignr with only the LHS, since we
3039   // don't have access to the actual shuffle elements to see if RHS is undef.
3040   bool Unary = Mask[i] < (int)e;
3041   bool NeedsUnary = false;
3042
3043   int s = Mask[i] - i;
3044
3045   // Check the rest of the elements to see if they are consecutive.
3046   for (++i; i != e; ++i) {
3047     int m = Mask[i];
3048     if (m < 0)
3049       continue;
3050
3051     Unary = Unary && (m < (int)e);
3052     NeedsUnary = NeedsUnary || (m < s);
3053
3054     if (NeedsUnary && !Unary)
3055       return false;
3056     if (Unary && m != ((s+i) & (e-1)))
3057       return false;
3058     if (!Unary && m != (s+i))
3059       return false;
3060   }
3061   return true;
3062 }
3063
3064 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3065   SmallVector<int, 8> M;
3066   N->getMask(M);
3067   return ::isPALIGNRMask(M, N->getValueType(0), true);
3068 }
3069
3070 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3071 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3072 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3073   int NumElems = VT.getVectorNumElements();
3074   if (NumElems != 2 && NumElems != 4)
3075     return false;
3076
3077   int Half = NumElems / 2;
3078   for (int i = 0; i < Half; ++i)
3079     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3080       return false;
3081   for (int i = Half; i < NumElems; ++i)
3082     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3083       return false;
3084
3085   return true;
3086 }
3087
3088 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3089   SmallVector<int, 8> M;
3090   N->getMask(M);
3091   return ::isSHUFPMask(M, N->getValueType(0));
3092 }
3093
3094 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3095 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3096 /// half elements to come from vector 1 (which would equal the dest.) and
3097 /// the upper half to come from vector 2.
3098 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3099   int NumElems = VT.getVectorNumElements();
3100
3101   if (NumElems != 2 && NumElems != 4)
3102     return false;
3103
3104   int Half = NumElems / 2;
3105   for (int i = 0; i < Half; ++i)
3106     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3107       return false;
3108   for (int i = Half; i < NumElems; ++i)
3109     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3110       return false;
3111   return true;
3112 }
3113
3114 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3115   SmallVector<int, 8> M;
3116   N->getMask(M);
3117   return isCommutedSHUFPMask(M, N->getValueType(0));
3118 }
3119
3120 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3121 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3122 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3123   if (N->getValueType(0).getVectorNumElements() != 4)
3124     return false;
3125
3126   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3127   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3128          isUndefOrEqual(N->getMaskElt(1), 7) &&
3129          isUndefOrEqual(N->getMaskElt(2), 2) &&
3130          isUndefOrEqual(N->getMaskElt(3), 3);
3131 }
3132
3133 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3134 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3135 /// <2, 3, 2, 3>
3136 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3137   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3138
3139   if (NumElems != 4)
3140     return false;
3141
3142   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3143   isUndefOrEqual(N->getMaskElt(1), 3) &&
3144   isUndefOrEqual(N->getMaskElt(2), 2) &&
3145   isUndefOrEqual(N->getMaskElt(3), 3);
3146 }
3147
3148 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3149 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3150 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3151   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3152
3153   if (NumElems != 2 && NumElems != 4)
3154     return false;
3155
3156   for (unsigned i = 0; i < NumElems/2; ++i)
3157     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3158       return false;
3159
3160   for (unsigned i = NumElems/2; i < NumElems; ++i)
3161     if (!isUndefOrEqual(N->getMaskElt(i), i))
3162       return false;
3163
3164   return true;
3165 }
3166
3167 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3168 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3169 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3170   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3171
3172   if ((NumElems != 2 && NumElems != 4)
3173       || N->getValueType(0).getSizeInBits() > 128)
3174     return false;
3175
3176   for (unsigned i = 0; i < NumElems/2; ++i)
3177     if (!isUndefOrEqual(N->getMaskElt(i), i))
3178       return false;
3179
3180   for (unsigned i = 0; i < NumElems/2; ++i)
3181     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3182       return false;
3183
3184   return true;
3185 }
3186
3187 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3188 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3189 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3190                          bool V2IsSplat = false) {
3191   int NumElts = VT.getVectorNumElements();
3192   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3193     return false;
3194
3195   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3196   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3197   // sections.
3198   unsigned NumSections = VT.getSizeInBits() / 128;
3199   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3200   unsigned NumSectionElts = NumElts / NumSections;
3201
3202   unsigned Start = 0;
3203   unsigned End = NumSectionElts;
3204   for (unsigned s = 0; s < NumSections; ++s) {
3205     for (unsigned i = Start, j = s * NumSectionElts;
3206          i != End;
3207          i += 2, ++j) {
3208       int BitI  = Mask[i];
3209       int BitI1 = Mask[i+1];
3210       if (!isUndefOrEqual(BitI, j))
3211         return false;
3212       if (V2IsSplat) {
3213         if (!isUndefOrEqual(BitI1, NumElts))
3214           return false;
3215       } else {
3216         if (!isUndefOrEqual(BitI1, j + NumElts))
3217           return false;
3218       }
3219     }
3220     // Process the next 128 bits.
3221     Start += NumSectionElts;
3222     End += NumSectionElts;
3223   }
3224
3225   return true;
3226 }
3227
3228 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3229   SmallVector<int, 8> M;
3230   N->getMask(M);
3231   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3232 }
3233
3234 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3235 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3236 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3237                          bool V2IsSplat = false) {
3238   int NumElts = VT.getVectorNumElements();
3239   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3240     return false;
3241
3242   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3243     int BitI  = Mask[i];
3244     int BitI1 = Mask[i+1];
3245     if (!isUndefOrEqual(BitI, j + NumElts/2))
3246       return false;
3247     if (V2IsSplat) {
3248       if (isUndefOrEqual(BitI1, NumElts))
3249         return false;
3250     } else {
3251       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3252         return false;
3253     }
3254   }
3255   return true;
3256 }
3257
3258 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3259   SmallVector<int, 8> M;
3260   N->getMask(M);
3261   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3262 }
3263
3264 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3265 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3266 /// <0, 0, 1, 1>
3267 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3268   int NumElems = VT.getVectorNumElements();
3269   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3270     return false;
3271
3272   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3273   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3274   // sections.
3275   unsigned NumSections = VT.getSizeInBits() / 128;
3276   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3277   unsigned NumSectionElts = NumElems / NumSections;
3278
3279   for (unsigned s = 0; s < NumSections; ++s) {
3280     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3281          i != NumSectionElts * (s + 1);
3282          i += 2, ++j) {
3283       int BitI  = Mask[i];
3284       int BitI1 = Mask[i+1];
3285
3286       if (!isUndefOrEqual(BitI, j))
3287         return false;
3288       if (!isUndefOrEqual(BitI1, j))
3289         return false;
3290     }
3291   }
3292
3293   return true;
3294 }
3295
3296 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3297   SmallVector<int, 8> M;
3298   N->getMask(M);
3299   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3300 }
3301
3302 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3303 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3304 /// <2, 2, 3, 3>
3305 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3306   int NumElems = VT.getVectorNumElements();
3307   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3308     return false;
3309
3310   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3311     int BitI  = Mask[i];
3312     int BitI1 = Mask[i+1];
3313     if (!isUndefOrEqual(BitI, j))
3314       return false;
3315     if (!isUndefOrEqual(BitI1, j))
3316       return false;
3317   }
3318   return true;
3319 }
3320
3321 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3322   SmallVector<int, 8> M;
3323   N->getMask(M);
3324   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3325 }
3326
3327 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3328 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3329 /// MOVSD, and MOVD, i.e. setting the lowest element.
3330 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3331   if (VT.getVectorElementType().getSizeInBits() < 32)
3332     return false;
3333
3334   int NumElts = VT.getVectorNumElements();
3335
3336   if (!isUndefOrEqual(Mask[0], NumElts))
3337     return false;
3338
3339   for (int i = 1; i < NumElts; ++i)
3340     if (!isUndefOrEqual(Mask[i], i))
3341       return false;
3342
3343   return true;
3344 }
3345
3346 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3347   SmallVector<int, 8> M;
3348   N->getMask(M);
3349   return ::isMOVLMask(M, N->getValueType(0));
3350 }
3351
3352 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3353 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3354 /// element of vector 2 and the other elements to come from vector 1 in order.
3355 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3356                                bool V2IsSplat = false, bool V2IsUndef = false) {
3357   int NumOps = VT.getVectorNumElements();
3358   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3359     return false;
3360
3361   if (!isUndefOrEqual(Mask[0], 0))
3362     return false;
3363
3364   for (int i = 1; i < NumOps; ++i)
3365     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3366           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3367           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3368       return false;
3369
3370   return true;
3371 }
3372
3373 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3374                            bool V2IsUndef = false) {
3375   SmallVector<int, 8> M;
3376   N->getMask(M);
3377   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3378 }
3379
3380 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3381 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3382 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3383   if (N->getValueType(0).getVectorNumElements() != 4)
3384     return false;
3385
3386   // Expect 1, 1, 3, 3
3387   for (unsigned i = 0; i < 2; ++i) {
3388     int Elt = N->getMaskElt(i);
3389     if (Elt >= 0 && Elt != 1)
3390       return false;
3391   }
3392
3393   bool HasHi = false;
3394   for (unsigned i = 2; i < 4; ++i) {
3395     int Elt = N->getMaskElt(i);
3396     if (Elt >= 0 && Elt != 3)
3397       return false;
3398     if (Elt == 3)
3399       HasHi = true;
3400   }
3401   // Don't use movshdup if it can be done with a shufps.
3402   // FIXME: verify that matching u, u, 3, 3 is what we want.
3403   return HasHi;
3404 }
3405
3406 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3407 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3408 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3409   if (N->getValueType(0).getVectorNumElements() != 4)
3410     return false;
3411
3412   // Expect 0, 0, 2, 2
3413   for (unsigned i = 0; i < 2; ++i)
3414     if (N->getMaskElt(i) > 0)
3415       return false;
3416
3417   bool HasHi = false;
3418   for (unsigned i = 2; i < 4; ++i) {
3419     int Elt = N->getMaskElt(i);
3420     if (Elt >= 0 && Elt != 2)
3421       return false;
3422     if (Elt == 2)
3423       HasHi = true;
3424   }
3425   // Don't use movsldup if it can be done with a shufps.
3426   return HasHi;
3427 }
3428
3429 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3430 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3431 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3432   int e = N->getValueType(0).getVectorNumElements() / 2;
3433
3434   for (int i = 0; i < e; ++i)
3435     if (!isUndefOrEqual(N->getMaskElt(i), i))
3436       return false;
3437   for (int i = 0; i < e; ++i)
3438     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3439       return false;
3440   return true;
3441 }
3442
3443 /// isVEXTRACTF128Index - Return true if the specified
3444 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3445 /// suitable for input to VEXTRACTF128.
3446 bool X86::isVEXTRACTF128Index(SDNode *N) {
3447   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3448     return false;
3449
3450   // The index should be aligned on a 128-bit boundary.
3451   uint64_t Index =
3452     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3453
3454   unsigned VL = N->getValueType(0).getVectorNumElements();
3455   unsigned VBits = N->getValueType(0).getSizeInBits();
3456   unsigned ElSize = VBits / VL;
3457   bool Result = (Index * ElSize) % 128 == 0;
3458
3459   return Result;
3460 }
3461
3462 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3463 /// operand specifies a subvector insert that is suitable for input to
3464 /// VINSERTF128.
3465 bool X86::isVINSERTF128Index(SDNode *N) {
3466   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3467     return false;
3468
3469   // The index should be aligned on a 128-bit boundary.
3470   uint64_t Index =
3471     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3472
3473   unsigned VL = N->getValueType(0).getVectorNumElements();
3474   unsigned VBits = N->getValueType(0).getSizeInBits();
3475   unsigned ElSize = VBits / VL;
3476   bool Result = (Index * ElSize) % 128 == 0;
3477
3478   return Result;
3479 }
3480
3481 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3482 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3483 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3484   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3485   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3486
3487   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3488   unsigned Mask = 0;
3489   for (int i = 0; i < NumOperands; ++i) {
3490     int Val = SVOp->getMaskElt(NumOperands-i-1);
3491     if (Val < 0) Val = 0;
3492     if (Val >= NumOperands) Val -= NumOperands;
3493     Mask |= Val;
3494     if (i != NumOperands - 1)
3495       Mask <<= Shift;
3496   }
3497   return Mask;
3498 }
3499
3500 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3501 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3502 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3503   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3504   unsigned Mask = 0;
3505   // 8 nodes, but we only care about the last 4.
3506   for (unsigned i = 7; i >= 4; --i) {
3507     int Val = SVOp->getMaskElt(i);
3508     if (Val >= 0)
3509       Mask |= (Val - 4);
3510     if (i != 4)
3511       Mask <<= 2;
3512   }
3513   return Mask;
3514 }
3515
3516 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3517 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3518 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3519   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3520   unsigned Mask = 0;
3521   // 8 nodes, but we only care about the first 4.
3522   for (int i = 3; i >= 0; --i) {
3523     int Val = SVOp->getMaskElt(i);
3524     if (Val >= 0)
3525       Mask |= Val;
3526     if (i != 0)
3527       Mask <<= 2;
3528   }
3529   return Mask;
3530 }
3531
3532 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3533 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3534 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3535   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3536   EVT VVT = N->getValueType(0);
3537   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3538   int Val = 0;
3539
3540   unsigned i, e;
3541   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3542     Val = SVOp->getMaskElt(i);
3543     if (Val >= 0)
3544       break;
3545   }
3546   return (Val - i) * EltSize;
3547 }
3548
3549 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3550 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3551 /// instructions.
3552 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3553   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3554     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3555
3556   uint64_t Index =
3557     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3558
3559   EVT VecVT = N->getOperand(0).getValueType();
3560   EVT ElVT = VecVT.getVectorElementType();
3561
3562   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3563
3564   return Index / NumElemsPerChunk;
3565 }
3566
3567 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3568 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3569 /// instructions.
3570 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3571   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3572     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3573
3574   uint64_t Index =
3575     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3576
3577   EVT VecVT = N->getValueType(0);
3578   EVT ElVT = VecVT.getVectorElementType();
3579
3580   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3581
3582   return Index / NumElemsPerChunk;
3583 }
3584
3585 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3586 /// constant +0.0.
3587 bool X86::isZeroNode(SDValue Elt) {
3588   return ((isa<ConstantSDNode>(Elt) &&
3589            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3590           (isa<ConstantFPSDNode>(Elt) &&
3591            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3592 }
3593
3594 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3595 /// their permute mask.
3596 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3597                                     SelectionDAG &DAG) {
3598   EVT VT = SVOp->getValueType(0);
3599   unsigned NumElems = VT.getVectorNumElements();
3600   SmallVector<int, 8> MaskVec;
3601
3602   for (unsigned i = 0; i != NumElems; ++i) {
3603     int idx = SVOp->getMaskElt(i);
3604     if (idx < 0)
3605       MaskVec.push_back(idx);
3606     else if (idx < (int)NumElems)
3607       MaskVec.push_back(idx + NumElems);
3608     else
3609       MaskVec.push_back(idx - NumElems);
3610   }
3611   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3612                               SVOp->getOperand(0), &MaskVec[0]);
3613 }
3614
3615 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3616 /// the two vector operands have swapped position.
3617 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3618   unsigned NumElems = VT.getVectorNumElements();
3619   for (unsigned i = 0; i != NumElems; ++i) {
3620     int idx = Mask[i];
3621     if (idx < 0)
3622       continue;
3623     else if (idx < (int)NumElems)
3624       Mask[i] = idx + NumElems;
3625     else
3626       Mask[i] = idx - NumElems;
3627   }
3628 }
3629
3630 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3631 /// match movhlps. The lower half elements should come from upper half of
3632 /// V1 (and in order), and the upper half elements should come from the upper
3633 /// half of V2 (and in order).
3634 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3635   if (Op->getValueType(0).getVectorNumElements() != 4)
3636     return false;
3637   for (unsigned i = 0, e = 2; i != e; ++i)
3638     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3639       return false;
3640   for (unsigned i = 2; i != 4; ++i)
3641     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3642       return false;
3643   return true;
3644 }
3645
3646 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3647 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3648 /// required.
3649 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3650   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3651     return false;
3652   N = N->getOperand(0).getNode();
3653   if (!ISD::isNON_EXTLoad(N))
3654     return false;
3655   if (LD)
3656     *LD = cast<LoadSDNode>(N);
3657   return true;
3658 }
3659
3660 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3661 /// match movlp{s|d}. The lower half elements should come from lower half of
3662 /// V1 (and in order), and the upper half elements should come from the upper
3663 /// half of V2 (and in order). And since V1 will become the source of the
3664 /// MOVLP, it must be either a vector load or a scalar load to vector.
3665 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3666                                ShuffleVectorSDNode *Op) {
3667   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3668     return false;
3669   // Is V2 is a vector load, don't do this transformation. We will try to use
3670   // load folding shufps op.
3671   if (ISD::isNON_EXTLoad(V2))
3672     return false;
3673
3674   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3675
3676   if (NumElems != 2 && NumElems != 4)
3677     return false;
3678   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3679     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3680       return false;
3681   for (unsigned i = NumElems/2; i != NumElems; ++i)
3682     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3683       return false;
3684   return true;
3685 }
3686
3687 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3688 /// all the same.
3689 static bool isSplatVector(SDNode *N) {
3690   if (N->getOpcode() != ISD::BUILD_VECTOR)
3691     return false;
3692
3693   SDValue SplatValue = N->getOperand(0);
3694   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3695     if (N->getOperand(i) != SplatValue)
3696       return false;
3697   return true;
3698 }
3699
3700 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3701 /// to an zero vector.
3702 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3703 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3704   SDValue V1 = N->getOperand(0);
3705   SDValue V2 = N->getOperand(1);
3706   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3707   for (unsigned i = 0; i != NumElems; ++i) {
3708     int Idx = N->getMaskElt(i);
3709     if (Idx >= (int)NumElems) {
3710       unsigned Opc = V2.getOpcode();
3711       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3712         continue;
3713       if (Opc != ISD::BUILD_VECTOR ||
3714           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3715         return false;
3716     } else if (Idx >= 0) {
3717       unsigned Opc = V1.getOpcode();
3718       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3719         continue;
3720       if (Opc != ISD::BUILD_VECTOR ||
3721           !X86::isZeroNode(V1.getOperand(Idx)))
3722         return false;
3723     }
3724   }
3725   return true;
3726 }
3727
3728 /// getZeroVector - Returns a vector of specified type with all zero elements.
3729 ///
3730 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3731                              DebugLoc dl) {
3732   assert(VT.isVector() && "Expected a vector type");
3733
3734   // Always build SSE zero vectors as <4 x i32> bitcasted
3735   // to their dest type. This ensures they get CSE'd.
3736   SDValue Vec;
3737   if (VT.getSizeInBits() == 128) {  // SSE
3738     if (HasSSE2) {  // SSE2
3739       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3740       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3741     } else { // SSE1
3742       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3743       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3744     }
3745   } else if (VT.getSizeInBits() == 256) { // AVX
3746     // 256-bit logic and arithmetic instructions in AVX are
3747     // all floating-point, no support for integer ops. Default
3748     // to emitting fp zeroed vectors then.
3749     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3750     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3751     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3752   }
3753   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3754 }
3755
3756 /// getOnesVector - Returns a vector of specified type with all bits set.
3757 ///
3758 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3759   assert(VT.isVector() && "Expected a vector type");
3760
3761   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3762   // type.  This ensures they get CSE'd.
3763   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3764   SDValue Vec;
3765   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3766   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3767 }
3768
3769
3770 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3771 /// that point to V2 points to its first element.
3772 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3773   EVT VT = SVOp->getValueType(0);
3774   unsigned NumElems = VT.getVectorNumElements();
3775
3776   bool Changed = false;
3777   SmallVector<int, 8> MaskVec;
3778   SVOp->getMask(MaskVec);
3779
3780   for (unsigned i = 0; i != NumElems; ++i) {
3781     if (MaskVec[i] > (int)NumElems) {
3782       MaskVec[i] = NumElems;
3783       Changed = true;
3784     }
3785   }
3786   if (Changed)
3787     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3788                                 SVOp->getOperand(1), &MaskVec[0]);
3789   return SDValue(SVOp, 0);
3790 }
3791
3792 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3793 /// operation of specified width.
3794 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3795                        SDValue V2) {
3796   unsigned NumElems = VT.getVectorNumElements();
3797   SmallVector<int, 8> Mask;
3798   Mask.push_back(NumElems);
3799   for (unsigned i = 1; i != NumElems; ++i)
3800     Mask.push_back(i);
3801   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3802 }
3803
3804 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3805 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3806                           SDValue V2) {
3807   unsigned NumElems = VT.getVectorNumElements();
3808   SmallVector<int, 8> Mask;
3809   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3810     Mask.push_back(i);
3811     Mask.push_back(i + NumElems);
3812   }
3813   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3814 }
3815
3816 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3817 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3818                           SDValue V2) {
3819   unsigned NumElems = VT.getVectorNumElements();
3820   unsigned Half = NumElems/2;
3821   SmallVector<int, 8> Mask;
3822   for (unsigned i = 0; i != Half; ++i) {
3823     Mask.push_back(i + Half);
3824     Mask.push_back(i + NumElems + Half);
3825   }
3826   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3827 }
3828
3829 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3830 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3831   EVT PVT = MVT::v4f32;
3832   EVT VT = SV->getValueType(0);
3833   DebugLoc dl = SV->getDebugLoc();
3834   SDValue V1 = SV->getOperand(0);
3835   int NumElems = VT.getVectorNumElements();
3836   int EltNo = SV->getSplatIndex();
3837
3838   // unpack elements to the correct location
3839   while (NumElems > 4) {
3840     if (EltNo < NumElems/2) {
3841       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3842     } else {
3843       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3844       EltNo -= NumElems/2;
3845     }
3846     NumElems >>= 1;
3847   }
3848
3849   // Perform the splat.
3850   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3851   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3852   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3853   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3854 }
3855
3856 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3857 /// vector of zero or undef vector.  This produces a shuffle where the low
3858 /// element of V2 is swizzled into the zero/undef vector, landing at element
3859 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3860 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3861                                              bool isZero, bool HasSSE2,
3862                                              SelectionDAG &DAG) {
3863   EVT VT = V2.getValueType();
3864   SDValue V1 = isZero
3865     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3866   unsigned NumElems = VT.getVectorNumElements();
3867   SmallVector<int, 16> MaskVec;
3868   for (unsigned i = 0; i != NumElems; ++i)
3869     // If this is the insertion idx, put the low elt of V2 here.
3870     MaskVec.push_back(i == Idx ? NumElems : i);
3871   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3872 }
3873
3874 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3875 /// element of the result of the vector shuffle.
3876 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3877                             unsigned Depth) {
3878   if (Depth == 6)
3879     return SDValue();  // Limit search depth.
3880
3881   SDValue V = SDValue(N, 0);
3882   EVT VT = V.getValueType();
3883   unsigned Opcode = V.getOpcode();
3884
3885   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3886   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3887     Index = SV->getMaskElt(Index);
3888
3889     if (Index < 0)
3890       return DAG.getUNDEF(VT.getVectorElementType());
3891
3892     int NumElems = VT.getVectorNumElements();
3893     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3894     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3895   }
3896
3897   // Recurse into target specific vector shuffles to find scalars.
3898   if (isTargetShuffle(Opcode)) {
3899     int NumElems = VT.getVectorNumElements();
3900     SmallVector<unsigned, 16> ShuffleMask;
3901     SDValue ImmN;
3902
3903     switch(Opcode) {
3904     case X86ISD::SHUFPS:
3905     case X86ISD::SHUFPD:
3906       ImmN = N->getOperand(N->getNumOperands()-1);
3907       DecodeSHUFPSMask(NumElems,
3908                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3909                        ShuffleMask);
3910       break;
3911     case X86ISD::PUNPCKHBW:
3912     case X86ISD::PUNPCKHWD:
3913     case X86ISD::PUNPCKHDQ:
3914     case X86ISD::PUNPCKHQDQ:
3915       DecodePUNPCKHMask(NumElems, ShuffleMask);
3916       break;
3917     case X86ISD::UNPCKHPS:
3918     case X86ISD::UNPCKHPD:
3919       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3920       break;
3921     case X86ISD::PUNPCKLBW:
3922     case X86ISD::PUNPCKLWD:
3923     case X86ISD::PUNPCKLDQ:
3924     case X86ISD::PUNPCKLQDQ:
3925       DecodePUNPCKLMask(VT, ShuffleMask);
3926       break;
3927     case X86ISD::UNPCKLPS:
3928     case X86ISD::UNPCKLPD:
3929     case X86ISD::VUNPCKLPS:
3930     case X86ISD::VUNPCKLPD:
3931     case X86ISD::VUNPCKLPSY:
3932     case X86ISD::VUNPCKLPDY:
3933       DecodeUNPCKLPMask(VT, ShuffleMask);
3934       break;
3935     case X86ISD::MOVHLPS:
3936       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3937       break;
3938     case X86ISD::MOVLHPS:
3939       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3940       break;
3941     case X86ISD::PSHUFD:
3942       ImmN = N->getOperand(N->getNumOperands()-1);
3943       DecodePSHUFMask(NumElems,
3944                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3945                       ShuffleMask);
3946       break;
3947     case X86ISD::PSHUFHW:
3948       ImmN = N->getOperand(N->getNumOperands()-1);
3949       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3950                         ShuffleMask);
3951       break;
3952     case X86ISD::PSHUFLW:
3953       ImmN = N->getOperand(N->getNumOperands()-1);
3954       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3955                         ShuffleMask);
3956       break;
3957     case X86ISD::MOVSS:
3958     case X86ISD::MOVSD: {
3959       // The index 0 always comes from the first element of the second source,
3960       // this is why MOVSS and MOVSD are used in the first place. The other
3961       // elements come from the other positions of the first source vector.
3962       unsigned OpNum = (Index == 0) ? 1 : 0;
3963       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3964                                  Depth+1);
3965     }
3966     default:
3967       assert("not implemented for target shuffle node");
3968       return SDValue();
3969     }
3970
3971     Index = ShuffleMask[Index];
3972     if (Index < 0)
3973       return DAG.getUNDEF(VT.getVectorElementType());
3974
3975     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3976     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3977                                Depth+1);
3978   }
3979
3980   // Actual nodes that may contain scalar elements
3981   if (Opcode == ISD::BITCAST) {
3982     V = V.getOperand(0);
3983     EVT SrcVT = V.getValueType();
3984     unsigned NumElems = VT.getVectorNumElements();
3985
3986     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3987       return SDValue();
3988   }
3989
3990   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3991     return (Index == 0) ? V.getOperand(0)
3992                           : DAG.getUNDEF(VT.getVectorElementType());
3993
3994   if (V.getOpcode() == ISD::BUILD_VECTOR)
3995     return V.getOperand(Index);
3996
3997   return SDValue();
3998 }
3999
4000 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4001 /// shuffle operation which come from a consecutively from a zero. The
4002 /// search can start in two diferent directions, from left or right.
4003 static
4004 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4005                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4006   int i = 0;
4007
4008   while (i < NumElems) {
4009     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4010     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4011     if (!(Elt.getNode() &&
4012          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4013       break;
4014     ++i;
4015   }
4016
4017   return i;
4018 }
4019
4020 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4021 /// MaskE correspond consecutively to elements from one of the vector operands,
4022 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4023 static
4024 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4025                               int OpIdx, int NumElems, unsigned &OpNum) {
4026   bool SeenV1 = false;
4027   bool SeenV2 = false;
4028
4029   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4030     int Idx = SVOp->getMaskElt(i);
4031     // Ignore undef indicies
4032     if (Idx < 0)
4033       continue;
4034
4035     if (Idx < NumElems)
4036       SeenV1 = true;
4037     else
4038       SeenV2 = true;
4039
4040     // Only accept consecutive elements from the same vector
4041     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4042       return false;
4043   }
4044
4045   OpNum = SeenV1 ? 0 : 1;
4046   return true;
4047 }
4048
4049 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4050 /// logical left shift of a vector.
4051 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4052                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4053   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4054   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4055               false /* check zeros from right */, DAG);
4056   unsigned OpSrc;
4057
4058   if (!NumZeros)
4059     return false;
4060
4061   // Considering the elements in the mask that are not consecutive zeros,
4062   // check if they consecutively come from only one of the source vectors.
4063   //
4064   //               V1 = {X, A, B, C}     0
4065   //                         \  \  \    /
4066   //   vector_shuffle V1, V2 <1, 2, 3, X>
4067   //
4068   if (!isShuffleMaskConsecutive(SVOp,
4069             0,                   // Mask Start Index
4070             NumElems-NumZeros-1, // Mask End Index
4071             NumZeros,            // Where to start looking in the src vector
4072             NumElems,            // Number of elements in vector
4073             OpSrc))              // Which source operand ?
4074     return false;
4075
4076   isLeft = false;
4077   ShAmt = NumZeros;
4078   ShVal = SVOp->getOperand(OpSrc);
4079   return true;
4080 }
4081
4082 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4083 /// logical left shift of a vector.
4084 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4085                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4086   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4087   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4088               true /* check zeros from left */, DAG);
4089   unsigned OpSrc;
4090
4091   if (!NumZeros)
4092     return false;
4093
4094   // Considering the elements in the mask that are not consecutive zeros,
4095   // check if they consecutively come from only one of the source vectors.
4096   //
4097   //                           0    { A, B, X, X } = V2
4098   //                          / \    /  /
4099   //   vector_shuffle V1, V2 <X, X, 4, 5>
4100   //
4101   if (!isShuffleMaskConsecutive(SVOp,
4102             NumZeros,     // Mask Start Index
4103             NumElems-1,   // Mask End Index
4104             0,            // Where to start looking in the src vector
4105             NumElems,     // Number of elements in vector
4106             OpSrc))       // Which source operand ?
4107     return false;
4108
4109   isLeft = true;
4110   ShAmt = NumZeros;
4111   ShVal = SVOp->getOperand(OpSrc);
4112   return true;
4113 }
4114
4115 /// isVectorShift - Returns true if the shuffle can be implemented as a
4116 /// logical left or right shift of a vector.
4117 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4118                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4119   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4120       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4121     return true;
4122
4123   return false;
4124 }
4125
4126 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4127 ///
4128 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4129                                        unsigned NumNonZero, unsigned NumZero,
4130                                        SelectionDAG &DAG,
4131                                        const TargetLowering &TLI) {
4132   if (NumNonZero > 8)
4133     return SDValue();
4134
4135   DebugLoc dl = Op.getDebugLoc();
4136   SDValue V(0, 0);
4137   bool First = true;
4138   for (unsigned i = 0; i < 16; ++i) {
4139     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4140     if (ThisIsNonZero && First) {
4141       if (NumZero)
4142         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4143       else
4144         V = DAG.getUNDEF(MVT::v8i16);
4145       First = false;
4146     }
4147
4148     if ((i & 1) != 0) {
4149       SDValue ThisElt(0, 0), LastElt(0, 0);
4150       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4151       if (LastIsNonZero) {
4152         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4153                               MVT::i16, Op.getOperand(i-1));
4154       }
4155       if (ThisIsNonZero) {
4156         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4157         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4158                               ThisElt, DAG.getConstant(8, MVT::i8));
4159         if (LastIsNonZero)
4160           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4161       } else
4162         ThisElt = LastElt;
4163
4164       if (ThisElt.getNode())
4165         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4166                         DAG.getIntPtrConstant(i/2));
4167     }
4168   }
4169
4170   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4171 }
4172
4173 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4174 ///
4175 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4176                                      unsigned NumNonZero, unsigned NumZero,
4177                                      SelectionDAG &DAG,
4178                                      const TargetLowering &TLI) {
4179   if (NumNonZero > 4)
4180     return SDValue();
4181
4182   DebugLoc dl = Op.getDebugLoc();
4183   SDValue V(0, 0);
4184   bool First = true;
4185   for (unsigned i = 0; i < 8; ++i) {
4186     bool isNonZero = (NonZeros & (1 << i)) != 0;
4187     if (isNonZero) {
4188       if (First) {
4189         if (NumZero)
4190           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4191         else
4192           V = DAG.getUNDEF(MVT::v8i16);
4193         First = false;
4194       }
4195       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4196                       MVT::v8i16, V, Op.getOperand(i),
4197                       DAG.getIntPtrConstant(i));
4198     }
4199   }
4200
4201   return V;
4202 }
4203
4204 /// getVShift - Return a vector logical shift node.
4205 ///
4206 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4207                          unsigned NumBits, SelectionDAG &DAG,
4208                          const TargetLowering &TLI, DebugLoc dl) {
4209   EVT ShVT = MVT::v2i64;
4210   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4211   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4212   return DAG.getNode(ISD::BITCAST, dl, VT,
4213                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4214                              DAG.getConstant(NumBits,
4215                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4216 }
4217
4218 SDValue
4219 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4220                                           SelectionDAG &DAG) const {
4221
4222   // Check if the scalar load can be widened into a vector load. And if
4223   // the address is "base + cst" see if the cst can be "absorbed" into
4224   // the shuffle mask.
4225   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4226     SDValue Ptr = LD->getBasePtr();
4227     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4228       return SDValue();
4229     EVT PVT = LD->getValueType(0);
4230     if (PVT != MVT::i32 && PVT != MVT::f32)
4231       return SDValue();
4232
4233     int FI = -1;
4234     int64_t Offset = 0;
4235     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4236       FI = FINode->getIndex();
4237       Offset = 0;
4238     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4239                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4240       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4241       Offset = Ptr.getConstantOperandVal(1);
4242       Ptr = Ptr.getOperand(0);
4243     } else {
4244       return SDValue();
4245     }
4246
4247     SDValue Chain = LD->getChain();
4248     // Make sure the stack object alignment is at least 16.
4249     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4250     if (DAG.InferPtrAlignment(Ptr) < 16) {
4251       if (MFI->isFixedObjectIndex(FI)) {
4252         // Can't change the alignment. FIXME: It's possible to compute
4253         // the exact stack offset and reference FI + adjust offset instead.
4254         // If someone *really* cares about this. That's the way to implement it.
4255         return SDValue();
4256       } else {
4257         MFI->setObjectAlignment(FI, 16);
4258       }
4259     }
4260
4261     // (Offset % 16) must be multiple of 4. Then address is then
4262     // Ptr + (Offset & ~15).
4263     if (Offset < 0)
4264       return SDValue();
4265     if ((Offset % 16) & 3)
4266       return SDValue();
4267     int64_t StartOffset = Offset & ~15;
4268     if (StartOffset)
4269       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4270                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4271
4272     int EltNo = (Offset - StartOffset) >> 2;
4273     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4274     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4275     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4276                              LD->getPointerInfo().getWithOffset(StartOffset),
4277                              false, false, 0);
4278     // Canonicalize it to a v4i32 shuffle.
4279     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4280     return DAG.getNode(ISD::BITCAST, dl, VT,
4281                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4282                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4283   }
4284
4285   return SDValue();
4286 }
4287
4288 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4289 /// vector of type 'VT', see if the elements can be replaced by a single large
4290 /// load which has the same value as a build_vector whose operands are 'elts'.
4291 ///
4292 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4293 ///
4294 /// FIXME: we'd also like to handle the case where the last elements are zero
4295 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4296 /// There's even a handy isZeroNode for that purpose.
4297 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4298                                         DebugLoc &DL, SelectionDAG &DAG) {
4299   EVT EltVT = VT.getVectorElementType();
4300   unsigned NumElems = Elts.size();
4301
4302   LoadSDNode *LDBase = NULL;
4303   unsigned LastLoadedElt = -1U;
4304
4305   // For each element in the initializer, see if we've found a load or an undef.
4306   // If we don't find an initial load element, or later load elements are
4307   // non-consecutive, bail out.
4308   for (unsigned i = 0; i < NumElems; ++i) {
4309     SDValue Elt = Elts[i];
4310
4311     if (!Elt.getNode() ||
4312         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4313       return SDValue();
4314     if (!LDBase) {
4315       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4316         return SDValue();
4317       LDBase = cast<LoadSDNode>(Elt.getNode());
4318       LastLoadedElt = i;
4319       continue;
4320     }
4321     if (Elt.getOpcode() == ISD::UNDEF)
4322       continue;
4323
4324     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4325     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4326       return SDValue();
4327     LastLoadedElt = i;
4328   }
4329
4330   // If we have found an entire vector of loads and undefs, then return a large
4331   // load of the entire vector width starting at the base pointer.  If we found
4332   // consecutive loads for the low half, generate a vzext_load node.
4333   if (LastLoadedElt == NumElems - 1) {
4334     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4335       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4336                          LDBase->getPointerInfo(),
4337                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4338     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4339                        LDBase->getPointerInfo(),
4340                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4341                        LDBase->getAlignment());
4342   } else if (NumElems == 4 && LastLoadedElt == 1) {
4343     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4344     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4345     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4346                                               Ops, 2, MVT::i32,
4347                                               LDBase->getMemOperand());
4348     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4349   }
4350   return SDValue();
4351 }
4352
4353 SDValue
4354 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4355   DebugLoc dl = Op.getDebugLoc();
4356
4357   EVT VT = Op.getValueType();
4358   EVT ExtVT = VT.getVectorElementType();
4359
4360   unsigned NumElems = Op.getNumOperands();
4361
4362   // For AVX-length vectors, build the individual 128-bit pieces and
4363   // use shuffles to put them in place.
4364   if (VT.getSizeInBits() > 256 &&
4365       Subtarget->hasAVX() &&
4366       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4367     SmallVector<SDValue, 8> V;
4368     V.resize(NumElems);
4369     for (unsigned i = 0; i < NumElems; ++i) {
4370       V[i] = Op.getOperand(i);
4371     }
4372
4373     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4374
4375     // Build the lower subvector.
4376     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4377     // Build the upper subvector.
4378     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4379                                 NumElems/2);
4380
4381     return ConcatVectors(Lower, Upper, DAG);
4382   }
4383
4384   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4385   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4386   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4387   // is present, so AllOnes is ignored.
4388   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4389       (Op.getValueType().getSizeInBits() != 256 &&
4390        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4391     // Canonicalize this to <4 x i32> (SSE) to
4392     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4393     // eliminated on x86-32 hosts.
4394     if (Op.getValueType() == MVT::v4i32)
4395       return Op;
4396
4397     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4398       return getOnesVector(Op.getValueType(), DAG, dl);
4399     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4400   }
4401
4402   unsigned EVTBits = ExtVT.getSizeInBits();
4403
4404   unsigned NumZero  = 0;
4405   unsigned NumNonZero = 0;
4406   unsigned NonZeros = 0;
4407   bool IsAllConstants = true;
4408   SmallSet<SDValue, 8> Values;
4409   for (unsigned i = 0; i < NumElems; ++i) {
4410     SDValue Elt = Op.getOperand(i);
4411     if (Elt.getOpcode() == ISD::UNDEF)
4412       continue;
4413     Values.insert(Elt);
4414     if (Elt.getOpcode() != ISD::Constant &&
4415         Elt.getOpcode() != ISD::ConstantFP)
4416       IsAllConstants = false;
4417     if (X86::isZeroNode(Elt))
4418       NumZero++;
4419     else {
4420       NonZeros |= (1 << i);
4421       NumNonZero++;
4422     }
4423   }
4424
4425   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4426   if (NumNonZero == 0)
4427     return DAG.getUNDEF(VT);
4428
4429   // Special case for single non-zero, non-undef, element.
4430   if (NumNonZero == 1) {
4431     unsigned Idx = CountTrailingZeros_32(NonZeros);
4432     SDValue Item = Op.getOperand(Idx);
4433
4434     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4435     // the value are obviously zero, truncate the value to i32 and do the
4436     // insertion that way.  Only do this if the value is non-constant or if the
4437     // value is a constant being inserted into element 0.  It is cheaper to do
4438     // a constant pool load than it is to do a movd + shuffle.
4439     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4440         (!IsAllConstants || Idx == 0)) {
4441       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4442         // Handle SSE only.
4443         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4444         EVT VecVT = MVT::v4i32;
4445         unsigned VecElts = 4;
4446
4447         // Truncate the value (which may itself be a constant) to i32, and
4448         // convert it to a vector with movd (S2V+shuffle to zero extend).
4449         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4450         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4451         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4452                                            Subtarget->hasSSE2(), DAG);
4453
4454         // Now we have our 32-bit value zero extended in the low element of
4455         // a vector.  If Idx != 0, swizzle it into place.
4456         if (Idx != 0) {
4457           SmallVector<int, 4> Mask;
4458           Mask.push_back(Idx);
4459           for (unsigned i = 1; i != VecElts; ++i)
4460             Mask.push_back(i);
4461           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4462                                       DAG.getUNDEF(Item.getValueType()),
4463                                       &Mask[0]);
4464         }
4465         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4466       }
4467     }
4468
4469     // If we have a constant or non-constant insertion into the low element of
4470     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4471     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4472     // depending on what the source datatype is.
4473     if (Idx == 0) {
4474       if (NumZero == 0) {
4475         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4476       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4477           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4478         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4479         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4480         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4481                                            DAG);
4482       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4483         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4484         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4485         EVT MiddleVT = MVT::v4i32;
4486         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4487         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4488                                            Subtarget->hasSSE2(), DAG);
4489         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4490       }
4491     }
4492
4493     // Is it a vector logical left shift?
4494     if (NumElems == 2 && Idx == 1 &&
4495         X86::isZeroNode(Op.getOperand(0)) &&
4496         !X86::isZeroNode(Op.getOperand(1))) {
4497       unsigned NumBits = VT.getSizeInBits();
4498       return getVShift(true, VT,
4499                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4500                                    VT, Op.getOperand(1)),
4501                        NumBits/2, DAG, *this, dl);
4502     }
4503
4504     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4505       return SDValue();
4506
4507     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4508     // is a non-constant being inserted into an element other than the low one,
4509     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4510     // movd/movss) to move this into the low element, then shuffle it into
4511     // place.
4512     if (EVTBits == 32) {
4513       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4514
4515       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4516       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4517                                          Subtarget->hasSSE2(), DAG);
4518       SmallVector<int, 8> MaskVec;
4519       for (unsigned i = 0; i < NumElems; i++)
4520         MaskVec.push_back(i == Idx ? 0 : 1);
4521       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4522     }
4523   }
4524
4525   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4526   if (Values.size() == 1) {
4527     if (EVTBits == 32) {
4528       // Instead of a shuffle like this:
4529       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4530       // Check if it's possible to issue this instead.
4531       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4532       unsigned Idx = CountTrailingZeros_32(NonZeros);
4533       SDValue Item = Op.getOperand(Idx);
4534       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4535         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4536     }
4537     return SDValue();
4538   }
4539
4540   // A vector full of immediates; various special cases are already
4541   // handled, so this is best done with a single constant-pool load.
4542   if (IsAllConstants)
4543     return SDValue();
4544
4545   // Let legalizer expand 2-wide build_vectors.
4546   if (EVTBits == 64) {
4547     if (NumNonZero == 1) {
4548       // One half is zero or undef.
4549       unsigned Idx = CountTrailingZeros_32(NonZeros);
4550       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4551                                  Op.getOperand(Idx));
4552       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4553                                          Subtarget->hasSSE2(), DAG);
4554     }
4555     return SDValue();
4556   }
4557
4558   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4559   if (EVTBits == 8 && NumElems == 16) {
4560     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4561                                         *this);
4562     if (V.getNode()) return V;
4563   }
4564
4565   if (EVTBits == 16 && NumElems == 8) {
4566     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4567                                       *this);
4568     if (V.getNode()) return V;
4569   }
4570
4571   // If element VT is == 32 bits, turn it into a number of shuffles.
4572   SmallVector<SDValue, 8> V;
4573   V.resize(NumElems);
4574   if (NumElems == 4 && NumZero > 0) {
4575     for (unsigned i = 0; i < 4; ++i) {
4576       bool isZero = !(NonZeros & (1 << i));
4577       if (isZero)
4578         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4579       else
4580         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4581     }
4582
4583     for (unsigned i = 0; i < 2; ++i) {
4584       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4585         default: break;
4586         case 0:
4587           V[i] = V[i*2];  // Must be a zero vector.
4588           break;
4589         case 1:
4590           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4591           break;
4592         case 2:
4593           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4594           break;
4595         case 3:
4596           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4597           break;
4598       }
4599     }
4600
4601     SmallVector<int, 8> MaskVec;
4602     bool Reverse = (NonZeros & 0x3) == 2;
4603     for (unsigned i = 0; i < 2; ++i)
4604       MaskVec.push_back(Reverse ? 1-i : i);
4605     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4606     for (unsigned i = 0; i < 2; ++i)
4607       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4608     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4609   }
4610
4611   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4612     // Check for a build vector of consecutive loads.
4613     for (unsigned i = 0; i < NumElems; ++i)
4614       V[i] = Op.getOperand(i);
4615
4616     // Check for elements which are consecutive loads.
4617     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4618     if (LD.getNode())
4619       return LD;
4620
4621     // For SSE 4.1, use insertps to put the high elements into the low element.
4622     if (getSubtarget()->hasSSE41()) {
4623       SDValue Result;
4624       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4625         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4626       else
4627         Result = DAG.getUNDEF(VT);
4628
4629       for (unsigned i = 1; i < NumElems; ++i) {
4630         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4631         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4632                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4633       }
4634       return Result;
4635     }
4636
4637     // Otherwise, expand into a number of unpckl*, start by extending each of
4638     // our (non-undef) elements to the full vector width with the element in the
4639     // bottom slot of the vector (which generates no code for SSE).
4640     for (unsigned i = 0; i < NumElems; ++i) {
4641       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4642         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4643       else
4644         V[i] = DAG.getUNDEF(VT);
4645     }
4646
4647     // Next, we iteratively mix elements, e.g. for v4f32:
4648     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4649     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4650     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4651     unsigned EltStride = NumElems >> 1;
4652     while (EltStride != 0) {
4653       for (unsigned i = 0; i < EltStride; ++i) {
4654         // If V[i+EltStride] is undef and this is the first round of mixing,
4655         // then it is safe to just drop this shuffle: V[i] is already in the
4656         // right place, the one element (since it's the first round) being
4657         // inserted as undef can be dropped.  This isn't safe for successive
4658         // rounds because they will permute elements within both vectors.
4659         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4660             EltStride == NumElems/2)
4661           continue;
4662
4663         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4664       }
4665       EltStride >>= 1;
4666     }
4667     return V[0];
4668   }
4669   return SDValue();
4670 }
4671
4672 SDValue
4673 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4674   // We support concatenate two MMX registers and place them in a MMX
4675   // register.  This is better than doing a stack convert.
4676   DebugLoc dl = Op.getDebugLoc();
4677   EVT ResVT = Op.getValueType();
4678   assert(Op.getNumOperands() == 2);
4679   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4680          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4681   int Mask[2];
4682   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4683   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4684   InVec = Op.getOperand(1);
4685   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4686     unsigned NumElts = ResVT.getVectorNumElements();
4687     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4688     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4689                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4690   } else {
4691     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4692     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4693     Mask[0] = 0; Mask[1] = 2;
4694     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4695   }
4696   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4697 }
4698
4699 // v8i16 shuffles - Prefer shuffles in the following order:
4700 // 1. [all]   pshuflw, pshufhw, optional move
4701 // 2. [ssse3] 1 x pshufb
4702 // 3. [ssse3] 2 x pshufb + 1 x por
4703 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4704 SDValue
4705 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4706                                             SelectionDAG &DAG) const {
4707   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4708   SDValue V1 = SVOp->getOperand(0);
4709   SDValue V2 = SVOp->getOperand(1);
4710   DebugLoc dl = SVOp->getDebugLoc();
4711   SmallVector<int, 8> MaskVals;
4712
4713   // Determine if more than 1 of the words in each of the low and high quadwords
4714   // of the result come from the same quadword of one of the two inputs.  Undef
4715   // mask values count as coming from any quadword, for better codegen.
4716   SmallVector<unsigned, 4> LoQuad(4);
4717   SmallVector<unsigned, 4> HiQuad(4);
4718   BitVector InputQuads(4);
4719   for (unsigned i = 0; i < 8; ++i) {
4720     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4721     int EltIdx = SVOp->getMaskElt(i);
4722     MaskVals.push_back(EltIdx);
4723     if (EltIdx < 0) {
4724       ++Quad[0];
4725       ++Quad[1];
4726       ++Quad[2];
4727       ++Quad[3];
4728       continue;
4729     }
4730     ++Quad[EltIdx / 4];
4731     InputQuads.set(EltIdx / 4);
4732   }
4733
4734   int BestLoQuad = -1;
4735   unsigned MaxQuad = 1;
4736   for (unsigned i = 0; i < 4; ++i) {
4737     if (LoQuad[i] > MaxQuad) {
4738       BestLoQuad = i;
4739       MaxQuad = LoQuad[i];
4740     }
4741   }
4742
4743   int BestHiQuad = -1;
4744   MaxQuad = 1;
4745   for (unsigned i = 0; i < 4; ++i) {
4746     if (HiQuad[i] > MaxQuad) {
4747       BestHiQuad = i;
4748       MaxQuad = HiQuad[i];
4749     }
4750   }
4751
4752   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4753   // of the two input vectors, shuffle them into one input vector so only a
4754   // single pshufb instruction is necessary. If There are more than 2 input
4755   // quads, disable the next transformation since it does not help SSSE3.
4756   bool V1Used = InputQuads[0] || InputQuads[1];
4757   bool V2Used = InputQuads[2] || InputQuads[3];
4758   if (Subtarget->hasSSSE3()) {
4759     if (InputQuads.count() == 2 && V1Used && V2Used) {
4760       BestLoQuad = InputQuads.find_first();
4761       BestHiQuad = InputQuads.find_next(BestLoQuad);
4762     }
4763     if (InputQuads.count() > 2) {
4764       BestLoQuad = -1;
4765       BestHiQuad = -1;
4766     }
4767   }
4768
4769   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4770   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4771   // words from all 4 input quadwords.
4772   SDValue NewV;
4773   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4774     SmallVector<int, 8> MaskV;
4775     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4776     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4777     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4778                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4779                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4780     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4781
4782     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4783     // source words for the shuffle, to aid later transformations.
4784     bool AllWordsInNewV = true;
4785     bool InOrder[2] = { true, true };
4786     for (unsigned i = 0; i != 8; ++i) {
4787       int idx = MaskVals[i];
4788       if (idx != (int)i)
4789         InOrder[i/4] = false;
4790       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4791         continue;
4792       AllWordsInNewV = false;
4793       break;
4794     }
4795
4796     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4797     if (AllWordsInNewV) {
4798       for (int i = 0; i != 8; ++i) {
4799         int idx = MaskVals[i];
4800         if (idx < 0)
4801           continue;
4802         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4803         if ((idx != i) && idx < 4)
4804           pshufhw = false;
4805         if ((idx != i) && idx > 3)
4806           pshuflw = false;
4807       }
4808       V1 = NewV;
4809       V2Used = false;
4810       BestLoQuad = 0;
4811       BestHiQuad = 1;
4812     }
4813
4814     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4815     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4816     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4817       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4818       unsigned TargetMask = 0;
4819       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4820                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4821       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4822                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4823       V1 = NewV.getOperand(0);
4824       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4825     }
4826   }
4827
4828   // If we have SSSE3, and all words of the result are from 1 input vector,
4829   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4830   // is present, fall back to case 4.
4831   if (Subtarget->hasSSSE3()) {
4832     SmallVector<SDValue,16> pshufbMask;
4833
4834     // If we have elements from both input vectors, set the high bit of the
4835     // shuffle mask element to zero out elements that come from V2 in the V1
4836     // mask, and elements that come from V1 in the V2 mask, so that the two
4837     // results can be OR'd together.
4838     bool TwoInputs = V1Used && V2Used;
4839     for (unsigned i = 0; i != 8; ++i) {
4840       int EltIdx = MaskVals[i] * 2;
4841       if (TwoInputs && (EltIdx >= 16)) {
4842         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4843         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4844         continue;
4845       }
4846       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4847       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4848     }
4849     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4850     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4851                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4852                                  MVT::v16i8, &pshufbMask[0], 16));
4853     if (!TwoInputs)
4854       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4855
4856     // Calculate the shuffle mask for the second input, shuffle it, and
4857     // OR it with the first shuffled input.
4858     pshufbMask.clear();
4859     for (unsigned i = 0; i != 8; ++i) {
4860       int EltIdx = MaskVals[i] * 2;
4861       if (EltIdx < 16) {
4862         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4863         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4864         continue;
4865       }
4866       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4867       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4868     }
4869     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4870     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4871                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4872                                  MVT::v16i8, &pshufbMask[0], 16));
4873     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4874     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4875   }
4876
4877   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4878   // and update MaskVals with new element order.
4879   BitVector InOrder(8);
4880   if (BestLoQuad >= 0) {
4881     SmallVector<int, 8> MaskV;
4882     for (int i = 0; i != 4; ++i) {
4883       int idx = MaskVals[i];
4884       if (idx < 0) {
4885         MaskV.push_back(-1);
4886         InOrder.set(i);
4887       } else if ((idx / 4) == BestLoQuad) {
4888         MaskV.push_back(idx & 3);
4889         InOrder.set(i);
4890       } else {
4891         MaskV.push_back(-1);
4892       }
4893     }
4894     for (unsigned i = 4; i != 8; ++i)
4895       MaskV.push_back(i);
4896     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4897                                 &MaskV[0]);
4898
4899     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4900       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4901                                NewV.getOperand(0),
4902                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4903                                DAG);
4904   }
4905
4906   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4907   // and update MaskVals with the new element order.
4908   if (BestHiQuad >= 0) {
4909     SmallVector<int, 8> MaskV;
4910     for (unsigned i = 0; i != 4; ++i)
4911       MaskV.push_back(i);
4912     for (unsigned i = 4; i != 8; ++i) {
4913       int idx = MaskVals[i];
4914       if (idx < 0) {
4915         MaskV.push_back(-1);
4916         InOrder.set(i);
4917       } else if ((idx / 4) == BestHiQuad) {
4918         MaskV.push_back((idx & 3) + 4);
4919         InOrder.set(i);
4920       } else {
4921         MaskV.push_back(-1);
4922       }
4923     }
4924     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4925                                 &MaskV[0]);
4926
4927     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4928       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4929                               NewV.getOperand(0),
4930                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4931                               DAG);
4932   }
4933
4934   // In case BestHi & BestLo were both -1, which means each quadword has a word
4935   // from each of the four input quadwords, calculate the InOrder bitvector now
4936   // before falling through to the insert/extract cleanup.
4937   if (BestLoQuad == -1 && BestHiQuad == -1) {
4938     NewV = V1;
4939     for (int i = 0; i != 8; ++i)
4940       if (MaskVals[i] < 0 || MaskVals[i] == i)
4941         InOrder.set(i);
4942   }
4943
4944   // The other elements are put in the right place using pextrw and pinsrw.
4945   for (unsigned i = 0; i != 8; ++i) {
4946     if (InOrder[i])
4947       continue;
4948     int EltIdx = MaskVals[i];
4949     if (EltIdx < 0)
4950       continue;
4951     SDValue ExtOp = (EltIdx < 8)
4952     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4953                   DAG.getIntPtrConstant(EltIdx))
4954     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4955                   DAG.getIntPtrConstant(EltIdx - 8));
4956     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4957                        DAG.getIntPtrConstant(i));
4958   }
4959   return NewV;
4960 }
4961
4962 // v16i8 shuffles - Prefer shuffles in the following order:
4963 // 1. [ssse3] 1 x pshufb
4964 // 2. [ssse3] 2 x pshufb + 1 x por
4965 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4966 static
4967 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4968                                  SelectionDAG &DAG,
4969                                  const X86TargetLowering &TLI) {
4970   SDValue V1 = SVOp->getOperand(0);
4971   SDValue V2 = SVOp->getOperand(1);
4972   DebugLoc dl = SVOp->getDebugLoc();
4973   SmallVector<int, 16> MaskVals;
4974   SVOp->getMask(MaskVals);
4975
4976   // If we have SSSE3, case 1 is generated when all result bytes come from
4977   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4978   // present, fall back to case 3.
4979   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4980   bool V1Only = true;
4981   bool V2Only = true;
4982   for (unsigned i = 0; i < 16; ++i) {
4983     int EltIdx = MaskVals[i];
4984     if (EltIdx < 0)
4985       continue;
4986     if (EltIdx < 16)
4987       V2Only = false;
4988     else
4989       V1Only = false;
4990   }
4991
4992   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4993   if (TLI.getSubtarget()->hasSSSE3()) {
4994     SmallVector<SDValue,16> pshufbMask;
4995
4996     // If all result elements are from one input vector, then only translate
4997     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4998     //
4999     // Otherwise, we have elements from both input vectors, and must zero out
5000     // elements that come from V2 in the first mask, and V1 in the second mask
5001     // so that we can OR them together.
5002     bool TwoInputs = !(V1Only || V2Only);
5003     for (unsigned i = 0; i != 16; ++i) {
5004       int EltIdx = MaskVals[i];
5005       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5006         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5007         continue;
5008       }
5009       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5010     }
5011     // If all the elements are from V2, assign it to V1 and return after
5012     // building the first pshufb.
5013     if (V2Only)
5014       V1 = V2;
5015     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5016                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5017                                  MVT::v16i8, &pshufbMask[0], 16));
5018     if (!TwoInputs)
5019       return V1;
5020
5021     // Calculate the shuffle mask for the second input, shuffle it, and
5022     // OR it with the first shuffled input.
5023     pshufbMask.clear();
5024     for (unsigned i = 0; i != 16; ++i) {
5025       int EltIdx = MaskVals[i];
5026       if (EltIdx < 16) {
5027         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5028         continue;
5029       }
5030       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5031     }
5032     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5033                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5034                                  MVT::v16i8, &pshufbMask[0], 16));
5035     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5036   }
5037
5038   // No SSSE3 - Calculate in place words and then fix all out of place words
5039   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5040   // the 16 different words that comprise the two doublequadword input vectors.
5041   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5042   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5043   SDValue NewV = V2Only ? V2 : V1;
5044   for (int i = 0; i != 8; ++i) {
5045     int Elt0 = MaskVals[i*2];
5046     int Elt1 = MaskVals[i*2+1];
5047
5048     // This word of the result is all undef, skip it.
5049     if (Elt0 < 0 && Elt1 < 0)
5050       continue;
5051
5052     // This word of the result is already in the correct place, skip it.
5053     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5054       continue;
5055     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5056       continue;
5057
5058     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5059     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5060     SDValue InsElt;
5061
5062     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5063     // using a single extract together, load it and store it.
5064     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5065       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5066                            DAG.getIntPtrConstant(Elt1 / 2));
5067       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5068                         DAG.getIntPtrConstant(i));
5069       continue;
5070     }
5071
5072     // If Elt1 is defined, extract it from the appropriate source.  If the
5073     // source byte is not also odd, shift the extracted word left 8 bits
5074     // otherwise clear the bottom 8 bits if we need to do an or.
5075     if (Elt1 >= 0) {
5076       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5077                            DAG.getIntPtrConstant(Elt1 / 2));
5078       if ((Elt1 & 1) == 0)
5079         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5080                              DAG.getConstant(8,
5081                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5082       else if (Elt0 >= 0)
5083         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5084                              DAG.getConstant(0xFF00, MVT::i16));
5085     }
5086     // If Elt0 is defined, extract it from the appropriate source.  If the
5087     // source byte is not also even, shift the extracted word right 8 bits. If
5088     // Elt1 was also defined, OR the extracted values together before
5089     // inserting them in the result.
5090     if (Elt0 >= 0) {
5091       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5092                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5093       if ((Elt0 & 1) != 0)
5094         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5095                               DAG.getConstant(8,
5096                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5097       else if (Elt1 >= 0)
5098         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5099                              DAG.getConstant(0x00FF, MVT::i16));
5100       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5101                          : InsElt0;
5102     }
5103     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5104                        DAG.getIntPtrConstant(i));
5105   }
5106   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5107 }
5108
5109 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5110 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5111 /// done when every pair / quad of shuffle mask elements point to elements in
5112 /// the right sequence. e.g.
5113 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5114 static
5115 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5116                                  SelectionDAG &DAG, DebugLoc dl) {
5117   EVT VT = SVOp->getValueType(0);
5118   SDValue V1 = SVOp->getOperand(0);
5119   SDValue V2 = SVOp->getOperand(1);
5120   unsigned NumElems = VT.getVectorNumElements();
5121   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5122   EVT NewVT;
5123   switch (VT.getSimpleVT().SimpleTy) {
5124   default: assert(false && "Unexpected!");
5125   case MVT::v4f32: NewVT = MVT::v2f64; break;
5126   case MVT::v4i32: NewVT = MVT::v2i64; break;
5127   case MVT::v8i16: NewVT = MVT::v4i32; break;
5128   case MVT::v16i8: NewVT = MVT::v4i32; break;
5129   }
5130
5131   int Scale = NumElems / NewWidth;
5132   SmallVector<int, 8> MaskVec;
5133   for (unsigned i = 0; i < NumElems; i += Scale) {
5134     int StartIdx = -1;
5135     for (int j = 0; j < Scale; ++j) {
5136       int EltIdx = SVOp->getMaskElt(i+j);
5137       if (EltIdx < 0)
5138         continue;
5139       if (StartIdx == -1)
5140         StartIdx = EltIdx - (EltIdx % Scale);
5141       if (EltIdx != StartIdx + j)
5142         return SDValue();
5143     }
5144     if (StartIdx == -1)
5145       MaskVec.push_back(-1);
5146     else
5147       MaskVec.push_back(StartIdx / Scale);
5148   }
5149
5150   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5151   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5152   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5153 }
5154
5155 /// getVZextMovL - Return a zero-extending vector move low node.
5156 ///
5157 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5158                             SDValue SrcOp, SelectionDAG &DAG,
5159                             const X86Subtarget *Subtarget, DebugLoc dl) {
5160   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5161     LoadSDNode *LD = NULL;
5162     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5163       LD = dyn_cast<LoadSDNode>(SrcOp);
5164     if (!LD) {
5165       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5166       // instead.
5167       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5168       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5169           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5170           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5171           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5172         // PR2108
5173         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5174         return DAG.getNode(ISD::BITCAST, dl, VT,
5175                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5176                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5177                                                    OpVT,
5178                                                    SrcOp.getOperand(0)
5179                                                           .getOperand(0))));
5180       }
5181     }
5182   }
5183
5184   return DAG.getNode(ISD::BITCAST, dl, VT,
5185                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5186                                  DAG.getNode(ISD::BITCAST, dl,
5187                                              OpVT, SrcOp)));
5188 }
5189
5190 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5191 /// shuffles.
5192 static SDValue
5193 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5194   SDValue V1 = SVOp->getOperand(0);
5195   SDValue V2 = SVOp->getOperand(1);
5196   DebugLoc dl = SVOp->getDebugLoc();
5197   EVT VT = SVOp->getValueType(0);
5198
5199   SmallVector<std::pair<int, int>, 8> Locs;
5200   Locs.resize(4);
5201   SmallVector<int, 8> Mask1(4U, -1);
5202   SmallVector<int, 8> PermMask;
5203   SVOp->getMask(PermMask);
5204
5205   unsigned NumHi = 0;
5206   unsigned NumLo = 0;
5207   for (unsigned i = 0; i != 4; ++i) {
5208     int Idx = PermMask[i];
5209     if (Idx < 0) {
5210       Locs[i] = std::make_pair(-1, -1);
5211     } else {
5212       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5213       if (Idx < 4) {
5214         Locs[i] = std::make_pair(0, NumLo);
5215         Mask1[NumLo] = Idx;
5216         NumLo++;
5217       } else {
5218         Locs[i] = std::make_pair(1, NumHi);
5219         if (2+NumHi < 4)
5220           Mask1[2+NumHi] = Idx;
5221         NumHi++;
5222       }
5223     }
5224   }
5225
5226   if (NumLo <= 2 && NumHi <= 2) {
5227     // If no more than two elements come from either vector. This can be
5228     // implemented with two shuffles. First shuffle gather the elements.
5229     // The second shuffle, which takes the first shuffle as both of its
5230     // vector operands, put the elements into the right order.
5231     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5232
5233     SmallVector<int, 8> Mask2(4U, -1);
5234
5235     for (unsigned i = 0; i != 4; ++i) {
5236       if (Locs[i].first == -1)
5237         continue;
5238       else {
5239         unsigned Idx = (i < 2) ? 0 : 4;
5240         Idx += Locs[i].first * 2 + Locs[i].second;
5241         Mask2[i] = Idx;
5242       }
5243     }
5244
5245     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5246   } else if (NumLo == 3 || NumHi == 3) {
5247     // Otherwise, we must have three elements from one vector, call it X, and
5248     // one element from the other, call it Y.  First, use a shufps to build an
5249     // intermediate vector with the one element from Y and the element from X
5250     // that will be in the same half in the final destination (the indexes don't
5251     // matter). Then, use a shufps to build the final vector, taking the half
5252     // containing the element from Y from the intermediate, and the other half
5253     // from X.
5254     if (NumHi == 3) {
5255       // Normalize it so the 3 elements come from V1.
5256       CommuteVectorShuffleMask(PermMask, VT);
5257       std::swap(V1, V2);
5258     }
5259
5260     // Find the element from V2.
5261     unsigned HiIndex;
5262     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5263       int Val = PermMask[HiIndex];
5264       if (Val < 0)
5265         continue;
5266       if (Val >= 4)
5267         break;
5268     }
5269
5270     Mask1[0] = PermMask[HiIndex];
5271     Mask1[1] = -1;
5272     Mask1[2] = PermMask[HiIndex^1];
5273     Mask1[3] = -1;
5274     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5275
5276     if (HiIndex >= 2) {
5277       Mask1[0] = PermMask[0];
5278       Mask1[1] = PermMask[1];
5279       Mask1[2] = HiIndex & 1 ? 6 : 4;
5280       Mask1[3] = HiIndex & 1 ? 4 : 6;
5281       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5282     } else {
5283       Mask1[0] = HiIndex & 1 ? 2 : 0;
5284       Mask1[1] = HiIndex & 1 ? 0 : 2;
5285       Mask1[2] = PermMask[2];
5286       Mask1[3] = PermMask[3];
5287       if (Mask1[2] >= 0)
5288         Mask1[2] += 4;
5289       if (Mask1[3] >= 0)
5290         Mask1[3] += 4;
5291       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5292     }
5293   }
5294
5295   // Break it into (shuffle shuffle_hi, shuffle_lo).
5296   Locs.clear();
5297   Locs.resize(4);
5298   SmallVector<int,8> LoMask(4U, -1);
5299   SmallVector<int,8> HiMask(4U, -1);
5300
5301   SmallVector<int,8> *MaskPtr = &LoMask;
5302   unsigned MaskIdx = 0;
5303   unsigned LoIdx = 0;
5304   unsigned HiIdx = 2;
5305   for (unsigned i = 0; i != 4; ++i) {
5306     if (i == 2) {
5307       MaskPtr = &HiMask;
5308       MaskIdx = 1;
5309       LoIdx = 0;
5310       HiIdx = 2;
5311     }
5312     int Idx = PermMask[i];
5313     if (Idx < 0) {
5314       Locs[i] = std::make_pair(-1, -1);
5315     } else if (Idx < 4) {
5316       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5317       (*MaskPtr)[LoIdx] = Idx;
5318       LoIdx++;
5319     } else {
5320       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5321       (*MaskPtr)[HiIdx] = Idx;
5322       HiIdx++;
5323     }
5324   }
5325
5326   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5327   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5328   SmallVector<int, 8> MaskOps;
5329   for (unsigned i = 0; i != 4; ++i) {
5330     if (Locs[i].first == -1) {
5331       MaskOps.push_back(-1);
5332     } else {
5333       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5334       MaskOps.push_back(Idx);
5335     }
5336   }
5337   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5338 }
5339
5340 static bool MayFoldVectorLoad(SDValue V) {
5341   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5342     V = V.getOperand(0);
5343   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5344     V = V.getOperand(0);
5345   if (MayFoldLoad(V))
5346     return true;
5347   return false;
5348 }
5349
5350 // FIXME: the version above should always be used. Since there's
5351 // a bug where several vector shuffles can't be folded because the
5352 // DAG is not updated during lowering and a node claims to have two
5353 // uses while it only has one, use this version, and let isel match
5354 // another instruction if the load really happens to have more than
5355 // one use. Remove this version after this bug get fixed.
5356 // rdar://8434668, PR8156
5357 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5358   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5359     V = V.getOperand(0);
5360   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5361     V = V.getOperand(0);
5362   if (ISD::isNormalLoad(V.getNode()))
5363     return true;
5364   return false;
5365 }
5366
5367 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5368 /// a vector extract, and if both can be later optimized into a single load.
5369 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5370 /// here because otherwise a target specific shuffle node is going to be
5371 /// emitted for this shuffle, and the optimization not done.
5372 /// FIXME: This is probably not the best approach, but fix the problem
5373 /// until the right path is decided.
5374 static
5375 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5376                                          const TargetLowering &TLI) {
5377   EVT VT = V.getValueType();
5378   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5379
5380   // Be sure that the vector shuffle is present in a pattern like this:
5381   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5382   if (!V.hasOneUse())
5383     return false;
5384
5385   SDNode *N = *V.getNode()->use_begin();
5386   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5387     return false;
5388
5389   SDValue EltNo = N->getOperand(1);
5390   if (!isa<ConstantSDNode>(EltNo))
5391     return false;
5392
5393   // If the bit convert changed the number of elements, it is unsafe
5394   // to examine the mask.
5395   bool HasShuffleIntoBitcast = false;
5396   if (V.getOpcode() == ISD::BITCAST) {
5397     EVT SrcVT = V.getOperand(0).getValueType();
5398     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5399       return false;
5400     V = V.getOperand(0);
5401     HasShuffleIntoBitcast = true;
5402   }
5403
5404   // Select the input vector, guarding against out of range extract vector.
5405   unsigned NumElems = VT.getVectorNumElements();
5406   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5407   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5408   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5409
5410   // Skip one more bit_convert if necessary
5411   if (V.getOpcode() == ISD::BITCAST)
5412     V = V.getOperand(0);
5413
5414   if (ISD::isNormalLoad(V.getNode())) {
5415     // Is the original load suitable?
5416     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5417
5418     // FIXME: avoid the multi-use bug that is preventing lots of
5419     // of foldings to be detected, this is still wrong of course, but
5420     // give the temporary desired behavior, and if it happens that
5421     // the load has real more uses, during isel it will not fold, and
5422     // will generate poor code.
5423     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5424       return false;
5425
5426     if (!HasShuffleIntoBitcast)
5427       return true;
5428
5429     // If there's a bitcast before the shuffle, check if the load type and
5430     // alignment is valid.
5431     unsigned Align = LN0->getAlignment();
5432     unsigned NewAlign =
5433       TLI.getTargetData()->getABITypeAlignment(
5434                                     VT.getTypeForEVT(*DAG.getContext()));
5435
5436     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5437       return false;
5438   }
5439
5440   return true;
5441 }
5442
5443 static
5444 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5445   EVT VT = Op.getValueType();
5446
5447   // Canonizalize to v2f64.
5448   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5449   return DAG.getNode(ISD::BITCAST, dl, VT,
5450                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5451                                           V1, DAG));
5452 }
5453
5454 static
5455 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5456                         bool HasSSE2) {
5457   SDValue V1 = Op.getOperand(0);
5458   SDValue V2 = Op.getOperand(1);
5459   EVT VT = Op.getValueType();
5460
5461   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5462
5463   if (HasSSE2 && VT == MVT::v2f64)
5464     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5465
5466   // v4f32 or v4i32
5467   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5468 }
5469
5470 static
5471 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5472   SDValue V1 = Op.getOperand(0);
5473   SDValue V2 = Op.getOperand(1);
5474   EVT VT = Op.getValueType();
5475
5476   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5477          "unsupported shuffle type");
5478
5479   if (V2.getOpcode() == ISD::UNDEF)
5480     V2 = V1;
5481
5482   // v4i32 or v4f32
5483   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5484 }
5485
5486 static
5487 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5488   SDValue V1 = Op.getOperand(0);
5489   SDValue V2 = Op.getOperand(1);
5490   EVT VT = Op.getValueType();
5491   unsigned NumElems = VT.getVectorNumElements();
5492
5493   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5494   // operand of these instructions is only memory, so check if there's a
5495   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5496   // same masks.
5497   bool CanFoldLoad = false;
5498
5499   // Trivial case, when V2 comes from a load.
5500   if (MayFoldVectorLoad(V2))
5501     CanFoldLoad = true;
5502
5503   // When V1 is a load, it can be folded later into a store in isel, example:
5504   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5505   //    turns into:
5506   //  (MOVLPSmr addr:$src1, VR128:$src2)
5507   // So, recognize this potential and also use MOVLPS or MOVLPD
5508   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5509     CanFoldLoad = true;
5510
5511   // Both of them can't be memory operations though.
5512   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5513     CanFoldLoad = false;
5514
5515   if (CanFoldLoad) {
5516     if (HasSSE2 && NumElems == 2)
5517       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5518
5519     if (NumElems == 4)
5520       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5521   }
5522
5523   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5524   // movl and movlp will both match v2i64, but v2i64 is never matched by
5525   // movl earlier because we make it strict to avoid messing with the movlp load
5526   // folding logic (see the code above getMOVLP call). Match it here then,
5527   // this is horrible, but will stay like this until we move all shuffle
5528   // matching to x86 specific nodes. Note that for the 1st condition all
5529   // types are matched with movsd.
5530   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5531     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5532   else if (HasSSE2)
5533     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5534
5535
5536   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5537
5538   // Invert the operand order and use SHUFPS to match it.
5539   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5540                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5541 }
5542
5543 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5544   switch(VT.getSimpleVT().SimpleTy) {
5545   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5546   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5547   case MVT::v4f32:
5548     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5549   case MVT::v2f64:
5550     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5551   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5552   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5553   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5554   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5555   default:
5556     llvm_unreachable("Unknown type for unpckl");
5557   }
5558   return 0;
5559 }
5560
5561 static inline unsigned getUNPCKHOpcode(EVT VT) {
5562   switch(VT.getSimpleVT().SimpleTy) {
5563   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5564   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5565   case MVT::v4f32: return X86ISD::UNPCKHPS;
5566   case MVT::v2f64: return X86ISD::UNPCKHPD;
5567   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5568   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5569   default:
5570     llvm_unreachable("Unknown type for unpckh");
5571   }
5572   return 0;
5573 }
5574
5575 static
5576 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5577                                const TargetLowering &TLI,
5578                                const X86Subtarget *Subtarget) {
5579   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5580   EVT VT = Op.getValueType();
5581   DebugLoc dl = Op.getDebugLoc();
5582   SDValue V1 = Op.getOperand(0);
5583   SDValue V2 = Op.getOperand(1);
5584
5585   if (isZeroShuffle(SVOp))
5586     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5587
5588   // Handle splat operations
5589   if (SVOp->isSplat()) {
5590     // Special case, this is the only place now where it's
5591     // allowed to return a vector_shuffle operation without
5592     // using a target specific node, because *hopefully* it
5593     // will be optimized away by the dag combiner.
5594     if (VT.getVectorNumElements() <= 4 &&
5595         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5596       return Op;
5597
5598     // Handle splats by matching through known masks
5599     if (VT.getVectorNumElements() <= 4)
5600       return SDValue();
5601
5602     // Canonicalize all of the remaining to v4f32.
5603     return PromoteSplat(SVOp, DAG);
5604   }
5605
5606   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5607   // do it!
5608   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5609     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5610     if (NewOp.getNode())
5611       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5612   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5613     // FIXME: Figure out a cleaner way to do this.
5614     // Try to make use of movq to zero out the top part.
5615     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5616       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5617       if (NewOp.getNode()) {
5618         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5619           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5620                               DAG, Subtarget, dl);
5621       }
5622     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5623       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5624       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5625         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5626                             DAG, Subtarget, dl);
5627     }
5628   }
5629   return SDValue();
5630 }
5631
5632 SDValue
5633 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5634   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5635   SDValue V1 = Op.getOperand(0);
5636   SDValue V2 = Op.getOperand(1);
5637   EVT VT = Op.getValueType();
5638   DebugLoc dl = Op.getDebugLoc();
5639   unsigned NumElems = VT.getVectorNumElements();
5640   bool isMMX = VT.getSizeInBits() == 64;
5641   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5642   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5643   bool V1IsSplat = false;
5644   bool V2IsSplat = false;
5645   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5646   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5647   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5648   MachineFunction &MF = DAG.getMachineFunction();
5649   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5650
5651   // Shuffle operations on MMX not supported.
5652   if (isMMX)
5653     return Op;
5654
5655   // Vector shuffle lowering takes 3 steps:
5656   //
5657   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5658   //    narrowing and commutation of operands should be handled.
5659   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5660   //    shuffle nodes.
5661   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5662   //    so the shuffle can be broken into other shuffles and the legalizer can
5663   //    try the lowering again.
5664   //
5665   // The general ideia is that no vector_shuffle operation should be left to
5666   // be matched during isel, all of them must be converted to a target specific
5667   // node here.
5668
5669   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5670   // narrowing and commutation of operands should be handled. The actual code
5671   // doesn't include all of those, work in progress...
5672   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5673   if (NewOp.getNode())
5674     return NewOp;
5675
5676   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5677   // unpckh_undef). Only use pshufd if speed is more important than size.
5678   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5679     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5680       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5681   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5682     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5683       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5684
5685   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5686       RelaxedMayFoldVectorLoad(V1))
5687     return getMOVDDup(Op, dl, V1, DAG);
5688
5689   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5690     return getMOVHighToLow(Op, dl, DAG);
5691
5692   // Use to match splats
5693   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5694       (VT == MVT::v2f64 || VT == MVT::v2i64))
5695     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5696
5697   if (X86::isPSHUFDMask(SVOp)) {
5698     // The actual implementation will match the mask in the if above and then
5699     // during isel it can match several different instructions, not only pshufd
5700     // as its name says, sad but true, emulate the behavior for now...
5701     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5702         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5703
5704     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5705
5706     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5707       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5708
5709     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5710       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5711                                   TargetMask, DAG);
5712
5713     if (VT == MVT::v4f32)
5714       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5715                                   TargetMask, DAG);
5716   }
5717
5718   // Check if this can be converted into a logical shift.
5719   bool isLeft = false;
5720   unsigned ShAmt = 0;
5721   SDValue ShVal;
5722   bool isShift = getSubtarget()->hasSSE2() &&
5723     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5724   if (isShift && ShVal.hasOneUse()) {
5725     // If the shifted value has multiple uses, it may be cheaper to use
5726     // v_set0 + movlhps or movhlps, etc.
5727     EVT EltVT = VT.getVectorElementType();
5728     ShAmt *= EltVT.getSizeInBits();
5729     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5730   }
5731
5732   if (X86::isMOVLMask(SVOp)) {
5733     if (V1IsUndef)
5734       return V2;
5735     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5736       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5737     if (!X86::isMOVLPMask(SVOp)) {
5738       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5739         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5740
5741       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5742         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5743     }
5744   }
5745
5746   // FIXME: fold these into legal mask.
5747   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5748     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5749
5750   if (X86::isMOVHLPSMask(SVOp))
5751     return getMOVHighToLow(Op, dl, DAG);
5752
5753   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5754     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5755
5756   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5757     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5758
5759   if (X86::isMOVLPMask(SVOp))
5760     return getMOVLP(Op, dl, DAG, HasSSE2);
5761
5762   if (ShouldXformToMOVHLPS(SVOp) ||
5763       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5764     return CommuteVectorShuffle(SVOp, DAG);
5765
5766   if (isShift) {
5767     // No better options. Use a vshl / vsrl.
5768     EVT EltVT = VT.getVectorElementType();
5769     ShAmt *= EltVT.getSizeInBits();
5770     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5771   }
5772
5773   bool Commuted = false;
5774   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5775   // 1,1,1,1 -> v8i16 though.
5776   V1IsSplat = isSplatVector(V1.getNode());
5777   V2IsSplat = isSplatVector(V2.getNode());
5778
5779   // Canonicalize the splat or undef, if present, to be on the RHS.
5780   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5781     Op = CommuteVectorShuffle(SVOp, DAG);
5782     SVOp = cast<ShuffleVectorSDNode>(Op);
5783     V1 = SVOp->getOperand(0);
5784     V2 = SVOp->getOperand(1);
5785     std::swap(V1IsSplat, V2IsSplat);
5786     std::swap(V1IsUndef, V2IsUndef);
5787     Commuted = true;
5788   }
5789
5790   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5791     // Shuffling low element of v1 into undef, just return v1.
5792     if (V2IsUndef)
5793       return V1;
5794     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5795     // the instruction selector will not match, so get a canonical MOVL with
5796     // swapped operands to undo the commute.
5797     return getMOVL(DAG, dl, VT, V2, V1);
5798   }
5799
5800   if (X86::isUNPCKLMask(SVOp))
5801     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5802                                 dl, VT, V1, V2, DAG);
5803
5804   if (X86::isUNPCKHMask(SVOp))
5805     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5806
5807   if (V2IsSplat) {
5808     // Normalize mask so all entries that point to V2 points to its first
5809     // element then try to match unpck{h|l} again. If match, return a
5810     // new vector_shuffle with the corrected mask.
5811     SDValue NewMask = NormalizeMask(SVOp, DAG);
5812     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5813     if (NSVOp != SVOp) {
5814       if (X86::isUNPCKLMask(NSVOp, true)) {
5815         return NewMask;
5816       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5817         return NewMask;
5818       }
5819     }
5820   }
5821
5822   if (Commuted) {
5823     // Commute is back and try unpck* again.
5824     // FIXME: this seems wrong.
5825     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5826     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5827
5828     if (X86::isUNPCKLMask(NewSVOp))
5829       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5830                                   dl, VT, V2, V1, DAG);
5831
5832     if (X86::isUNPCKHMask(NewSVOp))
5833       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5834   }
5835
5836   // Normalize the node to match x86 shuffle ops if needed
5837   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5838     return CommuteVectorShuffle(SVOp, DAG);
5839
5840   // The checks below are all present in isShuffleMaskLegal, but they are
5841   // inlined here right now to enable us to directly emit target specific
5842   // nodes, and remove one by one until they don't return Op anymore.
5843   SmallVector<int, 16> M;
5844   SVOp->getMask(M);
5845
5846   if (isPALIGNRMask(M, VT, HasSSSE3))
5847     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5848                                 X86::getShufflePALIGNRImmediate(SVOp),
5849                                 DAG);
5850
5851   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5852       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5853     if (VT == MVT::v2f64) {
5854       X86ISD::NodeType Opcode =
5855         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5856       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5857     }
5858     if (VT == MVT::v2i64)
5859       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5860   }
5861
5862   if (isPSHUFHWMask(M, VT))
5863     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5864                                 X86::getShufflePSHUFHWImmediate(SVOp),
5865                                 DAG);
5866
5867   if (isPSHUFLWMask(M, VT))
5868     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5869                                 X86::getShufflePSHUFLWImmediate(SVOp),
5870                                 DAG);
5871
5872   if (isSHUFPMask(M, VT)) {
5873     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5874     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5875       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5876                                   TargetMask, DAG);
5877     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5878       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5879                                   TargetMask, DAG);
5880   }
5881
5882   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5883     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5884       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5885                                   dl, VT, V1, V1, DAG);
5886   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5887     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5888       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5889
5890   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5891   if (VT == MVT::v8i16) {
5892     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5893     if (NewOp.getNode())
5894       return NewOp;
5895   }
5896
5897   if (VT == MVT::v16i8) {
5898     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5899     if (NewOp.getNode())
5900       return NewOp;
5901   }
5902
5903   // Handle all 4 wide cases with a number of shuffles.
5904   if (NumElems == 4)
5905     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5906
5907   return SDValue();
5908 }
5909
5910 SDValue
5911 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5912                                                 SelectionDAG &DAG) const {
5913   EVT VT = Op.getValueType();
5914   DebugLoc dl = Op.getDebugLoc();
5915   if (VT.getSizeInBits() == 8) {
5916     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5917                                     Op.getOperand(0), Op.getOperand(1));
5918     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5919                                     DAG.getValueType(VT));
5920     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5921   } else if (VT.getSizeInBits() == 16) {
5922     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5923     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5924     if (Idx == 0)
5925       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5926                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5927                                      DAG.getNode(ISD::BITCAST, dl,
5928                                                  MVT::v4i32,
5929                                                  Op.getOperand(0)),
5930                                      Op.getOperand(1)));
5931     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5932                                     Op.getOperand(0), Op.getOperand(1));
5933     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5934                                     DAG.getValueType(VT));
5935     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5936   } else if (VT == MVT::f32) {
5937     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5938     // the result back to FR32 register. It's only worth matching if the
5939     // result has a single use which is a store or a bitcast to i32.  And in
5940     // the case of a store, it's not worth it if the index is a constant 0,
5941     // because a MOVSSmr can be used instead, which is smaller and faster.
5942     if (!Op.hasOneUse())
5943       return SDValue();
5944     SDNode *User = *Op.getNode()->use_begin();
5945     if ((User->getOpcode() != ISD::STORE ||
5946          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5947           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5948         (User->getOpcode() != ISD::BITCAST ||
5949          User->getValueType(0) != MVT::i32))
5950       return SDValue();
5951     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5952                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5953                                               Op.getOperand(0)),
5954                                               Op.getOperand(1));
5955     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5956   } else if (VT == MVT::i32) {
5957     // ExtractPS works with constant index.
5958     if (isa<ConstantSDNode>(Op.getOperand(1)))
5959       return Op;
5960   }
5961   return SDValue();
5962 }
5963
5964
5965 SDValue
5966 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5967                                            SelectionDAG &DAG) const {
5968   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5969     return SDValue();
5970
5971   SDValue Vec = Op.getOperand(0);
5972   EVT VecVT = Vec.getValueType();
5973
5974   // If this is a 256-bit vector result, first extract the 128-bit
5975   // vector and then extract from the 128-bit vector.
5976   if (VecVT.getSizeInBits() > 128) {
5977     DebugLoc dl = Op.getNode()->getDebugLoc();
5978     unsigned NumElems = VecVT.getVectorNumElements();
5979     SDValue Idx = Op.getOperand(1);
5980
5981     if (!isa<ConstantSDNode>(Idx))
5982       return SDValue();
5983
5984     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
5985     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5986
5987     // Get the 128-bit vector.
5988     bool Upper = IdxVal >= ExtractNumElems;
5989     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
5990
5991     // Extract from it.
5992     SDValue ScaledIdx = Idx;
5993     if (Upper)
5994       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
5995                               DAG.getConstant(ExtractNumElems,
5996                                               Idx.getValueType()));
5997     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
5998                        ScaledIdx);
5999   }
6000
6001   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6002
6003   if (Subtarget->hasSSE41()) {
6004     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6005     if (Res.getNode())
6006       return Res;
6007   }
6008
6009   EVT VT = Op.getValueType();
6010   DebugLoc dl = Op.getDebugLoc();
6011   // TODO: handle v16i8.
6012   if (VT.getSizeInBits() == 16) {
6013     SDValue Vec = Op.getOperand(0);
6014     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6015     if (Idx == 0)
6016       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6017                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6018                                      DAG.getNode(ISD::BITCAST, dl,
6019                                                  MVT::v4i32, Vec),
6020                                      Op.getOperand(1)));
6021     // Transform it so it match pextrw which produces a 32-bit result.
6022     EVT EltVT = MVT::i32;
6023     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6024                                     Op.getOperand(0), Op.getOperand(1));
6025     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6026                                     DAG.getValueType(VT));
6027     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6028   } else if (VT.getSizeInBits() == 32) {
6029     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6030     if (Idx == 0)
6031       return Op;
6032
6033     // SHUFPS the element to the lowest double word, then movss.
6034     int Mask[4] = { Idx, -1, -1, -1 };
6035     EVT VVT = Op.getOperand(0).getValueType();
6036     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6037                                        DAG.getUNDEF(VVT), Mask);
6038     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6039                        DAG.getIntPtrConstant(0));
6040   } else if (VT.getSizeInBits() == 64) {
6041     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6042     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6043     //        to match extract_elt for f64.
6044     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6045     if (Idx == 0)
6046       return Op;
6047
6048     // UNPCKHPD the element to the lowest double word, then movsd.
6049     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6050     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6051     int Mask[2] = { 1, -1 };
6052     EVT VVT = Op.getOperand(0).getValueType();
6053     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6054                                        DAG.getUNDEF(VVT), Mask);
6055     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6056                        DAG.getIntPtrConstant(0));
6057   }
6058
6059   return SDValue();
6060 }
6061
6062 SDValue
6063 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6064                                                SelectionDAG &DAG) const {
6065   EVT VT = Op.getValueType();
6066   EVT EltVT = VT.getVectorElementType();
6067   DebugLoc dl = Op.getDebugLoc();
6068
6069   SDValue N0 = Op.getOperand(0);
6070   SDValue N1 = Op.getOperand(1);
6071   SDValue N2 = Op.getOperand(2);
6072
6073   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6074       isa<ConstantSDNode>(N2)) {
6075     unsigned Opc;
6076     if (VT == MVT::v8i16)
6077       Opc = X86ISD::PINSRW;
6078     else if (VT == MVT::v16i8)
6079       Opc = X86ISD::PINSRB;
6080     else
6081       Opc = X86ISD::PINSRB;
6082
6083     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6084     // argument.
6085     if (N1.getValueType() != MVT::i32)
6086       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6087     if (N2.getValueType() != MVT::i32)
6088       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6089     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6090   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6091     // Bits [7:6] of the constant are the source select.  This will always be
6092     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6093     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6094     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6095     // Bits [5:4] of the constant are the destination select.  This is the
6096     //  value of the incoming immediate.
6097     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6098     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6099     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6100     // Create this as a scalar to vector..
6101     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6102     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6103   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6104     // PINSR* works with constant index.
6105     return Op;
6106   }
6107   return SDValue();
6108 }
6109
6110 SDValue
6111 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6112   EVT VT = Op.getValueType();
6113   EVT EltVT = VT.getVectorElementType();
6114
6115   DebugLoc dl = Op.getDebugLoc();
6116   SDValue N0 = Op.getOperand(0);
6117   SDValue N1 = Op.getOperand(1);
6118   SDValue N2 = Op.getOperand(2);
6119
6120   // If this is a 256-bit vector result, first insert into a 128-bit
6121   // vector and then insert into the 256-bit vector.
6122   if (VT.getSizeInBits() > 128) {
6123     if (!isa<ConstantSDNode>(N2))
6124       return SDValue();
6125
6126     // Get the 128-bit vector.
6127     unsigned NumElems = VT.getVectorNumElements();
6128     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6129     bool Upper = IdxVal >= NumElems / 2;
6130
6131     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6132
6133     // Insert into it.
6134     SDValue ScaledN2 = N2;
6135     if (Upper)
6136       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6137                              DAG.getConstant(NumElems /
6138                                              (VT.getSizeInBits() / 128),
6139                                              N2.getValueType()));
6140     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6141                      N1, ScaledN2);
6142
6143     // Insert the 128-bit vector
6144     // FIXME: Why UNDEF?
6145     return Insert128BitVector(N0, Op, N2, DAG, dl);
6146   }
6147
6148   if (Subtarget->hasSSE41())
6149     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6150
6151   if (EltVT == MVT::i8)
6152     return SDValue();
6153
6154   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6155     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6156     // as its second argument.
6157     if (N1.getValueType() != MVT::i32)
6158       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6159     if (N2.getValueType() != MVT::i32)
6160       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6161     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6162   }
6163   return SDValue();
6164 }
6165
6166 SDValue
6167 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6168   LLVMContext *Context = DAG.getContext();
6169   DebugLoc dl = Op.getDebugLoc();
6170   EVT OpVT = Op.getValueType();
6171
6172   // If this is a 256-bit vector result, first insert into a 128-bit
6173   // vector and then insert into the 256-bit vector.
6174   if (OpVT.getSizeInBits() > 128) {
6175     // Insert into a 128-bit vector.
6176     EVT VT128 = EVT::getVectorVT(*Context,
6177                                  OpVT.getVectorElementType(),
6178                                  OpVT.getVectorNumElements() / 2);
6179
6180     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6181
6182     // Insert the 128-bit vector.
6183     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6184                               DAG.getConstant(0, MVT::i32),
6185                               DAG, dl);
6186   }
6187
6188   if (Op.getValueType() == MVT::v1i64 &&
6189       Op.getOperand(0).getValueType() == MVT::i64)
6190     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6191
6192   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6193   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6194          "Expected an SSE type!");
6195   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6196                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6197 }
6198
6199 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6200 // a simple subregister reference or explicit instructions to grab
6201 // upper bits of a vector.
6202 SDValue
6203 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6204   if (Subtarget->hasAVX()) {
6205     DebugLoc dl = Op.getNode()->getDebugLoc();
6206     SDValue Vec = Op.getNode()->getOperand(0);
6207     SDValue Idx = Op.getNode()->getOperand(1);
6208
6209     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6210         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6211         return Extract128BitVector(Vec, Idx, DAG, dl);
6212     }
6213   }
6214   return SDValue();
6215 }
6216
6217 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6218 // simple superregister reference or explicit instructions to insert
6219 // the upper bits of a vector.
6220 SDValue
6221 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6222   if (Subtarget->hasAVX()) {
6223     DebugLoc dl = Op.getNode()->getDebugLoc();
6224     SDValue Vec = Op.getNode()->getOperand(0);
6225     SDValue SubVec = Op.getNode()->getOperand(1);
6226     SDValue Idx = Op.getNode()->getOperand(2);
6227
6228     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6229         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6230       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6231     }
6232   }
6233   return SDValue();
6234 }
6235
6236 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6237 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6238 // one of the above mentioned nodes. It has to be wrapped because otherwise
6239 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6240 // be used to form addressing mode. These wrapped nodes will be selected
6241 // into MOV32ri.
6242 SDValue
6243 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6244   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6245
6246   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6247   // global base reg.
6248   unsigned char OpFlag = 0;
6249   unsigned WrapperKind = X86ISD::Wrapper;
6250   CodeModel::Model M = getTargetMachine().getCodeModel();
6251
6252   if (Subtarget->isPICStyleRIPRel() &&
6253       (M == CodeModel::Small || M == CodeModel::Kernel))
6254     WrapperKind = X86ISD::WrapperRIP;
6255   else if (Subtarget->isPICStyleGOT())
6256     OpFlag = X86II::MO_GOTOFF;
6257   else if (Subtarget->isPICStyleStubPIC())
6258     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6259
6260   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6261                                              CP->getAlignment(),
6262                                              CP->getOffset(), OpFlag);
6263   DebugLoc DL = CP->getDebugLoc();
6264   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6265   // With PIC, the address is actually $g + Offset.
6266   if (OpFlag) {
6267     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6268                          DAG.getNode(X86ISD::GlobalBaseReg,
6269                                      DebugLoc(), getPointerTy()),
6270                          Result);
6271   }
6272
6273   return Result;
6274 }
6275
6276 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6277   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6278
6279   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6280   // global base reg.
6281   unsigned char OpFlag = 0;
6282   unsigned WrapperKind = X86ISD::Wrapper;
6283   CodeModel::Model M = getTargetMachine().getCodeModel();
6284
6285   if (Subtarget->isPICStyleRIPRel() &&
6286       (M == CodeModel::Small || M == CodeModel::Kernel))
6287     WrapperKind = X86ISD::WrapperRIP;
6288   else if (Subtarget->isPICStyleGOT())
6289     OpFlag = X86II::MO_GOTOFF;
6290   else if (Subtarget->isPICStyleStubPIC())
6291     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6292
6293   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6294                                           OpFlag);
6295   DebugLoc DL = JT->getDebugLoc();
6296   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6297
6298   // With PIC, the address is actually $g + Offset.
6299   if (OpFlag)
6300     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6301                          DAG.getNode(X86ISD::GlobalBaseReg,
6302                                      DebugLoc(), getPointerTy()),
6303                          Result);
6304
6305   return Result;
6306 }
6307
6308 SDValue
6309 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6310   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6311
6312   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6313   // global base reg.
6314   unsigned char OpFlag = 0;
6315   unsigned WrapperKind = X86ISD::Wrapper;
6316   CodeModel::Model M = getTargetMachine().getCodeModel();
6317
6318   if (Subtarget->isPICStyleRIPRel() &&
6319       (M == CodeModel::Small || M == CodeModel::Kernel))
6320     WrapperKind = X86ISD::WrapperRIP;
6321   else if (Subtarget->isPICStyleGOT())
6322     OpFlag = X86II::MO_GOTOFF;
6323   else if (Subtarget->isPICStyleStubPIC())
6324     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6325
6326   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6327
6328   DebugLoc DL = Op.getDebugLoc();
6329   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6330
6331
6332   // With PIC, the address is actually $g + Offset.
6333   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6334       !Subtarget->is64Bit()) {
6335     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6336                          DAG.getNode(X86ISD::GlobalBaseReg,
6337                                      DebugLoc(), getPointerTy()),
6338                          Result);
6339   }
6340
6341   return Result;
6342 }
6343
6344 SDValue
6345 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6346   // Create the TargetBlockAddressAddress node.
6347   unsigned char OpFlags =
6348     Subtarget->ClassifyBlockAddressReference();
6349   CodeModel::Model M = getTargetMachine().getCodeModel();
6350   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6351   DebugLoc dl = Op.getDebugLoc();
6352   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6353                                        /*isTarget=*/true, OpFlags);
6354
6355   if (Subtarget->isPICStyleRIPRel() &&
6356       (M == CodeModel::Small || M == CodeModel::Kernel))
6357     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6358   else
6359     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6360
6361   // With PIC, the address is actually $g + Offset.
6362   if (isGlobalRelativeToPICBase(OpFlags)) {
6363     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6364                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6365                          Result);
6366   }
6367
6368   return Result;
6369 }
6370
6371 SDValue
6372 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6373                                       int64_t Offset,
6374                                       SelectionDAG &DAG) const {
6375   // Create the TargetGlobalAddress node, folding in the constant
6376   // offset if it is legal.
6377   unsigned char OpFlags =
6378     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6379   CodeModel::Model M = getTargetMachine().getCodeModel();
6380   SDValue Result;
6381   if (OpFlags == X86II::MO_NO_FLAG &&
6382       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6383     // A direct static reference to a global.
6384     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6385     Offset = 0;
6386   } else {
6387     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6388   }
6389
6390   if (Subtarget->isPICStyleRIPRel() &&
6391       (M == CodeModel::Small || M == CodeModel::Kernel))
6392     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6393   else
6394     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6395
6396   // With PIC, the address is actually $g + Offset.
6397   if (isGlobalRelativeToPICBase(OpFlags)) {
6398     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6399                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6400                          Result);
6401   }
6402
6403   // For globals that require a load from a stub to get the address, emit the
6404   // load.
6405   if (isGlobalStubReference(OpFlags))
6406     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6407                          MachinePointerInfo::getGOT(), false, false, 0);
6408
6409   // If there was a non-zero offset that we didn't fold, create an explicit
6410   // addition for it.
6411   if (Offset != 0)
6412     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6413                          DAG.getConstant(Offset, getPointerTy()));
6414
6415   return Result;
6416 }
6417
6418 SDValue
6419 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6420   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6421   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6422   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6423 }
6424
6425 static SDValue
6426 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6427            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6428            unsigned char OperandFlags) {
6429   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6430   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6431   DebugLoc dl = GA->getDebugLoc();
6432   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6433                                            GA->getValueType(0),
6434                                            GA->getOffset(),
6435                                            OperandFlags);
6436   if (InFlag) {
6437     SDValue Ops[] = { Chain,  TGA, *InFlag };
6438     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6439   } else {
6440     SDValue Ops[]  = { Chain, TGA };
6441     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6442   }
6443
6444   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6445   MFI->setAdjustsStack(true);
6446
6447   SDValue Flag = Chain.getValue(1);
6448   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6449 }
6450
6451 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6452 static SDValue
6453 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6454                                 const EVT PtrVT) {
6455   SDValue InFlag;
6456   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6457   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6458                                      DAG.getNode(X86ISD::GlobalBaseReg,
6459                                                  DebugLoc(), PtrVT), InFlag);
6460   InFlag = Chain.getValue(1);
6461
6462   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6463 }
6464
6465 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6466 static SDValue
6467 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6468                                 const EVT PtrVT) {
6469   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6470                     X86::RAX, X86II::MO_TLSGD);
6471 }
6472
6473 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6474 // "local exec" model.
6475 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6476                                    const EVT PtrVT, TLSModel::Model model,
6477                                    bool is64Bit) {
6478   DebugLoc dl = GA->getDebugLoc();
6479
6480   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6481   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6482                                                          is64Bit ? 257 : 256));
6483
6484   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6485                                       DAG.getIntPtrConstant(0),
6486                                       MachinePointerInfo(Ptr), false, false, 0);
6487
6488   unsigned char OperandFlags = 0;
6489   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6490   // initialexec.
6491   unsigned WrapperKind = X86ISD::Wrapper;
6492   if (model == TLSModel::LocalExec) {
6493     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6494   } else if (is64Bit) {
6495     assert(model == TLSModel::InitialExec);
6496     OperandFlags = X86II::MO_GOTTPOFF;
6497     WrapperKind = X86ISD::WrapperRIP;
6498   } else {
6499     assert(model == TLSModel::InitialExec);
6500     OperandFlags = X86II::MO_INDNTPOFF;
6501   }
6502
6503   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6504   // exec)
6505   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6506                                            GA->getValueType(0),
6507                                            GA->getOffset(), OperandFlags);
6508   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6509
6510   if (model == TLSModel::InitialExec)
6511     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6512                          MachinePointerInfo::getGOT(), false, false, 0);
6513
6514   // The address of the thread local variable is the add of the thread
6515   // pointer with the offset of the variable.
6516   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6517 }
6518
6519 SDValue
6520 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6521
6522   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6523   const GlobalValue *GV = GA->getGlobal();
6524
6525   if (Subtarget->isTargetELF()) {
6526     // TODO: implement the "local dynamic" model
6527     // TODO: implement the "initial exec"model for pic executables
6528
6529     // If GV is an alias then use the aliasee for determining
6530     // thread-localness.
6531     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6532       GV = GA->resolveAliasedGlobal(false);
6533
6534     TLSModel::Model model
6535       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6536
6537     switch (model) {
6538       case TLSModel::GeneralDynamic:
6539       case TLSModel::LocalDynamic: // not implemented
6540         if (Subtarget->is64Bit())
6541           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6542         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6543
6544       case TLSModel::InitialExec:
6545       case TLSModel::LocalExec:
6546         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6547                                    Subtarget->is64Bit());
6548     }
6549   } else if (Subtarget->isTargetDarwin()) {
6550     // Darwin only has one model of TLS.  Lower to that.
6551     unsigned char OpFlag = 0;
6552     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6553                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6554
6555     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6556     // global base reg.
6557     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6558                   !Subtarget->is64Bit();
6559     if (PIC32)
6560       OpFlag = X86II::MO_TLVP_PIC_BASE;
6561     else
6562       OpFlag = X86II::MO_TLVP;
6563     DebugLoc DL = Op.getDebugLoc();
6564     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6565                                                 GA->getValueType(0),
6566                                                 GA->getOffset(), OpFlag);
6567     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6568
6569     // With PIC32, the address is actually $g + Offset.
6570     if (PIC32)
6571       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6572                            DAG.getNode(X86ISD::GlobalBaseReg,
6573                                        DebugLoc(), getPointerTy()),
6574                            Offset);
6575
6576     // Lowering the machine isd will make sure everything is in the right
6577     // location.
6578     SDValue Chain = DAG.getEntryNode();
6579     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6580     SDValue Args[] = { Chain, Offset };
6581     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6582
6583     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6584     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6585     MFI->setAdjustsStack(true);
6586
6587     // And our return value (tls address) is in the standard call return value
6588     // location.
6589     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6590     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6591   }
6592
6593   assert(false &&
6594          "TLS not implemented for this target.");
6595
6596   llvm_unreachable("Unreachable");
6597   return SDValue();
6598 }
6599
6600
6601 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6602 /// take a 2 x i32 value to shift plus a shift amount.
6603 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6604   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6605   EVT VT = Op.getValueType();
6606   unsigned VTBits = VT.getSizeInBits();
6607   DebugLoc dl = Op.getDebugLoc();
6608   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6609   SDValue ShOpLo = Op.getOperand(0);
6610   SDValue ShOpHi = Op.getOperand(1);
6611   SDValue ShAmt  = Op.getOperand(2);
6612   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6613                                      DAG.getConstant(VTBits - 1, MVT::i8))
6614                        : DAG.getConstant(0, VT);
6615
6616   SDValue Tmp2, Tmp3;
6617   if (Op.getOpcode() == ISD::SHL_PARTS) {
6618     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6619     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6620   } else {
6621     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6622     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6623   }
6624
6625   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6626                                 DAG.getConstant(VTBits, MVT::i8));
6627   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6628                              AndNode, DAG.getConstant(0, MVT::i8));
6629
6630   SDValue Hi, Lo;
6631   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6632   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6633   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6634
6635   if (Op.getOpcode() == ISD::SHL_PARTS) {
6636     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6637     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6638   } else {
6639     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6640     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6641   }
6642
6643   SDValue Ops[2] = { Lo, Hi };
6644   return DAG.getMergeValues(Ops, 2, dl);
6645 }
6646
6647 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6648                                            SelectionDAG &DAG) const {
6649   EVT SrcVT = Op.getOperand(0).getValueType();
6650
6651   if (SrcVT.isVector())
6652     return SDValue();
6653
6654   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6655          "Unknown SINT_TO_FP to lower!");
6656
6657   // These are really Legal; return the operand so the caller accepts it as
6658   // Legal.
6659   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6660     return Op;
6661   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6662       Subtarget->is64Bit()) {
6663     return Op;
6664   }
6665
6666   DebugLoc dl = Op.getDebugLoc();
6667   unsigned Size = SrcVT.getSizeInBits()/8;
6668   MachineFunction &MF = DAG.getMachineFunction();
6669   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6670   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6671   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6672                                StackSlot,
6673                                MachinePointerInfo::getFixedStack(SSFI),
6674                                false, false, 0);
6675   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6676 }
6677
6678 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6679                                      SDValue StackSlot,
6680                                      SelectionDAG &DAG) const {
6681   // Build the FILD
6682   DebugLoc DL = Op.getDebugLoc();
6683   SDVTList Tys;
6684   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6685   if (useSSE)
6686     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6687   else
6688     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6689
6690   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6691
6692   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6693   MachineMemOperand *MMO =
6694     DAG.getMachineFunction()
6695     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6696                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6697
6698   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6699   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6700                                            X86ISD::FILD, DL,
6701                                            Tys, Ops, array_lengthof(Ops),
6702                                            SrcVT, MMO);
6703
6704   if (useSSE) {
6705     Chain = Result.getValue(1);
6706     SDValue InFlag = Result.getValue(2);
6707
6708     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6709     // shouldn't be necessary except that RFP cannot be live across
6710     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6711     MachineFunction &MF = DAG.getMachineFunction();
6712     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6713     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6714     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6715     Tys = DAG.getVTList(MVT::Other);
6716     SDValue Ops[] = {
6717       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6718     };
6719     MachineMemOperand *MMO =
6720       DAG.getMachineFunction()
6721       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6722                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6723
6724     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6725                                     Ops, array_lengthof(Ops),
6726                                     Op.getValueType(), MMO);
6727     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6728                          MachinePointerInfo::getFixedStack(SSFI),
6729                          false, false, 0);
6730   }
6731
6732   return Result;
6733 }
6734
6735 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6736 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6737                                                SelectionDAG &DAG) const {
6738   // This algorithm is not obvious. Here it is in C code, more or less:
6739   /*
6740     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6741       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6742       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6743
6744       // Copy ints to xmm registers.
6745       __m128i xh = _mm_cvtsi32_si128( hi );
6746       __m128i xl = _mm_cvtsi32_si128( lo );
6747
6748       // Combine into low half of a single xmm register.
6749       __m128i x = _mm_unpacklo_epi32( xh, xl );
6750       __m128d d;
6751       double sd;
6752
6753       // Merge in appropriate exponents to give the integer bits the right
6754       // magnitude.
6755       x = _mm_unpacklo_epi32( x, exp );
6756
6757       // Subtract away the biases to deal with the IEEE-754 double precision
6758       // implicit 1.
6759       d = _mm_sub_pd( (__m128d) x, bias );
6760
6761       // All conversions up to here are exact. The correctly rounded result is
6762       // calculated using the current rounding mode using the following
6763       // horizontal add.
6764       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6765       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6766                                 // store doesn't really need to be here (except
6767                                 // maybe to zero the other double)
6768       return sd;
6769     }
6770   */
6771
6772   DebugLoc dl = Op.getDebugLoc();
6773   LLVMContext *Context = DAG.getContext();
6774
6775   // Build some magic constants.
6776   std::vector<Constant*> CV0;
6777   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6778   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6779   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6780   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6781   Constant *C0 = ConstantVector::get(CV0);
6782   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6783
6784   std::vector<Constant*> CV1;
6785   CV1.push_back(
6786     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6787   CV1.push_back(
6788     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6789   Constant *C1 = ConstantVector::get(CV1);
6790   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6791
6792   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6793                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6794                                         Op.getOperand(0),
6795                                         DAG.getIntPtrConstant(1)));
6796   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6797                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6798                                         Op.getOperand(0),
6799                                         DAG.getIntPtrConstant(0)));
6800   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6801   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6802                               MachinePointerInfo::getConstantPool(),
6803                               false, false, 16);
6804   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6805   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6806   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6807                               MachinePointerInfo::getConstantPool(),
6808                               false, false, 16);
6809   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6810
6811   // Add the halves; easiest way is to swap them into another reg first.
6812   int ShufMask[2] = { 1, -1 };
6813   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6814                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6815   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6816   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6817                      DAG.getIntPtrConstant(0));
6818 }
6819
6820 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6821 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6822                                                SelectionDAG &DAG) const {
6823   DebugLoc dl = Op.getDebugLoc();
6824   // FP constant to bias correct the final result.
6825   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6826                                    MVT::f64);
6827
6828   // Load the 32-bit value into an XMM register.
6829   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6830                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6831                                          Op.getOperand(0),
6832                                          DAG.getIntPtrConstant(0)));
6833
6834   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6835                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6836                      DAG.getIntPtrConstant(0));
6837
6838   // Or the load with the bias.
6839   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6840                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6841                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6842                                                    MVT::v2f64, Load)),
6843                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6844                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6845                                                    MVT::v2f64, Bias)));
6846   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6847                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6848                    DAG.getIntPtrConstant(0));
6849
6850   // Subtract the bias.
6851   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6852
6853   // Handle final rounding.
6854   EVT DestVT = Op.getValueType();
6855
6856   if (DestVT.bitsLT(MVT::f64)) {
6857     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6858                        DAG.getIntPtrConstant(0));
6859   } else if (DestVT.bitsGT(MVT::f64)) {
6860     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6861   }
6862
6863   // Handle final rounding.
6864   return Sub;
6865 }
6866
6867 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6868                                            SelectionDAG &DAG) const {
6869   SDValue N0 = Op.getOperand(0);
6870   DebugLoc dl = Op.getDebugLoc();
6871
6872   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6873   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6874   // the optimization here.
6875   if (DAG.SignBitIsZero(N0))
6876     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6877
6878   EVT SrcVT = N0.getValueType();
6879   EVT DstVT = Op.getValueType();
6880   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6881     return LowerUINT_TO_FP_i64(Op, DAG);
6882   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6883     return LowerUINT_TO_FP_i32(Op, DAG);
6884
6885   // Make a 64-bit buffer, and use it to build an FILD.
6886   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6887   if (SrcVT == MVT::i32) {
6888     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6889     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6890                                      getPointerTy(), StackSlot, WordOff);
6891     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6892                                   StackSlot, MachinePointerInfo(),
6893                                   false, false, 0);
6894     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6895                                   OffsetSlot, MachinePointerInfo(),
6896                                   false, false, 0);
6897     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6898     return Fild;
6899   }
6900
6901   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6902   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6903                                 StackSlot, MachinePointerInfo(),
6904                                false, false, 0);
6905   // For i64 source, we need to add the appropriate power of 2 if the input
6906   // was negative.  This is the same as the optimization in
6907   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6908   // we must be careful to do the computation in x87 extended precision, not
6909   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6910   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6911   MachineMemOperand *MMO =
6912     DAG.getMachineFunction()
6913     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6914                           MachineMemOperand::MOLoad, 8, 8);
6915
6916   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6917   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6918   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6919                                          MVT::i64, MMO);
6920
6921   APInt FF(32, 0x5F800000ULL);
6922
6923   // Check whether the sign bit is set.
6924   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6925                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6926                                  ISD::SETLT);
6927
6928   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6929   SDValue FudgePtr = DAG.getConstantPool(
6930                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6931                                          getPointerTy());
6932
6933   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6934   SDValue Zero = DAG.getIntPtrConstant(0);
6935   SDValue Four = DAG.getIntPtrConstant(4);
6936   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6937                                Zero, Four);
6938   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6939
6940   // Load the value out, extending it from f32 to f80.
6941   // FIXME: Avoid the extend by constructing the right constant pool?
6942   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6943                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6944                                  MVT::f32, false, false, 4);
6945   // Extend everything to 80 bits to force it to be done on x87.
6946   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6947   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6948 }
6949
6950 std::pair<SDValue,SDValue> X86TargetLowering::
6951 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6952   DebugLoc DL = Op.getDebugLoc();
6953
6954   EVT DstTy = Op.getValueType();
6955
6956   if (!IsSigned) {
6957     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6958     DstTy = MVT::i64;
6959   }
6960
6961   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6962          DstTy.getSimpleVT() >= MVT::i16 &&
6963          "Unknown FP_TO_SINT to lower!");
6964
6965   // These are really Legal.
6966   if (DstTy == MVT::i32 &&
6967       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6968     return std::make_pair(SDValue(), SDValue());
6969   if (Subtarget->is64Bit() &&
6970       DstTy == MVT::i64 &&
6971       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6972     return std::make_pair(SDValue(), SDValue());
6973
6974   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6975   // stack slot.
6976   MachineFunction &MF = DAG.getMachineFunction();
6977   unsigned MemSize = DstTy.getSizeInBits()/8;
6978   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6979   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6980
6981
6982
6983   unsigned Opc;
6984   switch (DstTy.getSimpleVT().SimpleTy) {
6985   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6986   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6987   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6988   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6989   }
6990
6991   SDValue Chain = DAG.getEntryNode();
6992   SDValue Value = Op.getOperand(0);
6993   EVT TheVT = Op.getOperand(0).getValueType();
6994   if (isScalarFPTypeInSSEReg(TheVT)) {
6995     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6996     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6997                          MachinePointerInfo::getFixedStack(SSFI),
6998                          false, false, 0);
6999     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7000     SDValue Ops[] = {
7001       Chain, StackSlot, DAG.getValueType(TheVT)
7002     };
7003
7004     MachineMemOperand *MMO =
7005       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7006                               MachineMemOperand::MOLoad, MemSize, MemSize);
7007     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7008                                     DstTy, MMO);
7009     Chain = Value.getValue(1);
7010     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7011     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7012   }
7013
7014   MachineMemOperand *MMO =
7015     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7016                             MachineMemOperand::MOStore, MemSize, MemSize);
7017
7018   // Build the FP_TO_INT*_IN_MEM
7019   SDValue Ops[] = { Chain, Value, StackSlot };
7020   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7021                                          Ops, 3, DstTy, MMO);
7022
7023   return std::make_pair(FIST, StackSlot);
7024 }
7025
7026 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7027                                            SelectionDAG &DAG) const {
7028   if (Op.getValueType().isVector())
7029     return SDValue();
7030
7031   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7032   SDValue FIST = Vals.first, StackSlot = Vals.second;
7033   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7034   if (FIST.getNode() == 0) return Op;
7035
7036   // Load the result.
7037   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7038                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7039 }
7040
7041 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7042                                            SelectionDAG &DAG) const {
7043   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7044   SDValue FIST = Vals.first, StackSlot = Vals.second;
7045   assert(FIST.getNode() && "Unexpected failure");
7046
7047   // Load the result.
7048   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7049                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7050 }
7051
7052 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7053                                      SelectionDAG &DAG) const {
7054   LLVMContext *Context = DAG.getContext();
7055   DebugLoc dl = Op.getDebugLoc();
7056   EVT VT = Op.getValueType();
7057   EVT EltVT = VT;
7058   if (VT.isVector())
7059     EltVT = VT.getVectorElementType();
7060   std::vector<Constant*> CV;
7061   if (EltVT == MVT::f64) {
7062     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7063     CV.push_back(C);
7064     CV.push_back(C);
7065   } else {
7066     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7067     CV.push_back(C);
7068     CV.push_back(C);
7069     CV.push_back(C);
7070     CV.push_back(C);
7071   }
7072   Constant *C = ConstantVector::get(CV);
7073   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7074   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7075                              MachinePointerInfo::getConstantPool(),
7076                              false, false, 16);
7077   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7078 }
7079
7080 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7081   LLVMContext *Context = DAG.getContext();
7082   DebugLoc dl = Op.getDebugLoc();
7083   EVT VT = Op.getValueType();
7084   EVT EltVT = VT;
7085   if (VT.isVector())
7086     EltVT = VT.getVectorElementType();
7087   std::vector<Constant*> CV;
7088   if (EltVT == MVT::f64) {
7089     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7090     CV.push_back(C);
7091     CV.push_back(C);
7092   } else {
7093     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7094     CV.push_back(C);
7095     CV.push_back(C);
7096     CV.push_back(C);
7097     CV.push_back(C);
7098   }
7099   Constant *C = ConstantVector::get(CV);
7100   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7101   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7102                              MachinePointerInfo::getConstantPool(),
7103                              false, false, 16);
7104   if (VT.isVector()) {
7105     return DAG.getNode(ISD::BITCAST, dl, VT,
7106                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7107                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7108                                 Op.getOperand(0)),
7109                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7110   } else {
7111     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7112   }
7113 }
7114
7115 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7116   LLVMContext *Context = DAG.getContext();
7117   SDValue Op0 = Op.getOperand(0);
7118   SDValue Op1 = Op.getOperand(1);
7119   DebugLoc dl = Op.getDebugLoc();
7120   EVT VT = Op.getValueType();
7121   EVT SrcVT = Op1.getValueType();
7122
7123   // If second operand is smaller, extend it first.
7124   if (SrcVT.bitsLT(VT)) {
7125     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7126     SrcVT = VT;
7127   }
7128   // And if it is bigger, shrink it first.
7129   if (SrcVT.bitsGT(VT)) {
7130     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7131     SrcVT = VT;
7132   }
7133
7134   // At this point the operands and the result should have the same
7135   // type, and that won't be f80 since that is not custom lowered.
7136
7137   // First get the sign bit of second operand.
7138   std::vector<Constant*> CV;
7139   if (SrcVT == MVT::f64) {
7140     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7141     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7142   } else {
7143     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7144     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7145     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7146     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7147   }
7148   Constant *C = ConstantVector::get(CV);
7149   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7150   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7151                               MachinePointerInfo::getConstantPool(),
7152                               false, false, 16);
7153   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7154
7155   // Shift sign bit right or left if the two operands have different types.
7156   if (SrcVT.bitsGT(VT)) {
7157     // Op0 is MVT::f32, Op1 is MVT::f64.
7158     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7159     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7160                           DAG.getConstant(32, MVT::i32));
7161     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7162     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7163                           DAG.getIntPtrConstant(0));
7164   }
7165
7166   // Clear first operand sign bit.
7167   CV.clear();
7168   if (VT == MVT::f64) {
7169     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7170     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7171   } else {
7172     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7173     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7174     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7175     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7176   }
7177   C = ConstantVector::get(CV);
7178   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7179   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7180                               MachinePointerInfo::getConstantPool(),
7181                               false, false, 16);
7182   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7183
7184   // Or the value with the sign bit.
7185   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7186 }
7187
7188 /// Emit nodes that will be selected as "test Op0,Op0", or something
7189 /// equivalent.
7190 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7191                                     SelectionDAG &DAG) const {
7192   DebugLoc dl = Op.getDebugLoc();
7193
7194   // CF and OF aren't always set the way we want. Determine which
7195   // of these we need.
7196   bool NeedCF = false;
7197   bool NeedOF = false;
7198   switch (X86CC) {
7199   default: break;
7200   case X86::COND_A: case X86::COND_AE:
7201   case X86::COND_B: case X86::COND_BE:
7202     NeedCF = true;
7203     break;
7204   case X86::COND_G: case X86::COND_GE:
7205   case X86::COND_L: case X86::COND_LE:
7206   case X86::COND_O: case X86::COND_NO:
7207     NeedOF = true;
7208     break;
7209   }
7210
7211   // See if we can use the EFLAGS value from the operand instead of
7212   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7213   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7214   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7215     // Emit a CMP with 0, which is the TEST pattern.
7216     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7217                        DAG.getConstant(0, Op.getValueType()));
7218
7219   unsigned Opcode = 0;
7220   unsigned NumOperands = 0;
7221   switch (Op.getNode()->getOpcode()) {
7222   case ISD::ADD:
7223     // Due to an isel shortcoming, be conservative if this add is likely to be
7224     // selected as part of a load-modify-store instruction. When the root node
7225     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7226     // uses of other nodes in the match, such as the ADD in this case. This
7227     // leads to the ADD being left around and reselected, with the result being
7228     // two adds in the output.  Alas, even if none our users are stores, that
7229     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7230     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7231     // climbing the DAG back to the root, and it doesn't seem to be worth the
7232     // effort.
7233     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7234            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7235       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7236         goto default_case;
7237
7238     if (ConstantSDNode *C =
7239         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7240       // An add of one will be selected as an INC.
7241       if (C->getAPIntValue() == 1) {
7242         Opcode = X86ISD::INC;
7243         NumOperands = 1;
7244         break;
7245       }
7246
7247       // An add of negative one (subtract of one) will be selected as a DEC.
7248       if (C->getAPIntValue().isAllOnesValue()) {
7249         Opcode = X86ISD::DEC;
7250         NumOperands = 1;
7251         break;
7252       }
7253     }
7254
7255     // Otherwise use a regular EFLAGS-setting add.
7256     Opcode = X86ISD::ADD;
7257     NumOperands = 2;
7258     break;
7259   case ISD::AND: {
7260     // If the primary and result isn't used, don't bother using X86ISD::AND,
7261     // because a TEST instruction will be better.
7262     bool NonFlagUse = false;
7263     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7264            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7265       SDNode *User = *UI;
7266       unsigned UOpNo = UI.getOperandNo();
7267       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7268         // Look pass truncate.
7269         UOpNo = User->use_begin().getOperandNo();
7270         User = *User->use_begin();
7271       }
7272
7273       if (User->getOpcode() != ISD::BRCOND &&
7274           User->getOpcode() != ISD::SETCC &&
7275           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7276         NonFlagUse = true;
7277         break;
7278       }
7279     }
7280
7281     if (!NonFlagUse)
7282       break;
7283   }
7284     // FALL THROUGH
7285   case ISD::SUB:
7286   case ISD::OR:
7287   case ISD::XOR:
7288     // Due to the ISEL shortcoming noted above, be conservative if this op is
7289     // likely to be selected as part of a load-modify-store instruction.
7290     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7291            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7292       if (UI->getOpcode() == ISD::STORE)
7293         goto default_case;
7294
7295     // Otherwise use a regular EFLAGS-setting instruction.
7296     switch (Op.getNode()->getOpcode()) {
7297     default: llvm_unreachable("unexpected operator!");
7298     case ISD::SUB: Opcode = X86ISD::SUB; break;
7299     case ISD::OR:  Opcode = X86ISD::OR;  break;
7300     case ISD::XOR: Opcode = X86ISD::XOR; break;
7301     case ISD::AND: Opcode = X86ISD::AND; break;
7302     }
7303
7304     NumOperands = 2;
7305     break;
7306   case X86ISD::ADD:
7307   case X86ISD::SUB:
7308   case X86ISD::INC:
7309   case X86ISD::DEC:
7310   case X86ISD::OR:
7311   case X86ISD::XOR:
7312   case X86ISD::AND:
7313     return SDValue(Op.getNode(), 1);
7314   default:
7315   default_case:
7316     break;
7317   }
7318
7319   if (Opcode == 0)
7320     // Emit a CMP with 0, which is the TEST pattern.
7321     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7322                        DAG.getConstant(0, Op.getValueType()));
7323
7324   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7325   SmallVector<SDValue, 4> Ops;
7326   for (unsigned i = 0; i != NumOperands; ++i)
7327     Ops.push_back(Op.getOperand(i));
7328
7329   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7330   DAG.ReplaceAllUsesWith(Op, New);
7331   return SDValue(New.getNode(), 1);
7332 }
7333
7334 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7335 /// equivalent.
7336 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7337                                    SelectionDAG &DAG) const {
7338   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7339     if (C->getAPIntValue() == 0)
7340       return EmitTest(Op0, X86CC, DAG);
7341
7342   DebugLoc dl = Op0.getDebugLoc();
7343   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7344 }
7345
7346 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7347 /// if it's possible.
7348 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7349                                      DebugLoc dl, SelectionDAG &DAG) const {
7350   SDValue Op0 = And.getOperand(0);
7351   SDValue Op1 = And.getOperand(1);
7352   if (Op0.getOpcode() == ISD::TRUNCATE)
7353     Op0 = Op0.getOperand(0);
7354   if (Op1.getOpcode() == ISD::TRUNCATE)
7355     Op1 = Op1.getOperand(0);
7356
7357   SDValue LHS, RHS;
7358   if (Op1.getOpcode() == ISD::SHL)
7359     std::swap(Op0, Op1);
7360   if (Op0.getOpcode() == ISD::SHL) {
7361     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7362       if (And00C->getZExtValue() == 1) {
7363         // If we looked past a truncate, check that it's only truncating away
7364         // known zeros.
7365         unsigned BitWidth = Op0.getValueSizeInBits();
7366         unsigned AndBitWidth = And.getValueSizeInBits();
7367         if (BitWidth > AndBitWidth) {
7368           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7369           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7370           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7371             return SDValue();
7372         }
7373         LHS = Op1;
7374         RHS = Op0.getOperand(1);
7375       }
7376   } else if (Op1.getOpcode() == ISD::Constant) {
7377     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7378     SDValue AndLHS = Op0;
7379     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7380       LHS = AndLHS.getOperand(0);
7381       RHS = AndLHS.getOperand(1);
7382     }
7383   }
7384
7385   if (LHS.getNode()) {
7386     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7387     // instruction.  Since the shift amount is in-range-or-undefined, we know
7388     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7389     // the encoding for the i16 version is larger than the i32 version.
7390     // Also promote i16 to i32 for performance / code size reason.
7391     if (LHS.getValueType() == MVT::i8 ||
7392         LHS.getValueType() == MVT::i16)
7393       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7394
7395     // If the operand types disagree, extend the shift amount to match.  Since
7396     // BT ignores high bits (like shifts) we can use anyextend.
7397     if (LHS.getValueType() != RHS.getValueType())
7398       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7399
7400     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7401     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7402     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7403                        DAG.getConstant(Cond, MVT::i8), BT);
7404   }
7405
7406   return SDValue();
7407 }
7408
7409 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7410   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7411   SDValue Op0 = Op.getOperand(0);
7412   SDValue Op1 = Op.getOperand(1);
7413   DebugLoc dl = Op.getDebugLoc();
7414   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7415
7416   // Optimize to BT if possible.
7417   // Lower (X & (1 << N)) == 0 to BT(X, N).
7418   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7419   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7420   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7421       Op1.getOpcode() == ISD::Constant &&
7422       cast<ConstantSDNode>(Op1)->isNullValue() &&
7423       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7424     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7425     if (NewSetCC.getNode())
7426       return NewSetCC;
7427   }
7428
7429   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7430   // these.
7431   if (Op1.getOpcode() == ISD::Constant &&
7432       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7433        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7434       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7435
7436     // If the input is a setcc, then reuse the input setcc or use a new one with
7437     // the inverted condition.
7438     if (Op0.getOpcode() == X86ISD::SETCC) {
7439       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7440       bool Invert = (CC == ISD::SETNE) ^
7441         cast<ConstantSDNode>(Op1)->isNullValue();
7442       if (!Invert) return Op0;
7443
7444       CCode = X86::GetOppositeBranchCondition(CCode);
7445       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7446                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7447     }
7448   }
7449
7450   bool isFP = Op1.getValueType().isFloatingPoint();
7451   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7452   if (X86CC == X86::COND_INVALID)
7453     return SDValue();
7454
7455   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7456   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7457                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7458 }
7459
7460 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7461   SDValue Cond;
7462   SDValue Op0 = Op.getOperand(0);
7463   SDValue Op1 = Op.getOperand(1);
7464   SDValue CC = Op.getOperand(2);
7465   EVT VT = Op.getValueType();
7466   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7467   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7468   DebugLoc dl = Op.getDebugLoc();
7469
7470   if (isFP) {
7471     unsigned SSECC = 8;
7472     EVT VT0 = Op0.getValueType();
7473     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7474     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7475     bool Swap = false;
7476
7477     switch (SetCCOpcode) {
7478     default: break;
7479     case ISD::SETOEQ:
7480     case ISD::SETEQ:  SSECC = 0; break;
7481     case ISD::SETOGT:
7482     case ISD::SETGT: Swap = true; // Fallthrough
7483     case ISD::SETLT:
7484     case ISD::SETOLT: SSECC = 1; break;
7485     case ISD::SETOGE:
7486     case ISD::SETGE: Swap = true; // Fallthrough
7487     case ISD::SETLE:
7488     case ISD::SETOLE: SSECC = 2; break;
7489     case ISD::SETUO:  SSECC = 3; break;
7490     case ISD::SETUNE:
7491     case ISD::SETNE:  SSECC = 4; break;
7492     case ISD::SETULE: Swap = true;
7493     case ISD::SETUGE: SSECC = 5; break;
7494     case ISD::SETULT: Swap = true;
7495     case ISD::SETUGT: SSECC = 6; break;
7496     case ISD::SETO:   SSECC = 7; break;
7497     }
7498     if (Swap)
7499       std::swap(Op0, Op1);
7500
7501     // In the two special cases we can't handle, emit two comparisons.
7502     if (SSECC == 8) {
7503       if (SetCCOpcode == ISD::SETUEQ) {
7504         SDValue UNORD, EQ;
7505         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7506         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7507         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7508       }
7509       else if (SetCCOpcode == ISD::SETONE) {
7510         SDValue ORD, NEQ;
7511         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7512         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7513         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7514       }
7515       llvm_unreachable("Illegal FP comparison");
7516     }
7517     // Handle all other FP comparisons here.
7518     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7519   }
7520
7521   // We are handling one of the integer comparisons here.  Since SSE only has
7522   // GT and EQ comparisons for integer, swapping operands and multiple
7523   // operations may be required for some comparisons.
7524   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7525   bool Swap = false, Invert = false, FlipSigns = false;
7526
7527   switch (VT.getSimpleVT().SimpleTy) {
7528   default: break;
7529   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7530   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7531   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7532   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7533   }
7534
7535   switch (SetCCOpcode) {
7536   default: break;
7537   case ISD::SETNE:  Invert = true;
7538   case ISD::SETEQ:  Opc = EQOpc; break;
7539   case ISD::SETLT:  Swap = true;
7540   case ISD::SETGT:  Opc = GTOpc; break;
7541   case ISD::SETGE:  Swap = true;
7542   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7543   case ISD::SETULT: Swap = true;
7544   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7545   case ISD::SETUGE: Swap = true;
7546   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7547   }
7548   if (Swap)
7549     std::swap(Op0, Op1);
7550
7551   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7552   // bits of the inputs before performing those operations.
7553   if (FlipSigns) {
7554     EVT EltVT = VT.getVectorElementType();
7555     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7556                                       EltVT);
7557     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7558     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7559                                     SignBits.size());
7560     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7561     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7562   }
7563
7564   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7565
7566   // If the logical-not of the result is required, perform that now.
7567   if (Invert)
7568     Result = DAG.getNOT(dl, Result, VT);
7569
7570   return Result;
7571 }
7572
7573 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7574 static bool isX86LogicalCmp(SDValue Op) {
7575   unsigned Opc = Op.getNode()->getOpcode();
7576   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7577     return true;
7578   if (Op.getResNo() == 1 &&
7579       (Opc == X86ISD::ADD ||
7580        Opc == X86ISD::SUB ||
7581        Opc == X86ISD::ADC ||
7582        Opc == X86ISD::SBB ||
7583        Opc == X86ISD::SMUL ||
7584        Opc == X86ISD::UMUL ||
7585        Opc == X86ISD::INC ||
7586        Opc == X86ISD::DEC ||
7587        Opc == X86ISD::OR ||
7588        Opc == X86ISD::XOR ||
7589        Opc == X86ISD::AND))
7590     return true;
7591
7592   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7593     return true;
7594
7595   return false;
7596 }
7597
7598 static bool isZero(SDValue V) {
7599   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7600   return C && C->isNullValue();
7601 }
7602
7603 static bool isAllOnes(SDValue V) {
7604   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7605   return C && C->isAllOnesValue();
7606 }
7607
7608 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7609   bool addTest = true;
7610   SDValue Cond  = Op.getOperand(0);
7611   SDValue Op1 = Op.getOperand(1);
7612   SDValue Op2 = Op.getOperand(2);
7613   DebugLoc DL = Op.getDebugLoc();
7614   SDValue CC;
7615
7616   if (Cond.getOpcode() == ISD::SETCC) {
7617     SDValue NewCond = LowerSETCC(Cond, DAG);
7618     if (NewCond.getNode())
7619       Cond = NewCond;
7620   }
7621
7622   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7623   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7624   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7625   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7626   if (Cond.getOpcode() == X86ISD::SETCC &&
7627       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7628       isZero(Cond.getOperand(1).getOperand(1))) {
7629     SDValue Cmp = Cond.getOperand(1);
7630
7631     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7632
7633     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7634         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7635       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7636
7637       SDValue CmpOp0 = Cmp.getOperand(0);
7638       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7639                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7640
7641       SDValue Res =   // Res = 0 or -1.
7642         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7643                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7644
7645       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7646         Res = DAG.getNOT(DL, Res, Res.getValueType());
7647
7648       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7649       if (N2C == 0 || !N2C->isNullValue())
7650         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7651       return Res;
7652     }
7653   }
7654
7655   // Look past (and (setcc_carry (cmp ...)), 1).
7656   if (Cond.getOpcode() == ISD::AND &&
7657       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7658     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7659     if (C && C->getAPIntValue() == 1)
7660       Cond = Cond.getOperand(0);
7661   }
7662
7663   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7664   // setting operand in place of the X86ISD::SETCC.
7665   if (Cond.getOpcode() == X86ISD::SETCC ||
7666       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7667     CC = Cond.getOperand(0);
7668
7669     SDValue Cmp = Cond.getOperand(1);
7670     unsigned Opc = Cmp.getOpcode();
7671     EVT VT = Op.getValueType();
7672
7673     bool IllegalFPCMov = false;
7674     if (VT.isFloatingPoint() && !VT.isVector() &&
7675         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7676       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7677
7678     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7679         Opc == X86ISD::BT) { // FIXME
7680       Cond = Cmp;
7681       addTest = false;
7682     }
7683   }
7684
7685   if (addTest) {
7686     // Look pass the truncate.
7687     if (Cond.getOpcode() == ISD::TRUNCATE)
7688       Cond = Cond.getOperand(0);
7689
7690     // We know the result of AND is compared against zero. Try to match
7691     // it to BT.
7692     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7693       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7694       if (NewSetCC.getNode()) {
7695         CC = NewSetCC.getOperand(0);
7696         Cond = NewSetCC.getOperand(1);
7697         addTest = false;
7698       }
7699     }
7700   }
7701
7702   if (addTest) {
7703     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7704     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7705   }
7706
7707   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7708   // a <  b ?  0 : -1 -> RES = setcc_carry
7709   // a >= b ? -1 :  0 -> RES = setcc_carry
7710   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7711   if (Cond.getOpcode() == X86ISD::CMP) {
7712     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7713
7714     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7715         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7716       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7717                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7718       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7719         return DAG.getNOT(DL, Res, Res.getValueType());
7720       return Res;
7721     }
7722   }
7723
7724   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7725   // condition is true.
7726   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7727   SDValue Ops[] = { Op2, Op1, CC, Cond };
7728   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7729 }
7730
7731 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7732 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7733 // from the AND / OR.
7734 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7735   Opc = Op.getOpcode();
7736   if (Opc != ISD::OR && Opc != ISD::AND)
7737     return false;
7738   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7739           Op.getOperand(0).hasOneUse() &&
7740           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7741           Op.getOperand(1).hasOneUse());
7742 }
7743
7744 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7745 // 1 and that the SETCC node has a single use.
7746 static bool isXor1OfSetCC(SDValue Op) {
7747   if (Op.getOpcode() != ISD::XOR)
7748     return false;
7749   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7750   if (N1C && N1C->getAPIntValue() == 1) {
7751     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7752       Op.getOperand(0).hasOneUse();
7753   }
7754   return false;
7755 }
7756
7757 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7758   bool addTest = true;
7759   SDValue Chain = Op.getOperand(0);
7760   SDValue Cond  = Op.getOperand(1);
7761   SDValue Dest  = Op.getOperand(2);
7762   DebugLoc dl = Op.getDebugLoc();
7763   SDValue CC;
7764
7765   if (Cond.getOpcode() == ISD::SETCC) {
7766     SDValue NewCond = LowerSETCC(Cond, DAG);
7767     if (NewCond.getNode())
7768       Cond = NewCond;
7769   }
7770 #if 0
7771   // FIXME: LowerXALUO doesn't handle these!!
7772   else if (Cond.getOpcode() == X86ISD::ADD  ||
7773            Cond.getOpcode() == X86ISD::SUB  ||
7774            Cond.getOpcode() == X86ISD::SMUL ||
7775            Cond.getOpcode() == X86ISD::UMUL)
7776     Cond = LowerXALUO(Cond, DAG);
7777 #endif
7778
7779   // Look pass (and (setcc_carry (cmp ...)), 1).
7780   if (Cond.getOpcode() == ISD::AND &&
7781       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7782     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7783     if (C && C->getAPIntValue() == 1)
7784       Cond = Cond.getOperand(0);
7785   }
7786
7787   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7788   // setting operand in place of the X86ISD::SETCC.
7789   if (Cond.getOpcode() == X86ISD::SETCC ||
7790       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7791     CC = Cond.getOperand(0);
7792
7793     SDValue Cmp = Cond.getOperand(1);
7794     unsigned Opc = Cmp.getOpcode();
7795     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7796     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7797       Cond = Cmp;
7798       addTest = false;
7799     } else {
7800       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7801       default: break;
7802       case X86::COND_O:
7803       case X86::COND_B:
7804         // These can only come from an arithmetic instruction with overflow,
7805         // e.g. SADDO, UADDO.
7806         Cond = Cond.getNode()->getOperand(1);
7807         addTest = false;
7808         break;
7809       }
7810     }
7811   } else {
7812     unsigned CondOpc;
7813     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7814       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7815       if (CondOpc == ISD::OR) {
7816         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7817         // two branches instead of an explicit OR instruction with a
7818         // separate test.
7819         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7820             isX86LogicalCmp(Cmp)) {
7821           CC = Cond.getOperand(0).getOperand(0);
7822           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7823                               Chain, Dest, CC, Cmp);
7824           CC = Cond.getOperand(1).getOperand(0);
7825           Cond = Cmp;
7826           addTest = false;
7827         }
7828       } else { // ISD::AND
7829         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7830         // two branches instead of an explicit AND instruction with a
7831         // separate test. However, we only do this if this block doesn't
7832         // have a fall-through edge, because this requires an explicit
7833         // jmp when the condition is false.
7834         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7835             isX86LogicalCmp(Cmp) &&
7836             Op.getNode()->hasOneUse()) {
7837           X86::CondCode CCode =
7838             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7839           CCode = X86::GetOppositeBranchCondition(CCode);
7840           CC = DAG.getConstant(CCode, MVT::i8);
7841           SDNode *User = *Op.getNode()->use_begin();
7842           // Look for an unconditional branch following this conditional branch.
7843           // We need this because we need to reverse the successors in order
7844           // to implement FCMP_OEQ.
7845           if (User->getOpcode() == ISD::BR) {
7846             SDValue FalseBB = User->getOperand(1);
7847             SDNode *NewBR =
7848               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7849             assert(NewBR == User);
7850             (void)NewBR;
7851             Dest = FalseBB;
7852
7853             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7854                                 Chain, Dest, CC, Cmp);
7855             X86::CondCode CCode =
7856               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7857             CCode = X86::GetOppositeBranchCondition(CCode);
7858             CC = DAG.getConstant(CCode, MVT::i8);
7859             Cond = Cmp;
7860             addTest = false;
7861           }
7862         }
7863       }
7864     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7865       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7866       // It should be transformed during dag combiner except when the condition
7867       // is set by a arithmetics with overflow node.
7868       X86::CondCode CCode =
7869         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7870       CCode = X86::GetOppositeBranchCondition(CCode);
7871       CC = DAG.getConstant(CCode, MVT::i8);
7872       Cond = Cond.getOperand(0).getOperand(1);
7873       addTest = false;
7874     }
7875   }
7876
7877   if (addTest) {
7878     // Look pass the truncate.
7879     if (Cond.getOpcode() == ISD::TRUNCATE)
7880       Cond = Cond.getOperand(0);
7881
7882     // We know the result of AND is compared against zero. Try to match
7883     // it to BT.
7884     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7885       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7886       if (NewSetCC.getNode()) {
7887         CC = NewSetCC.getOperand(0);
7888         Cond = NewSetCC.getOperand(1);
7889         addTest = false;
7890       }
7891     }
7892   }
7893
7894   if (addTest) {
7895     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7896     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7897   }
7898   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7899                      Chain, Dest, CC, Cond);
7900 }
7901
7902
7903 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7904 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7905 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7906 // that the guard pages used by the OS virtual memory manager are allocated in
7907 // correct sequence.
7908 SDValue
7909 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7910                                            SelectionDAG &DAG) const {
7911   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7912          "This should be used only on Windows targets");
7913   DebugLoc dl = Op.getDebugLoc();
7914
7915   // Get the inputs.
7916   SDValue Chain = Op.getOperand(0);
7917   SDValue Size  = Op.getOperand(1);
7918   // FIXME: Ensure alignment here
7919
7920   SDValue Flag;
7921
7922   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7923
7924   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7925   Flag = Chain.getValue(1);
7926
7927   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7928
7929   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7930   Flag = Chain.getValue(1);
7931
7932   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7933
7934   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7935   return DAG.getMergeValues(Ops1, 2, dl);
7936 }
7937
7938 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7939   MachineFunction &MF = DAG.getMachineFunction();
7940   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7941
7942   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7943   DebugLoc DL = Op.getDebugLoc();
7944
7945   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7946     // vastart just stores the address of the VarArgsFrameIndex slot into the
7947     // memory location argument.
7948     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7949                                    getPointerTy());
7950     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7951                         MachinePointerInfo(SV), false, false, 0);
7952   }
7953
7954   // __va_list_tag:
7955   //   gp_offset         (0 - 6 * 8)
7956   //   fp_offset         (48 - 48 + 8 * 16)
7957   //   overflow_arg_area (point to parameters coming in memory).
7958   //   reg_save_area
7959   SmallVector<SDValue, 8> MemOps;
7960   SDValue FIN = Op.getOperand(1);
7961   // Store gp_offset
7962   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7963                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7964                                                MVT::i32),
7965                                FIN, MachinePointerInfo(SV), false, false, 0);
7966   MemOps.push_back(Store);
7967
7968   // Store fp_offset
7969   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7970                     FIN, DAG.getIntPtrConstant(4));
7971   Store = DAG.getStore(Op.getOperand(0), DL,
7972                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7973                                        MVT::i32),
7974                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7975   MemOps.push_back(Store);
7976
7977   // Store ptr to overflow_arg_area
7978   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7979                     FIN, DAG.getIntPtrConstant(4));
7980   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7981                                     getPointerTy());
7982   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7983                        MachinePointerInfo(SV, 8),
7984                        false, false, 0);
7985   MemOps.push_back(Store);
7986
7987   // Store ptr to reg_save_area.
7988   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7989                     FIN, DAG.getIntPtrConstant(8));
7990   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7991                                     getPointerTy());
7992   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7993                        MachinePointerInfo(SV, 16), false, false, 0);
7994   MemOps.push_back(Store);
7995   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7996                      &MemOps[0], MemOps.size());
7997 }
7998
7999 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8000   assert(Subtarget->is64Bit() &&
8001          "LowerVAARG only handles 64-bit va_arg!");
8002   assert((Subtarget->isTargetLinux() ||
8003           Subtarget->isTargetDarwin()) &&
8004           "Unhandled target in LowerVAARG");
8005   assert(Op.getNode()->getNumOperands() == 4);
8006   SDValue Chain = Op.getOperand(0);
8007   SDValue SrcPtr = Op.getOperand(1);
8008   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8009   unsigned Align = Op.getConstantOperandVal(3);
8010   DebugLoc dl = Op.getDebugLoc();
8011
8012   EVT ArgVT = Op.getNode()->getValueType(0);
8013   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8014   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8015   uint8_t ArgMode;
8016
8017   // Decide which area this value should be read from.
8018   // TODO: Implement the AMD64 ABI in its entirety. This simple
8019   // selection mechanism works only for the basic types.
8020   if (ArgVT == MVT::f80) {
8021     llvm_unreachable("va_arg for f80 not yet implemented");
8022   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8023     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8024   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8025     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8026   } else {
8027     llvm_unreachable("Unhandled argument type in LowerVAARG");
8028   }
8029
8030   if (ArgMode == 2) {
8031     // Sanity Check: Make sure using fp_offset makes sense.
8032     assert(!UseSoftFloat &&
8033            !(DAG.getMachineFunction()
8034                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8035            Subtarget->hasXMM());
8036   }
8037
8038   // Insert VAARG_64 node into the DAG
8039   // VAARG_64 returns two values: Variable Argument Address, Chain
8040   SmallVector<SDValue, 11> InstOps;
8041   InstOps.push_back(Chain);
8042   InstOps.push_back(SrcPtr);
8043   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8044   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8045   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8046   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8047   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8048                                           VTs, &InstOps[0], InstOps.size(),
8049                                           MVT::i64,
8050                                           MachinePointerInfo(SV),
8051                                           /*Align=*/0,
8052                                           /*Volatile=*/false,
8053                                           /*ReadMem=*/true,
8054                                           /*WriteMem=*/true);
8055   Chain = VAARG.getValue(1);
8056
8057   // Load the next argument and return it
8058   return DAG.getLoad(ArgVT, dl,
8059                      Chain,
8060                      VAARG,
8061                      MachinePointerInfo(),
8062                      false, false, 0);
8063 }
8064
8065 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8066   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8067   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8068   SDValue Chain = Op.getOperand(0);
8069   SDValue DstPtr = Op.getOperand(1);
8070   SDValue SrcPtr = Op.getOperand(2);
8071   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8072   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8073   DebugLoc DL = Op.getDebugLoc();
8074
8075   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8076                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8077                        false,
8078                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8079 }
8080
8081 SDValue
8082 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8083   DebugLoc dl = Op.getDebugLoc();
8084   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8085   switch (IntNo) {
8086   default: return SDValue();    // Don't custom lower most intrinsics.
8087   // Comparison intrinsics.
8088   case Intrinsic::x86_sse_comieq_ss:
8089   case Intrinsic::x86_sse_comilt_ss:
8090   case Intrinsic::x86_sse_comile_ss:
8091   case Intrinsic::x86_sse_comigt_ss:
8092   case Intrinsic::x86_sse_comige_ss:
8093   case Intrinsic::x86_sse_comineq_ss:
8094   case Intrinsic::x86_sse_ucomieq_ss:
8095   case Intrinsic::x86_sse_ucomilt_ss:
8096   case Intrinsic::x86_sse_ucomile_ss:
8097   case Intrinsic::x86_sse_ucomigt_ss:
8098   case Intrinsic::x86_sse_ucomige_ss:
8099   case Intrinsic::x86_sse_ucomineq_ss:
8100   case Intrinsic::x86_sse2_comieq_sd:
8101   case Intrinsic::x86_sse2_comilt_sd:
8102   case Intrinsic::x86_sse2_comile_sd:
8103   case Intrinsic::x86_sse2_comigt_sd:
8104   case Intrinsic::x86_sse2_comige_sd:
8105   case Intrinsic::x86_sse2_comineq_sd:
8106   case Intrinsic::x86_sse2_ucomieq_sd:
8107   case Intrinsic::x86_sse2_ucomilt_sd:
8108   case Intrinsic::x86_sse2_ucomile_sd:
8109   case Intrinsic::x86_sse2_ucomigt_sd:
8110   case Intrinsic::x86_sse2_ucomige_sd:
8111   case Intrinsic::x86_sse2_ucomineq_sd: {
8112     unsigned Opc = 0;
8113     ISD::CondCode CC = ISD::SETCC_INVALID;
8114     switch (IntNo) {
8115     default: break;
8116     case Intrinsic::x86_sse_comieq_ss:
8117     case Intrinsic::x86_sse2_comieq_sd:
8118       Opc = X86ISD::COMI;
8119       CC = ISD::SETEQ;
8120       break;
8121     case Intrinsic::x86_sse_comilt_ss:
8122     case Intrinsic::x86_sse2_comilt_sd:
8123       Opc = X86ISD::COMI;
8124       CC = ISD::SETLT;
8125       break;
8126     case Intrinsic::x86_sse_comile_ss:
8127     case Intrinsic::x86_sse2_comile_sd:
8128       Opc = X86ISD::COMI;
8129       CC = ISD::SETLE;
8130       break;
8131     case Intrinsic::x86_sse_comigt_ss:
8132     case Intrinsic::x86_sse2_comigt_sd:
8133       Opc = X86ISD::COMI;
8134       CC = ISD::SETGT;
8135       break;
8136     case Intrinsic::x86_sse_comige_ss:
8137     case Intrinsic::x86_sse2_comige_sd:
8138       Opc = X86ISD::COMI;
8139       CC = ISD::SETGE;
8140       break;
8141     case Intrinsic::x86_sse_comineq_ss:
8142     case Intrinsic::x86_sse2_comineq_sd:
8143       Opc = X86ISD::COMI;
8144       CC = ISD::SETNE;
8145       break;
8146     case Intrinsic::x86_sse_ucomieq_ss:
8147     case Intrinsic::x86_sse2_ucomieq_sd:
8148       Opc = X86ISD::UCOMI;
8149       CC = ISD::SETEQ;
8150       break;
8151     case Intrinsic::x86_sse_ucomilt_ss:
8152     case Intrinsic::x86_sse2_ucomilt_sd:
8153       Opc = X86ISD::UCOMI;
8154       CC = ISD::SETLT;
8155       break;
8156     case Intrinsic::x86_sse_ucomile_ss:
8157     case Intrinsic::x86_sse2_ucomile_sd:
8158       Opc = X86ISD::UCOMI;
8159       CC = ISD::SETLE;
8160       break;
8161     case Intrinsic::x86_sse_ucomigt_ss:
8162     case Intrinsic::x86_sse2_ucomigt_sd:
8163       Opc = X86ISD::UCOMI;
8164       CC = ISD::SETGT;
8165       break;
8166     case Intrinsic::x86_sse_ucomige_ss:
8167     case Intrinsic::x86_sse2_ucomige_sd:
8168       Opc = X86ISD::UCOMI;
8169       CC = ISD::SETGE;
8170       break;
8171     case Intrinsic::x86_sse_ucomineq_ss:
8172     case Intrinsic::x86_sse2_ucomineq_sd:
8173       Opc = X86ISD::UCOMI;
8174       CC = ISD::SETNE;
8175       break;
8176     }
8177
8178     SDValue LHS = Op.getOperand(1);
8179     SDValue RHS = Op.getOperand(2);
8180     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8181     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8182     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8183     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8184                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8185     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8186   }
8187   // ptest and testp intrinsics. The intrinsic these come from are designed to
8188   // return an integer value, not just an instruction so lower it to the ptest
8189   // or testp pattern and a setcc for the result.
8190   case Intrinsic::x86_sse41_ptestz:
8191   case Intrinsic::x86_sse41_ptestc:
8192   case Intrinsic::x86_sse41_ptestnzc:
8193   case Intrinsic::x86_avx_ptestz_256:
8194   case Intrinsic::x86_avx_ptestc_256:
8195   case Intrinsic::x86_avx_ptestnzc_256:
8196   case Intrinsic::x86_avx_vtestz_ps:
8197   case Intrinsic::x86_avx_vtestc_ps:
8198   case Intrinsic::x86_avx_vtestnzc_ps:
8199   case Intrinsic::x86_avx_vtestz_pd:
8200   case Intrinsic::x86_avx_vtestc_pd:
8201   case Intrinsic::x86_avx_vtestnzc_pd:
8202   case Intrinsic::x86_avx_vtestz_ps_256:
8203   case Intrinsic::x86_avx_vtestc_ps_256:
8204   case Intrinsic::x86_avx_vtestnzc_ps_256:
8205   case Intrinsic::x86_avx_vtestz_pd_256:
8206   case Intrinsic::x86_avx_vtestc_pd_256:
8207   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8208     bool IsTestPacked = false;
8209     unsigned X86CC = 0;
8210     switch (IntNo) {
8211     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8212     case Intrinsic::x86_avx_vtestz_ps:
8213     case Intrinsic::x86_avx_vtestz_pd:
8214     case Intrinsic::x86_avx_vtestz_ps_256:
8215     case Intrinsic::x86_avx_vtestz_pd_256:
8216       IsTestPacked = true; // Fallthrough
8217     case Intrinsic::x86_sse41_ptestz:
8218     case Intrinsic::x86_avx_ptestz_256:
8219       // ZF = 1
8220       X86CC = X86::COND_E;
8221       break;
8222     case Intrinsic::x86_avx_vtestc_ps:
8223     case Intrinsic::x86_avx_vtestc_pd:
8224     case Intrinsic::x86_avx_vtestc_ps_256:
8225     case Intrinsic::x86_avx_vtestc_pd_256:
8226       IsTestPacked = true; // Fallthrough
8227     case Intrinsic::x86_sse41_ptestc:
8228     case Intrinsic::x86_avx_ptestc_256:
8229       // CF = 1
8230       X86CC = X86::COND_B;
8231       break;
8232     case Intrinsic::x86_avx_vtestnzc_ps:
8233     case Intrinsic::x86_avx_vtestnzc_pd:
8234     case Intrinsic::x86_avx_vtestnzc_ps_256:
8235     case Intrinsic::x86_avx_vtestnzc_pd_256:
8236       IsTestPacked = true; // Fallthrough
8237     case Intrinsic::x86_sse41_ptestnzc:
8238     case Intrinsic::x86_avx_ptestnzc_256:
8239       // ZF and CF = 0
8240       X86CC = X86::COND_A;
8241       break;
8242     }
8243
8244     SDValue LHS = Op.getOperand(1);
8245     SDValue RHS = Op.getOperand(2);
8246     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8247     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8248     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8249     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8250     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8251   }
8252
8253   // Fix vector shift instructions where the last operand is a non-immediate
8254   // i32 value.
8255   case Intrinsic::x86_sse2_pslli_w:
8256   case Intrinsic::x86_sse2_pslli_d:
8257   case Intrinsic::x86_sse2_pslli_q:
8258   case Intrinsic::x86_sse2_psrli_w:
8259   case Intrinsic::x86_sse2_psrli_d:
8260   case Intrinsic::x86_sse2_psrli_q:
8261   case Intrinsic::x86_sse2_psrai_w:
8262   case Intrinsic::x86_sse2_psrai_d:
8263   case Intrinsic::x86_mmx_pslli_w:
8264   case Intrinsic::x86_mmx_pslli_d:
8265   case Intrinsic::x86_mmx_pslli_q:
8266   case Intrinsic::x86_mmx_psrli_w:
8267   case Intrinsic::x86_mmx_psrli_d:
8268   case Intrinsic::x86_mmx_psrli_q:
8269   case Intrinsic::x86_mmx_psrai_w:
8270   case Intrinsic::x86_mmx_psrai_d: {
8271     SDValue ShAmt = Op.getOperand(2);
8272     if (isa<ConstantSDNode>(ShAmt))
8273       return SDValue();
8274
8275     unsigned NewIntNo = 0;
8276     EVT ShAmtVT = MVT::v4i32;
8277     switch (IntNo) {
8278     case Intrinsic::x86_sse2_pslli_w:
8279       NewIntNo = Intrinsic::x86_sse2_psll_w;
8280       break;
8281     case Intrinsic::x86_sse2_pslli_d:
8282       NewIntNo = Intrinsic::x86_sse2_psll_d;
8283       break;
8284     case Intrinsic::x86_sse2_pslli_q:
8285       NewIntNo = Intrinsic::x86_sse2_psll_q;
8286       break;
8287     case Intrinsic::x86_sse2_psrli_w:
8288       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8289       break;
8290     case Intrinsic::x86_sse2_psrli_d:
8291       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8292       break;
8293     case Intrinsic::x86_sse2_psrli_q:
8294       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8295       break;
8296     case Intrinsic::x86_sse2_psrai_w:
8297       NewIntNo = Intrinsic::x86_sse2_psra_w;
8298       break;
8299     case Intrinsic::x86_sse2_psrai_d:
8300       NewIntNo = Intrinsic::x86_sse2_psra_d;
8301       break;
8302     default: {
8303       ShAmtVT = MVT::v2i32;
8304       switch (IntNo) {
8305       case Intrinsic::x86_mmx_pslli_w:
8306         NewIntNo = Intrinsic::x86_mmx_psll_w;
8307         break;
8308       case Intrinsic::x86_mmx_pslli_d:
8309         NewIntNo = Intrinsic::x86_mmx_psll_d;
8310         break;
8311       case Intrinsic::x86_mmx_pslli_q:
8312         NewIntNo = Intrinsic::x86_mmx_psll_q;
8313         break;
8314       case Intrinsic::x86_mmx_psrli_w:
8315         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8316         break;
8317       case Intrinsic::x86_mmx_psrli_d:
8318         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8319         break;
8320       case Intrinsic::x86_mmx_psrli_q:
8321         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8322         break;
8323       case Intrinsic::x86_mmx_psrai_w:
8324         NewIntNo = Intrinsic::x86_mmx_psra_w;
8325         break;
8326       case Intrinsic::x86_mmx_psrai_d:
8327         NewIntNo = Intrinsic::x86_mmx_psra_d;
8328         break;
8329       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8330       }
8331       break;
8332     }
8333     }
8334
8335     // The vector shift intrinsics with scalars uses 32b shift amounts but
8336     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8337     // to be zero.
8338     SDValue ShOps[4];
8339     ShOps[0] = ShAmt;
8340     ShOps[1] = DAG.getConstant(0, MVT::i32);
8341     if (ShAmtVT == MVT::v4i32) {
8342       ShOps[2] = DAG.getUNDEF(MVT::i32);
8343       ShOps[3] = DAG.getUNDEF(MVT::i32);
8344       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8345     } else {
8346       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8347 // FIXME this must be lowered to get rid of the invalid type.
8348     }
8349
8350     EVT VT = Op.getValueType();
8351     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8352     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8353                        DAG.getConstant(NewIntNo, MVT::i32),
8354                        Op.getOperand(1), ShAmt);
8355   }
8356   }
8357 }
8358
8359 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8360                                            SelectionDAG &DAG) const {
8361   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8362   MFI->setReturnAddressIsTaken(true);
8363
8364   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8365   DebugLoc dl = Op.getDebugLoc();
8366
8367   if (Depth > 0) {
8368     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8369     SDValue Offset =
8370       DAG.getConstant(TD->getPointerSize(),
8371                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8372     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8373                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8374                                    FrameAddr, Offset),
8375                        MachinePointerInfo(), false, false, 0);
8376   }
8377
8378   // Just load the return address.
8379   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8380   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8381                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8382 }
8383
8384 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8385   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8386   MFI->setFrameAddressIsTaken(true);
8387
8388   EVT VT = Op.getValueType();
8389   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8390   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8391   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8392   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8393   while (Depth--)
8394     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8395                             MachinePointerInfo(),
8396                             false, false, 0);
8397   return FrameAddr;
8398 }
8399
8400 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8401                                                      SelectionDAG &DAG) const {
8402   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8403 }
8404
8405 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8406   MachineFunction &MF = DAG.getMachineFunction();
8407   SDValue Chain     = Op.getOperand(0);
8408   SDValue Offset    = Op.getOperand(1);
8409   SDValue Handler   = Op.getOperand(2);
8410   DebugLoc dl       = Op.getDebugLoc();
8411
8412   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8413                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8414                                      getPointerTy());
8415   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8416
8417   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8418                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8419   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8420   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8421                        false, false, 0);
8422   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8423   MF.getRegInfo().addLiveOut(StoreAddrReg);
8424
8425   return DAG.getNode(X86ISD::EH_RETURN, dl,
8426                      MVT::Other,
8427                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8428 }
8429
8430 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8431                                              SelectionDAG &DAG) const {
8432   SDValue Root = Op.getOperand(0);
8433   SDValue Trmp = Op.getOperand(1); // trampoline
8434   SDValue FPtr = Op.getOperand(2); // nested function
8435   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8436   DebugLoc dl  = Op.getDebugLoc();
8437
8438   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8439
8440   if (Subtarget->is64Bit()) {
8441     SDValue OutChains[6];
8442
8443     // Large code-model.
8444     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8445     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8446
8447     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8448     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8449
8450     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8451
8452     // Load the pointer to the nested function into R11.
8453     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8454     SDValue Addr = Trmp;
8455     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8456                                 Addr, MachinePointerInfo(TrmpAddr),
8457                                 false, false, 0);
8458
8459     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8460                        DAG.getConstant(2, MVT::i64));
8461     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8462                                 MachinePointerInfo(TrmpAddr, 2),
8463                                 false, false, 2);
8464
8465     // Load the 'nest' parameter value into R10.
8466     // R10 is specified in X86CallingConv.td
8467     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8468     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8469                        DAG.getConstant(10, MVT::i64));
8470     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8471                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8472                                 false, false, 0);
8473
8474     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8475                        DAG.getConstant(12, MVT::i64));
8476     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8477                                 MachinePointerInfo(TrmpAddr, 12),
8478                                 false, false, 2);
8479
8480     // Jump to the nested function.
8481     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8482     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8483                        DAG.getConstant(20, MVT::i64));
8484     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8485                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8486                                 false, false, 0);
8487
8488     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8489     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8490                        DAG.getConstant(22, MVT::i64));
8491     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8492                                 MachinePointerInfo(TrmpAddr, 22),
8493                                 false, false, 0);
8494
8495     SDValue Ops[] =
8496       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8497     return DAG.getMergeValues(Ops, 2, dl);
8498   } else {
8499     const Function *Func =
8500       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8501     CallingConv::ID CC = Func->getCallingConv();
8502     unsigned NestReg;
8503
8504     switch (CC) {
8505     default:
8506       llvm_unreachable("Unsupported calling convention");
8507     case CallingConv::C:
8508     case CallingConv::X86_StdCall: {
8509       // Pass 'nest' parameter in ECX.
8510       // Must be kept in sync with X86CallingConv.td
8511       NestReg = X86::ECX;
8512
8513       // Check that ECX wasn't needed by an 'inreg' parameter.
8514       const FunctionType *FTy = Func->getFunctionType();
8515       const AttrListPtr &Attrs = Func->getAttributes();
8516
8517       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8518         unsigned InRegCount = 0;
8519         unsigned Idx = 1;
8520
8521         for (FunctionType::param_iterator I = FTy->param_begin(),
8522              E = FTy->param_end(); I != E; ++I, ++Idx)
8523           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8524             // FIXME: should only count parameters that are lowered to integers.
8525             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8526
8527         if (InRegCount > 2) {
8528           report_fatal_error("Nest register in use - reduce number of inreg"
8529                              " parameters!");
8530         }
8531       }
8532       break;
8533     }
8534     case CallingConv::X86_FastCall:
8535     case CallingConv::X86_ThisCall:
8536     case CallingConv::Fast:
8537       // Pass 'nest' parameter in EAX.
8538       // Must be kept in sync with X86CallingConv.td
8539       NestReg = X86::EAX;
8540       break;
8541     }
8542
8543     SDValue OutChains[4];
8544     SDValue Addr, Disp;
8545
8546     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8547                        DAG.getConstant(10, MVT::i32));
8548     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8549
8550     // This is storing the opcode for MOV32ri.
8551     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8552     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8553     OutChains[0] = DAG.getStore(Root, dl,
8554                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8555                                 Trmp, MachinePointerInfo(TrmpAddr),
8556                                 false, false, 0);
8557
8558     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8559                        DAG.getConstant(1, MVT::i32));
8560     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8561                                 MachinePointerInfo(TrmpAddr, 1),
8562                                 false, false, 1);
8563
8564     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8565     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8566                        DAG.getConstant(5, MVT::i32));
8567     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8568                                 MachinePointerInfo(TrmpAddr, 5),
8569                                 false, false, 1);
8570
8571     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8572                        DAG.getConstant(6, MVT::i32));
8573     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8574                                 MachinePointerInfo(TrmpAddr, 6),
8575                                 false, false, 1);
8576
8577     SDValue Ops[] =
8578       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8579     return DAG.getMergeValues(Ops, 2, dl);
8580   }
8581 }
8582
8583 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8584                                             SelectionDAG &DAG) const {
8585   /*
8586    The rounding mode is in bits 11:10 of FPSR, and has the following
8587    settings:
8588      00 Round to nearest
8589      01 Round to -inf
8590      10 Round to +inf
8591      11 Round to 0
8592
8593   FLT_ROUNDS, on the other hand, expects the following:
8594     -1 Undefined
8595      0 Round to 0
8596      1 Round to nearest
8597      2 Round to +inf
8598      3 Round to -inf
8599
8600   To perform the conversion, we do:
8601     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8602   */
8603
8604   MachineFunction &MF = DAG.getMachineFunction();
8605   const TargetMachine &TM = MF.getTarget();
8606   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8607   unsigned StackAlignment = TFI.getStackAlignment();
8608   EVT VT = Op.getValueType();
8609   DebugLoc DL = Op.getDebugLoc();
8610
8611   // Save FP Control Word to stack slot
8612   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8613   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8614
8615
8616   MachineMemOperand *MMO =
8617    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8618                            MachineMemOperand::MOStore, 2, 2);
8619
8620   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8621   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8622                                           DAG.getVTList(MVT::Other),
8623                                           Ops, 2, MVT::i16, MMO);
8624
8625   // Load FP Control Word from stack slot
8626   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8627                             MachinePointerInfo(), false, false, 0);
8628
8629   // Transform as necessary
8630   SDValue CWD1 =
8631     DAG.getNode(ISD::SRL, DL, MVT::i16,
8632                 DAG.getNode(ISD::AND, DL, MVT::i16,
8633                             CWD, DAG.getConstant(0x800, MVT::i16)),
8634                 DAG.getConstant(11, MVT::i8));
8635   SDValue CWD2 =
8636     DAG.getNode(ISD::SRL, DL, MVT::i16,
8637                 DAG.getNode(ISD::AND, DL, MVT::i16,
8638                             CWD, DAG.getConstant(0x400, MVT::i16)),
8639                 DAG.getConstant(9, MVT::i8));
8640
8641   SDValue RetVal =
8642     DAG.getNode(ISD::AND, DL, MVT::i16,
8643                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8644                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8645                             DAG.getConstant(1, MVT::i16)),
8646                 DAG.getConstant(3, MVT::i16));
8647
8648
8649   return DAG.getNode((VT.getSizeInBits() < 16 ?
8650                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8651 }
8652
8653 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8654   EVT VT = Op.getValueType();
8655   EVT OpVT = VT;
8656   unsigned NumBits = VT.getSizeInBits();
8657   DebugLoc dl = Op.getDebugLoc();
8658
8659   Op = Op.getOperand(0);
8660   if (VT == MVT::i8) {
8661     // Zero extend to i32 since there is not an i8 bsr.
8662     OpVT = MVT::i32;
8663     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8664   }
8665
8666   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8667   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8668   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8669
8670   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8671   SDValue Ops[] = {
8672     Op,
8673     DAG.getConstant(NumBits+NumBits-1, OpVT),
8674     DAG.getConstant(X86::COND_E, MVT::i8),
8675     Op.getValue(1)
8676   };
8677   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8678
8679   // Finally xor with NumBits-1.
8680   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8681
8682   if (VT == MVT::i8)
8683     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8684   return Op;
8685 }
8686
8687 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8688   EVT VT = Op.getValueType();
8689   EVT OpVT = VT;
8690   unsigned NumBits = VT.getSizeInBits();
8691   DebugLoc dl = Op.getDebugLoc();
8692
8693   Op = Op.getOperand(0);
8694   if (VT == MVT::i8) {
8695     OpVT = MVT::i32;
8696     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8697   }
8698
8699   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8700   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8701   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8702
8703   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8704   SDValue Ops[] = {
8705     Op,
8706     DAG.getConstant(NumBits, OpVT),
8707     DAG.getConstant(X86::COND_E, MVT::i8),
8708     Op.getValue(1)
8709   };
8710   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8711
8712   if (VT == MVT::i8)
8713     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8714   return Op;
8715 }
8716
8717 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8718   EVT VT = Op.getValueType();
8719   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8720   DebugLoc dl = Op.getDebugLoc();
8721
8722   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8723   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8724   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8725   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8726   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8727   //
8728   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8729   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8730   //  return AloBlo + AloBhi + AhiBlo;
8731
8732   SDValue A = Op.getOperand(0);
8733   SDValue B = Op.getOperand(1);
8734
8735   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8736                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8737                        A, DAG.getConstant(32, MVT::i32));
8738   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8739                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8740                        B, DAG.getConstant(32, MVT::i32));
8741   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8742                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8743                        A, B);
8744   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8745                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8746                        A, Bhi);
8747   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8748                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8749                        Ahi, B);
8750   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8751                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8752                        AloBhi, DAG.getConstant(32, MVT::i32));
8753   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8754                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8755                        AhiBlo, DAG.getConstant(32, MVT::i32));
8756   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8757   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8758   return Res;
8759 }
8760
8761 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8762   EVT VT = Op.getValueType();
8763   DebugLoc dl = Op.getDebugLoc();
8764   SDValue R = Op.getOperand(0);
8765
8766   LLVMContext *Context = DAG.getContext();
8767
8768   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8769
8770   if (VT == MVT::v4i32) {
8771     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8772                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8773                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8774
8775     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8776
8777     std::vector<Constant*> CV(4, CI);
8778     Constant *C = ConstantVector::get(CV);
8779     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8780     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8781                                  MachinePointerInfo::getConstantPool(),
8782                                  false, false, 16);
8783
8784     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8785     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8786     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8787     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8788   }
8789   if (VT == MVT::v16i8) {
8790     // a = a << 5;
8791     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8792                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8793                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8794
8795     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8796     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8797
8798     std::vector<Constant*> CVM1(16, CM1);
8799     std::vector<Constant*> CVM2(16, CM2);
8800     Constant *C = ConstantVector::get(CVM1);
8801     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8802     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8803                             MachinePointerInfo::getConstantPool(),
8804                             false, false, 16);
8805
8806     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8807     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8808     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8809                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8810                     DAG.getConstant(4, MVT::i32));
8811     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8812     // a += a
8813     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8814
8815     C = ConstantVector::get(CVM2);
8816     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8817     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8818                     MachinePointerInfo::getConstantPool(),
8819                     false, false, 16);
8820
8821     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8822     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8823     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8824                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8825                     DAG.getConstant(2, MVT::i32));
8826     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8827     // a += a
8828     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8829
8830     // return pblendv(r, r+r, a);
8831     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8832                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8833     return R;
8834   }
8835   return SDValue();
8836 }
8837
8838 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8839   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8840   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8841   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8842   // has only one use.
8843   SDNode *N = Op.getNode();
8844   SDValue LHS = N->getOperand(0);
8845   SDValue RHS = N->getOperand(1);
8846   unsigned BaseOp = 0;
8847   unsigned Cond = 0;
8848   DebugLoc DL = Op.getDebugLoc();
8849   switch (Op.getOpcode()) {
8850   default: llvm_unreachable("Unknown ovf instruction!");
8851   case ISD::SADDO:
8852     // A subtract of one will be selected as a INC. Note that INC doesn't
8853     // set CF, so we can't do this for UADDO.
8854     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8855       if (C->isOne()) {
8856         BaseOp = X86ISD::INC;
8857         Cond = X86::COND_O;
8858         break;
8859       }
8860     BaseOp = X86ISD::ADD;
8861     Cond = X86::COND_O;
8862     break;
8863   case ISD::UADDO:
8864     BaseOp = X86ISD::ADD;
8865     Cond = X86::COND_B;
8866     break;
8867   case ISD::SSUBO:
8868     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8869     // set CF, so we can't do this for USUBO.
8870     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8871       if (C->isOne()) {
8872         BaseOp = X86ISD::DEC;
8873         Cond = X86::COND_O;
8874         break;
8875       }
8876     BaseOp = X86ISD::SUB;
8877     Cond = X86::COND_O;
8878     break;
8879   case ISD::USUBO:
8880     BaseOp = X86ISD::SUB;
8881     Cond = X86::COND_B;
8882     break;
8883   case ISD::SMULO:
8884     BaseOp = X86ISD::SMUL;
8885     Cond = X86::COND_O;
8886     break;
8887   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8888     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8889                                  MVT::i32);
8890     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8891
8892     SDValue SetCC =
8893       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8894                   DAG.getConstant(X86::COND_O, MVT::i32),
8895                   SDValue(Sum.getNode(), 2));
8896
8897     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8898     return Sum;
8899   }
8900   }
8901
8902   // Also sets EFLAGS.
8903   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8904   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8905
8906   SDValue SetCC =
8907     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8908                 DAG.getConstant(Cond, MVT::i32),
8909                 SDValue(Sum.getNode(), 1));
8910
8911   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8912   return Sum;
8913 }
8914
8915 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8916   DebugLoc dl = Op.getDebugLoc();
8917
8918   if (!Subtarget->hasSSE2()) {
8919     SDValue Chain = Op.getOperand(0);
8920     SDValue Zero = DAG.getConstant(0,
8921                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8922     SDValue Ops[] = {
8923       DAG.getRegister(X86::ESP, MVT::i32), // Base
8924       DAG.getTargetConstant(1, MVT::i8),   // Scale
8925       DAG.getRegister(0, MVT::i32),        // Index
8926       DAG.getTargetConstant(0, MVT::i32),  // Disp
8927       DAG.getRegister(0, MVT::i32),        // Segment.
8928       Zero,
8929       Chain
8930     };
8931     SDNode *Res =
8932       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8933                           array_lengthof(Ops));
8934     return SDValue(Res, 0);
8935   }
8936
8937   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8938   if (!isDev)
8939     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8940
8941   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8942   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8943   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8944   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8945
8946   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8947   if (!Op1 && !Op2 && !Op3 && Op4)
8948     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8949
8950   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8951   if (Op1 && !Op2 && !Op3 && !Op4)
8952     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8953
8954   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8955   //           (MFENCE)>;
8956   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8957 }
8958
8959 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8960   EVT T = Op.getValueType();
8961   DebugLoc DL = Op.getDebugLoc();
8962   unsigned Reg = 0;
8963   unsigned size = 0;
8964   switch(T.getSimpleVT().SimpleTy) {
8965   default:
8966     assert(false && "Invalid value type!");
8967   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8968   case MVT::i16: Reg = X86::AX;  size = 2; break;
8969   case MVT::i32: Reg = X86::EAX; size = 4; break;
8970   case MVT::i64:
8971     assert(Subtarget->is64Bit() && "Node not type legal!");
8972     Reg = X86::RAX; size = 8;
8973     break;
8974   }
8975   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8976                                     Op.getOperand(2), SDValue());
8977   SDValue Ops[] = { cpIn.getValue(0),
8978                     Op.getOperand(1),
8979                     Op.getOperand(3),
8980                     DAG.getTargetConstant(size, MVT::i8),
8981                     cpIn.getValue(1) };
8982   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8983   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8984   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8985                                            Ops, 5, T, MMO);
8986   SDValue cpOut =
8987     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8988   return cpOut;
8989 }
8990
8991 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8992                                                  SelectionDAG &DAG) const {
8993   assert(Subtarget->is64Bit() && "Result not type legalized?");
8994   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8995   SDValue TheChain = Op.getOperand(0);
8996   DebugLoc dl = Op.getDebugLoc();
8997   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8998   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8999   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9000                                    rax.getValue(2));
9001   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9002                             DAG.getConstant(32, MVT::i8));
9003   SDValue Ops[] = {
9004     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9005     rdx.getValue(1)
9006   };
9007   return DAG.getMergeValues(Ops, 2, dl);
9008 }
9009
9010 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9011                                             SelectionDAG &DAG) const {
9012   EVT SrcVT = Op.getOperand(0).getValueType();
9013   EVT DstVT = Op.getValueType();
9014   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9015          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9016   assert((DstVT == MVT::i64 ||
9017           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9018          "Unexpected custom BITCAST");
9019   // i64 <=> MMX conversions are Legal.
9020   if (SrcVT==MVT::i64 && DstVT.isVector())
9021     return Op;
9022   if (DstVT==MVT::i64 && SrcVT.isVector())
9023     return Op;
9024   // MMX <=> MMX conversions are Legal.
9025   if (SrcVT.isVector() && DstVT.isVector())
9026     return Op;
9027   // All other conversions need to be expanded.
9028   return SDValue();
9029 }
9030
9031 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9032   SDNode *Node = Op.getNode();
9033   DebugLoc dl = Node->getDebugLoc();
9034   EVT T = Node->getValueType(0);
9035   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9036                               DAG.getConstant(0, T), Node->getOperand(2));
9037   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9038                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9039                        Node->getOperand(0),
9040                        Node->getOperand(1), negOp,
9041                        cast<AtomicSDNode>(Node)->getSrcValue(),
9042                        cast<AtomicSDNode>(Node)->getAlignment());
9043 }
9044
9045 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9046   EVT VT = Op.getNode()->getValueType(0);
9047
9048   // Let legalize expand this if it isn't a legal type yet.
9049   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9050     return SDValue();
9051
9052   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9053
9054   unsigned Opc;
9055   bool ExtraOp = false;
9056   switch (Op.getOpcode()) {
9057   default: assert(0 && "Invalid code");
9058   case ISD::ADDC: Opc = X86ISD::ADD; break;
9059   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9060   case ISD::SUBC: Opc = X86ISD::SUB; break;
9061   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9062   }
9063
9064   if (!ExtraOp)
9065     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9066                        Op.getOperand(1));
9067   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9068                      Op.getOperand(1), Op.getOperand(2));
9069 }
9070
9071 /// LowerOperation - Provide custom lowering hooks for some operations.
9072 ///
9073 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9074   switch (Op.getOpcode()) {
9075   default: llvm_unreachable("Should not custom lower this!");
9076   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9077   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9078   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9079   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9080   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9081   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9082   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9083   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9084   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9085   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9086   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9087   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9088   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9089   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9090   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9091   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9092   case ISD::SHL_PARTS:
9093   case ISD::SRA_PARTS:
9094   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
9095   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9096   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9097   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9098   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9099   case ISD::FABS:               return LowerFABS(Op, DAG);
9100   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9101   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9102   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9103   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9104   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9105   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9106   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9107   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9108   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9109   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9110   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9111   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9112   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9113   case ISD::FRAME_TO_ARGS_OFFSET:
9114                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9115   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9116   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9117   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9118   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9119   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9120   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9121   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9122   case ISD::SHL:                return LowerSHL(Op, DAG);
9123   case ISD::SADDO:
9124   case ISD::UADDO:
9125   case ISD::SSUBO:
9126   case ISD::USUBO:
9127   case ISD::SMULO:
9128   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9129   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9130   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9131   case ISD::ADDC:
9132   case ISD::ADDE:
9133   case ISD::SUBC:
9134   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9135   }
9136 }
9137
9138 void X86TargetLowering::
9139 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9140                         SelectionDAG &DAG, unsigned NewOp) const {
9141   EVT T = Node->getValueType(0);
9142   DebugLoc dl = Node->getDebugLoc();
9143   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9144
9145   SDValue Chain = Node->getOperand(0);
9146   SDValue In1 = Node->getOperand(1);
9147   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9148                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9149   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9150                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9151   SDValue Ops[] = { Chain, In1, In2L, In2H };
9152   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9153   SDValue Result =
9154     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9155                             cast<MemSDNode>(Node)->getMemOperand());
9156   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9157   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9158   Results.push_back(Result.getValue(2));
9159 }
9160
9161 /// ReplaceNodeResults - Replace a node with an illegal result type
9162 /// with a new node built out of custom code.
9163 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9164                                            SmallVectorImpl<SDValue>&Results,
9165                                            SelectionDAG &DAG) const {
9166   DebugLoc dl = N->getDebugLoc();
9167   switch (N->getOpcode()) {
9168   default:
9169     assert(false && "Do not know how to custom type legalize this operation!");
9170     return;
9171   case ISD::ADDC:
9172   case ISD::ADDE:
9173   case ISD::SUBC:
9174   case ISD::SUBE:
9175     // We don't want to expand or promote these.
9176     return;
9177   case ISD::FP_TO_SINT: {
9178     std::pair<SDValue,SDValue> Vals =
9179         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9180     SDValue FIST = Vals.first, StackSlot = Vals.second;
9181     if (FIST.getNode() != 0) {
9182       EVT VT = N->getValueType(0);
9183       // Return a load from the stack slot.
9184       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9185                                     MachinePointerInfo(), false, false, 0));
9186     }
9187     return;
9188   }
9189   case ISD::READCYCLECOUNTER: {
9190     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9191     SDValue TheChain = N->getOperand(0);
9192     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9193     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9194                                      rd.getValue(1));
9195     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9196                                      eax.getValue(2));
9197     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9198     SDValue Ops[] = { eax, edx };
9199     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9200     Results.push_back(edx.getValue(1));
9201     return;
9202   }
9203   case ISD::ATOMIC_CMP_SWAP: {
9204     EVT T = N->getValueType(0);
9205     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9206     SDValue cpInL, cpInH;
9207     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9208                         DAG.getConstant(0, MVT::i32));
9209     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9210                         DAG.getConstant(1, MVT::i32));
9211     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9212     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9213                              cpInL.getValue(1));
9214     SDValue swapInL, swapInH;
9215     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9216                           DAG.getConstant(0, MVT::i32));
9217     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9218                           DAG.getConstant(1, MVT::i32));
9219     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9220                                cpInH.getValue(1));
9221     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9222                                swapInL.getValue(1));
9223     SDValue Ops[] = { swapInH.getValue(0),
9224                       N->getOperand(1),
9225                       swapInH.getValue(1) };
9226     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9227     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9228     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9229                                              Ops, 3, T, MMO);
9230     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9231                                         MVT::i32, Result.getValue(1));
9232     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9233                                         MVT::i32, cpOutL.getValue(2));
9234     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9235     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9236     Results.push_back(cpOutH.getValue(1));
9237     return;
9238   }
9239   case ISD::ATOMIC_LOAD_ADD:
9240     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9241     return;
9242   case ISD::ATOMIC_LOAD_AND:
9243     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9244     return;
9245   case ISD::ATOMIC_LOAD_NAND:
9246     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9247     return;
9248   case ISD::ATOMIC_LOAD_OR:
9249     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9250     return;
9251   case ISD::ATOMIC_LOAD_SUB:
9252     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9253     return;
9254   case ISD::ATOMIC_LOAD_XOR:
9255     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9256     return;
9257   case ISD::ATOMIC_SWAP:
9258     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9259     return;
9260   }
9261 }
9262
9263 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9264   switch (Opcode) {
9265   default: return NULL;
9266   case X86ISD::BSF:                return "X86ISD::BSF";
9267   case X86ISD::BSR:                return "X86ISD::BSR";
9268   case X86ISD::SHLD:               return "X86ISD::SHLD";
9269   case X86ISD::SHRD:               return "X86ISD::SHRD";
9270   case X86ISD::FAND:               return "X86ISD::FAND";
9271   case X86ISD::FOR:                return "X86ISD::FOR";
9272   case X86ISD::FXOR:               return "X86ISD::FXOR";
9273   case X86ISD::FSRL:               return "X86ISD::FSRL";
9274   case X86ISD::FILD:               return "X86ISD::FILD";
9275   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9276   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9277   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9278   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9279   case X86ISD::FLD:                return "X86ISD::FLD";
9280   case X86ISD::FST:                return "X86ISD::FST";
9281   case X86ISD::CALL:               return "X86ISD::CALL";
9282   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9283   case X86ISD::BT:                 return "X86ISD::BT";
9284   case X86ISD::CMP:                return "X86ISD::CMP";
9285   case X86ISD::COMI:               return "X86ISD::COMI";
9286   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9287   case X86ISD::SETCC:              return "X86ISD::SETCC";
9288   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9289   case X86ISD::CMOV:               return "X86ISD::CMOV";
9290   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9291   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9292   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9293   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9294   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9295   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9296   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9297   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9298   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9299   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9300   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9301   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9302   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9303   case X86ISD::PANDN:              return "X86ISD::PANDN";
9304   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9305   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9306   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9307   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9308   case X86ISD::FMAX:               return "X86ISD::FMAX";
9309   case X86ISD::FMIN:               return "X86ISD::FMIN";
9310   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9311   case X86ISD::FRCP:               return "X86ISD::FRCP";
9312   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9313   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9314   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9315   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9316   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9317   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9318   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9319   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9320   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9321   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9322   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9323   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9324   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9325   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9326   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9327   case X86ISD::VSHL:               return "X86ISD::VSHL";
9328   case X86ISD::VSRL:               return "X86ISD::VSRL";
9329   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9330   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9331   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9332   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9333   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9334   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9335   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9336   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9337   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9338   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9339   case X86ISD::ADD:                return "X86ISD::ADD";
9340   case X86ISD::SUB:                return "X86ISD::SUB";
9341   case X86ISD::ADC:                return "X86ISD::ADC";
9342   case X86ISD::SBB:                return "X86ISD::SBB";
9343   case X86ISD::SMUL:               return "X86ISD::SMUL";
9344   case X86ISD::UMUL:               return "X86ISD::UMUL";
9345   case X86ISD::INC:                return "X86ISD::INC";
9346   case X86ISD::DEC:                return "X86ISD::DEC";
9347   case X86ISD::OR:                 return "X86ISD::OR";
9348   case X86ISD::XOR:                return "X86ISD::XOR";
9349   case X86ISD::AND:                return "X86ISD::AND";
9350   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9351   case X86ISD::PTEST:              return "X86ISD::PTEST";
9352   case X86ISD::TESTP:              return "X86ISD::TESTP";
9353   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9354   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9355   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9356   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9357   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9358   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9359   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9360   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9361   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9362   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9363   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9364   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9365   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9366   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9367   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9368   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9369   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9370   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9371   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9372   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9373   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9374   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9375   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9376   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9377   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9378   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9379   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9380   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9381   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9382   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9383   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9384   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9385   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9386   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9387   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9388   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9389   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9390   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9391   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9392   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9393   }
9394 }
9395
9396 // isLegalAddressingMode - Return true if the addressing mode represented
9397 // by AM is legal for this target, for a load/store of the specified type.
9398 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9399                                               const Type *Ty) const {
9400   // X86 supports extremely general addressing modes.
9401   CodeModel::Model M = getTargetMachine().getCodeModel();
9402   Reloc::Model R = getTargetMachine().getRelocationModel();
9403
9404   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9405   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9406     return false;
9407
9408   if (AM.BaseGV) {
9409     unsigned GVFlags =
9410       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9411
9412     // If a reference to this global requires an extra load, we can't fold it.
9413     if (isGlobalStubReference(GVFlags))
9414       return false;
9415
9416     // If BaseGV requires a register for the PIC base, we cannot also have a
9417     // BaseReg specified.
9418     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9419       return false;
9420
9421     // If lower 4G is not available, then we must use rip-relative addressing.
9422     if ((M != CodeModel::Small || R != Reloc::Static) &&
9423         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9424       return false;
9425   }
9426
9427   switch (AM.Scale) {
9428   case 0:
9429   case 1:
9430   case 2:
9431   case 4:
9432   case 8:
9433     // These scales always work.
9434     break;
9435   case 3:
9436   case 5:
9437   case 9:
9438     // These scales are formed with basereg+scalereg.  Only accept if there is
9439     // no basereg yet.
9440     if (AM.HasBaseReg)
9441       return false;
9442     break;
9443   default:  // Other stuff never works.
9444     return false;
9445   }
9446
9447   return true;
9448 }
9449
9450
9451 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9452   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9453     return false;
9454   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9455   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9456   if (NumBits1 <= NumBits2)
9457     return false;
9458   return true;
9459 }
9460
9461 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9462   if (!VT1.isInteger() || !VT2.isInteger())
9463     return false;
9464   unsigned NumBits1 = VT1.getSizeInBits();
9465   unsigned NumBits2 = VT2.getSizeInBits();
9466   if (NumBits1 <= NumBits2)
9467     return false;
9468   return true;
9469 }
9470
9471 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9472   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9473   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9474 }
9475
9476 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9477   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9478   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9479 }
9480
9481 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9482   // i16 instructions are longer (0x66 prefix) and potentially slower.
9483   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9484 }
9485
9486 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9487 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9488 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9489 /// are assumed to be legal.
9490 bool
9491 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9492                                       EVT VT) const {
9493   // Very little shuffling can be done for 64-bit vectors right now.
9494   if (VT.getSizeInBits() == 64)
9495     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9496
9497   // FIXME: pshufb, blends, shifts.
9498   return (VT.getVectorNumElements() == 2 ||
9499           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9500           isMOVLMask(M, VT) ||
9501           isSHUFPMask(M, VT) ||
9502           isPSHUFDMask(M, VT) ||
9503           isPSHUFHWMask(M, VT) ||
9504           isPSHUFLWMask(M, VT) ||
9505           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9506           isUNPCKLMask(M, VT) ||
9507           isUNPCKHMask(M, VT) ||
9508           isUNPCKL_v_undef_Mask(M, VT) ||
9509           isUNPCKH_v_undef_Mask(M, VT));
9510 }
9511
9512 bool
9513 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9514                                           EVT VT) const {
9515   unsigned NumElts = VT.getVectorNumElements();
9516   // FIXME: This collection of masks seems suspect.
9517   if (NumElts == 2)
9518     return true;
9519   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9520     return (isMOVLMask(Mask, VT)  ||
9521             isCommutedMOVLMask(Mask, VT, true) ||
9522             isSHUFPMask(Mask, VT) ||
9523             isCommutedSHUFPMask(Mask, VT));
9524   }
9525   return false;
9526 }
9527
9528 //===----------------------------------------------------------------------===//
9529 //                           X86 Scheduler Hooks
9530 //===----------------------------------------------------------------------===//
9531
9532 // private utility function
9533 MachineBasicBlock *
9534 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9535                                                        MachineBasicBlock *MBB,
9536                                                        unsigned regOpc,
9537                                                        unsigned immOpc,
9538                                                        unsigned LoadOpc,
9539                                                        unsigned CXchgOpc,
9540                                                        unsigned notOpc,
9541                                                        unsigned EAXreg,
9542                                                        TargetRegisterClass *RC,
9543                                                        bool invSrc) const {
9544   // For the atomic bitwise operator, we generate
9545   //   thisMBB:
9546   //   newMBB:
9547   //     ld  t1 = [bitinstr.addr]
9548   //     op  t2 = t1, [bitinstr.val]
9549   //     mov EAX = t1
9550   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9551   //     bz  newMBB
9552   //     fallthrough -->nextMBB
9553   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9554   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9555   MachineFunction::iterator MBBIter = MBB;
9556   ++MBBIter;
9557
9558   /// First build the CFG
9559   MachineFunction *F = MBB->getParent();
9560   MachineBasicBlock *thisMBB = MBB;
9561   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9562   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9563   F->insert(MBBIter, newMBB);
9564   F->insert(MBBIter, nextMBB);
9565
9566   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9567   nextMBB->splice(nextMBB->begin(), thisMBB,
9568                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9569                   thisMBB->end());
9570   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9571
9572   // Update thisMBB to fall through to newMBB
9573   thisMBB->addSuccessor(newMBB);
9574
9575   // newMBB jumps to itself and fall through to nextMBB
9576   newMBB->addSuccessor(nextMBB);
9577   newMBB->addSuccessor(newMBB);
9578
9579   // Insert instructions into newMBB based on incoming instruction
9580   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9581          "unexpected number of operands");
9582   DebugLoc dl = bInstr->getDebugLoc();
9583   MachineOperand& destOper = bInstr->getOperand(0);
9584   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9585   int numArgs = bInstr->getNumOperands() - 1;
9586   for (int i=0; i < numArgs; ++i)
9587     argOpers[i] = &bInstr->getOperand(i+1);
9588
9589   // x86 address has 4 operands: base, index, scale, and displacement
9590   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9591   int valArgIndx = lastAddrIndx + 1;
9592
9593   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9594   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9595   for (int i=0; i <= lastAddrIndx; ++i)
9596     (*MIB).addOperand(*argOpers[i]);
9597
9598   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9599   if (invSrc) {
9600     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9601   }
9602   else
9603     tt = t1;
9604
9605   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9606   assert((argOpers[valArgIndx]->isReg() ||
9607           argOpers[valArgIndx]->isImm()) &&
9608          "invalid operand");
9609   if (argOpers[valArgIndx]->isReg())
9610     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9611   else
9612     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9613   MIB.addReg(tt);
9614   (*MIB).addOperand(*argOpers[valArgIndx]);
9615
9616   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9617   MIB.addReg(t1);
9618
9619   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9620   for (int i=0; i <= lastAddrIndx; ++i)
9621     (*MIB).addOperand(*argOpers[i]);
9622   MIB.addReg(t2);
9623   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9624   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9625                     bInstr->memoperands_end());
9626
9627   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9628   MIB.addReg(EAXreg);
9629
9630   // insert branch
9631   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9632
9633   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9634   return nextMBB;
9635 }
9636
9637 // private utility function:  64 bit atomics on 32 bit host.
9638 MachineBasicBlock *
9639 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9640                                                        MachineBasicBlock *MBB,
9641                                                        unsigned regOpcL,
9642                                                        unsigned regOpcH,
9643                                                        unsigned immOpcL,
9644                                                        unsigned immOpcH,
9645                                                        bool invSrc) const {
9646   // For the atomic bitwise operator, we generate
9647   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9648   //     ld t1,t2 = [bitinstr.addr]
9649   //   newMBB:
9650   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9651   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9652   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9653   //     mov ECX, EBX <- t5, t6
9654   //     mov EAX, EDX <- t1, t2
9655   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9656   //     mov t3, t4 <- EAX, EDX
9657   //     bz  newMBB
9658   //     result in out1, out2
9659   //     fallthrough -->nextMBB
9660
9661   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9662   const unsigned LoadOpc = X86::MOV32rm;
9663   const unsigned NotOpc = X86::NOT32r;
9664   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9665   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9666   MachineFunction::iterator MBBIter = MBB;
9667   ++MBBIter;
9668
9669   /// First build the CFG
9670   MachineFunction *F = MBB->getParent();
9671   MachineBasicBlock *thisMBB = MBB;
9672   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9673   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9674   F->insert(MBBIter, newMBB);
9675   F->insert(MBBIter, nextMBB);
9676
9677   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9678   nextMBB->splice(nextMBB->begin(), thisMBB,
9679                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9680                   thisMBB->end());
9681   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9682
9683   // Update thisMBB to fall through to newMBB
9684   thisMBB->addSuccessor(newMBB);
9685
9686   // newMBB jumps to itself and fall through to nextMBB
9687   newMBB->addSuccessor(nextMBB);
9688   newMBB->addSuccessor(newMBB);
9689
9690   DebugLoc dl = bInstr->getDebugLoc();
9691   // Insert instructions into newMBB based on incoming instruction
9692   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9693   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9694          "unexpected number of operands");
9695   MachineOperand& dest1Oper = bInstr->getOperand(0);
9696   MachineOperand& dest2Oper = bInstr->getOperand(1);
9697   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9698   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9699     argOpers[i] = &bInstr->getOperand(i+2);
9700
9701     // We use some of the operands multiple times, so conservatively just
9702     // clear any kill flags that might be present.
9703     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9704       argOpers[i]->setIsKill(false);
9705   }
9706
9707   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9708   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9709
9710   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9711   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9712   for (int i=0; i <= lastAddrIndx; ++i)
9713     (*MIB).addOperand(*argOpers[i]);
9714   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9715   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9716   // add 4 to displacement.
9717   for (int i=0; i <= lastAddrIndx-2; ++i)
9718     (*MIB).addOperand(*argOpers[i]);
9719   MachineOperand newOp3 = *(argOpers[3]);
9720   if (newOp3.isImm())
9721     newOp3.setImm(newOp3.getImm()+4);
9722   else
9723     newOp3.setOffset(newOp3.getOffset()+4);
9724   (*MIB).addOperand(newOp3);
9725   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9726
9727   // t3/4 are defined later, at the bottom of the loop
9728   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9729   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9730   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9731     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9732   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9733     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9734
9735   // The subsequent operations should be using the destination registers of
9736   //the PHI instructions.
9737   if (invSrc) {
9738     t1 = F->getRegInfo().createVirtualRegister(RC);
9739     t2 = F->getRegInfo().createVirtualRegister(RC);
9740     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9741     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9742   } else {
9743     t1 = dest1Oper.getReg();
9744     t2 = dest2Oper.getReg();
9745   }
9746
9747   int valArgIndx = lastAddrIndx + 1;
9748   assert((argOpers[valArgIndx]->isReg() ||
9749           argOpers[valArgIndx]->isImm()) &&
9750          "invalid operand");
9751   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9752   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9753   if (argOpers[valArgIndx]->isReg())
9754     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9755   else
9756     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9757   if (regOpcL != X86::MOV32rr)
9758     MIB.addReg(t1);
9759   (*MIB).addOperand(*argOpers[valArgIndx]);
9760   assert(argOpers[valArgIndx + 1]->isReg() ==
9761          argOpers[valArgIndx]->isReg());
9762   assert(argOpers[valArgIndx + 1]->isImm() ==
9763          argOpers[valArgIndx]->isImm());
9764   if (argOpers[valArgIndx + 1]->isReg())
9765     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9766   else
9767     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9768   if (regOpcH != X86::MOV32rr)
9769     MIB.addReg(t2);
9770   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9771
9772   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9773   MIB.addReg(t1);
9774   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9775   MIB.addReg(t2);
9776
9777   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9778   MIB.addReg(t5);
9779   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9780   MIB.addReg(t6);
9781
9782   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9783   for (int i=0; i <= lastAddrIndx; ++i)
9784     (*MIB).addOperand(*argOpers[i]);
9785
9786   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9787   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9788                     bInstr->memoperands_end());
9789
9790   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9791   MIB.addReg(X86::EAX);
9792   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9793   MIB.addReg(X86::EDX);
9794
9795   // insert branch
9796   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9797
9798   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9799   return nextMBB;
9800 }
9801
9802 // private utility function
9803 MachineBasicBlock *
9804 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9805                                                       MachineBasicBlock *MBB,
9806                                                       unsigned cmovOpc) const {
9807   // For the atomic min/max operator, we generate
9808   //   thisMBB:
9809   //   newMBB:
9810   //     ld t1 = [min/max.addr]
9811   //     mov t2 = [min/max.val]
9812   //     cmp  t1, t2
9813   //     cmov[cond] t2 = t1
9814   //     mov EAX = t1
9815   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9816   //     bz   newMBB
9817   //     fallthrough -->nextMBB
9818   //
9819   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9820   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9821   MachineFunction::iterator MBBIter = MBB;
9822   ++MBBIter;
9823
9824   /// First build the CFG
9825   MachineFunction *F = MBB->getParent();
9826   MachineBasicBlock *thisMBB = MBB;
9827   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9828   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9829   F->insert(MBBIter, newMBB);
9830   F->insert(MBBIter, nextMBB);
9831
9832   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9833   nextMBB->splice(nextMBB->begin(), thisMBB,
9834                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9835                   thisMBB->end());
9836   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9837
9838   // Update thisMBB to fall through to newMBB
9839   thisMBB->addSuccessor(newMBB);
9840
9841   // newMBB jumps to newMBB and fall through to nextMBB
9842   newMBB->addSuccessor(nextMBB);
9843   newMBB->addSuccessor(newMBB);
9844
9845   DebugLoc dl = mInstr->getDebugLoc();
9846   // Insert instructions into newMBB based on incoming instruction
9847   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9848          "unexpected number of operands");
9849   MachineOperand& destOper = mInstr->getOperand(0);
9850   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9851   int numArgs = mInstr->getNumOperands() - 1;
9852   for (int i=0; i < numArgs; ++i)
9853     argOpers[i] = &mInstr->getOperand(i+1);
9854
9855   // x86 address has 4 operands: base, index, scale, and displacement
9856   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9857   int valArgIndx = lastAddrIndx + 1;
9858
9859   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9860   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9861   for (int i=0; i <= lastAddrIndx; ++i)
9862     (*MIB).addOperand(*argOpers[i]);
9863
9864   // We only support register and immediate values
9865   assert((argOpers[valArgIndx]->isReg() ||
9866           argOpers[valArgIndx]->isImm()) &&
9867          "invalid operand");
9868
9869   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9870   if (argOpers[valArgIndx]->isReg())
9871     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9872   else
9873     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9874   (*MIB).addOperand(*argOpers[valArgIndx]);
9875
9876   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9877   MIB.addReg(t1);
9878
9879   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9880   MIB.addReg(t1);
9881   MIB.addReg(t2);
9882
9883   // Generate movc
9884   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9885   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9886   MIB.addReg(t2);
9887   MIB.addReg(t1);
9888
9889   // Cmp and exchange if none has modified the memory location
9890   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9891   for (int i=0; i <= lastAddrIndx; ++i)
9892     (*MIB).addOperand(*argOpers[i]);
9893   MIB.addReg(t3);
9894   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9895   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9896                     mInstr->memoperands_end());
9897
9898   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9899   MIB.addReg(X86::EAX);
9900
9901   // insert branch
9902   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9903
9904   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9905   return nextMBB;
9906 }
9907
9908 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9909 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9910 // in the .td file.
9911 MachineBasicBlock *
9912 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9913                             unsigned numArgs, bool memArg) const {
9914   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9915          "Target must have SSE4.2 or AVX features enabled");
9916
9917   DebugLoc dl = MI->getDebugLoc();
9918   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9919   unsigned Opc;
9920   if (!Subtarget->hasAVX()) {
9921     if (memArg)
9922       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9923     else
9924       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9925   } else {
9926     if (memArg)
9927       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9928     else
9929       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9930   }
9931
9932   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9933   for (unsigned i = 0; i < numArgs; ++i) {
9934     MachineOperand &Op = MI->getOperand(i+1);
9935     if (!(Op.isReg() && Op.isImplicit()))
9936       MIB.addOperand(Op);
9937   }
9938   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9939     .addReg(X86::XMM0);
9940
9941   MI->eraseFromParent();
9942   return BB;
9943 }
9944
9945 MachineBasicBlock *
9946 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9947   DebugLoc dl = MI->getDebugLoc();
9948   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9949
9950   // Address into RAX/EAX, other two args into ECX, EDX.
9951   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9952   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9953   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9954   for (int i = 0; i < X86::AddrNumOperands; ++i)
9955     MIB.addOperand(MI->getOperand(i));
9956
9957   unsigned ValOps = X86::AddrNumOperands;
9958   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9959     .addReg(MI->getOperand(ValOps).getReg());
9960   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9961     .addReg(MI->getOperand(ValOps+1).getReg());
9962
9963   // The instruction doesn't actually take any operands though.
9964   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9965
9966   MI->eraseFromParent(); // The pseudo is gone now.
9967   return BB;
9968 }
9969
9970 MachineBasicBlock *
9971 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9972   DebugLoc dl = MI->getDebugLoc();
9973   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9974
9975   // First arg in ECX, the second in EAX.
9976   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9977     .addReg(MI->getOperand(0).getReg());
9978   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9979     .addReg(MI->getOperand(1).getReg());
9980
9981   // The instruction doesn't actually take any operands though.
9982   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9983
9984   MI->eraseFromParent(); // The pseudo is gone now.
9985   return BB;
9986 }
9987
9988 MachineBasicBlock *
9989 X86TargetLowering::EmitVAARG64WithCustomInserter(
9990                    MachineInstr *MI,
9991                    MachineBasicBlock *MBB) const {
9992   // Emit va_arg instruction on X86-64.
9993
9994   // Operands to this pseudo-instruction:
9995   // 0  ) Output        : destination address (reg)
9996   // 1-5) Input         : va_list address (addr, i64mem)
9997   // 6  ) ArgSize       : Size (in bytes) of vararg type
9998   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9999   // 8  ) Align         : Alignment of type
10000   // 9  ) EFLAGS (implicit-def)
10001
10002   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10003   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10004
10005   unsigned DestReg = MI->getOperand(0).getReg();
10006   MachineOperand &Base = MI->getOperand(1);
10007   MachineOperand &Scale = MI->getOperand(2);
10008   MachineOperand &Index = MI->getOperand(3);
10009   MachineOperand &Disp = MI->getOperand(4);
10010   MachineOperand &Segment = MI->getOperand(5);
10011   unsigned ArgSize = MI->getOperand(6).getImm();
10012   unsigned ArgMode = MI->getOperand(7).getImm();
10013   unsigned Align = MI->getOperand(8).getImm();
10014
10015   // Memory Reference
10016   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10017   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10018   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10019
10020   // Machine Information
10021   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10022   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10023   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10024   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10025   DebugLoc DL = MI->getDebugLoc();
10026
10027   // struct va_list {
10028   //   i32   gp_offset
10029   //   i32   fp_offset
10030   //   i64   overflow_area (address)
10031   //   i64   reg_save_area (address)
10032   // }
10033   // sizeof(va_list) = 24
10034   // alignment(va_list) = 8
10035
10036   unsigned TotalNumIntRegs = 6;
10037   unsigned TotalNumXMMRegs = 8;
10038   bool UseGPOffset = (ArgMode == 1);
10039   bool UseFPOffset = (ArgMode == 2);
10040   unsigned MaxOffset = TotalNumIntRegs * 8 +
10041                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10042
10043   /* Align ArgSize to a multiple of 8 */
10044   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10045   bool NeedsAlign = (Align > 8);
10046
10047   MachineBasicBlock *thisMBB = MBB;
10048   MachineBasicBlock *overflowMBB;
10049   MachineBasicBlock *offsetMBB;
10050   MachineBasicBlock *endMBB;
10051
10052   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10053   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10054   unsigned OffsetReg = 0;
10055
10056   if (!UseGPOffset && !UseFPOffset) {
10057     // If we only pull from the overflow region, we don't create a branch.
10058     // We don't need to alter control flow.
10059     OffsetDestReg = 0; // unused
10060     OverflowDestReg = DestReg;
10061
10062     offsetMBB = NULL;
10063     overflowMBB = thisMBB;
10064     endMBB = thisMBB;
10065   } else {
10066     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10067     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10068     // If not, pull from overflow_area. (branch to overflowMBB)
10069     //
10070     //       thisMBB
10071     //         |     .
10072     //         |        .
10073     //     offsetMBB   overflowMBB
10074     //         |        .
10075     //         |     .
10076     //        endMBB
10077
10078     // Registers for the PHI in endMBB
10079     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10080     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10081
10082     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10083     MachineFunction *MF = MBB->getParent();
10084     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10085     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10086     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10087
10088     MachineFunction::iterator MBBIter = MBB;
10089     ++MBBIter;
10090
10091     // Insert the new basic blocks
10092     MF->insert(MBBIter, offsetMBB);
10093     MF->insert(MBBIter, overflowMBB);
10094     MF->insert(MBBIter, endMBB);
10095
10096     // Transfer the remainder of MBB and its successor edges to endMBB.
10097     endMBB->splice(endMBB->begin(), thisMBB,
10098                     llvm::next(MachineBasicBlock::iterator(MI)),
10099                     thisMBB->end());
10100     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10101
10102     // Make offsetMBB and overflowMBB successors of thisMBB
10103     thisMBB->addSuccessor(offsetMBB);
10104     thisMBB->addSuccessor(overflowMBB);
10105
10106     // endMBB is a successor of both offsetMBB and overflowMBB
10107     offsetMBB->addSuccessor(endMBB);
10108     overflowMBB->addSuccessor(endMBB);
10109
10110     // Load the offset value into a register
10111     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10112     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10113       .addOperand(Base)
10114       .addOperand(Scale)
10115       .addOperand(Index)
10116       .addDisp(Disp, UseFPOffset ? 4 : 0)
10117       .addOperand(Segment)
10118       .setMemRefs(MMOBegin, MMOEnd);
10119
10120     // Check if there is enough room left to pull this argument.
10121     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10122       .addReg(OffsetReg)
10123       .addImm(MaxOffset + 8 - ArgSizeA8);
10124
10125     // Branch to "overflowMBB" if offset >= max
10126     // Fall through to "offsetMBB" otherwise
10127     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10128       .addMBB(overflowMBB);
10129   }
10130
10131   // In offsetMBB, emit code to use the reg_save_area.
10132   if (offsetMBB) {
10133     assert(OffsetReg != 0);
10134
10135     // Read the reg_save_area address.
10136     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10137     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10138       .addOperand(Base)
10139       .addOperand(Scale)
10140       .addOperand(Index)
10141       .addDisp(Disp, 16)
10142       .addOperand(Segment)
10143       .setMemRefs(MMOBegin, MMOEnd);
10144
10145     // Zero-extend the offset
10146     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10147       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10148         .addImm(0)
10149         .addReg(OffsetReg)
10150         .addImm(X86::sub_32bit);
10151
10152     // Add the offset to the reg_save_area to get the final address.
10153     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10154       .addReg(OffsetReg64)
10155       .addReg(RegSaveReg);
10156
10157     // Compute the offset for the next argument
10158     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10159     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10160       .addReg(OffsetReg)
10161       .addImm(UseFPOffset ? 16 : 8);
10162
10163     // Store it back into the va_list.
10164     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10165       .addOperand(Base)
10166       .addOperand(Scale)
10167       .addOperand(Index)
10168       .addDisp(Disp, UseFPOffset ? 4 : 0)
10169       .addOperand(Segment)
10170       .addReg(NextOffsetReg)
10171       .setMemRefs(MMOBegin, MMOEnd);
10172
10173     // Jump to endMBB
10174     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10175       .addMBB(endMBB);
10176   }
10177
10178   //
10179   // Emit code to use overflow area
10180   //
10181
10182   // Load the overflow_area address into a register.
10183   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10184   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10185     .addOperand(Base)
10186     .addOperand(Scale)
10187     .addOperand(Index)
10188     .addDisp(Disp, 8)
10189     .addOperand(Segment)
10190     .setMemRefs(MMOBegin, MMOEnd);
10191
10192   // If we need to align it, do so. Otherwise, just copy the address
10193   // to OverflowDestReg.
10194   if (NeedsAlign) {
10195     // Align the overflow address
10196     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10197     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10198
10199     // aligned_addr = (addr + (align-1)) & ~(align-1)
10200     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10201       .addReg(OverflowAddrReg)
10202       .addImm(Align-1);
10203
10204     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10205       .addReg(TmpReg)
10206       .addImm(~(uint64_t)(Align-1));
10207   } else {
10208     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10209       .addReg(OverflowAddrReg);
10210   }
10211
10212   // Compute the next overflow address after this argument.
10213   // (the overflow address should be kept 8-byte aligned)
10214   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10215   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10216     .addReg(OverflowDestReg)
10217     .addImm(ArgSizeA8);
10218
10219   // Store the new overflow address.
10220   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10221     .addOperand(Base)
10222     .addOperand(Scale)
10223     .addOperand(Index)
10224     .addDisp(Disp, 8)
10225     .addOperand(Segment)
10226     .addReg(NextAddrReg)
10227     .setMemRefs(MMOBegin, MMOEnd);
10228
10229   // If we branched, emit the PHI to the front of endMBB.
10230   if (offsetMBB) {
10231     BuildMI(*endMBB, endMBB->begin(), DL,
10232             TII->get(X86::PHI), DestReg)
10233       .addReg(OffsetDestReg).addMBB(offsetMBB)
10234       .addReg(OverflowDestReg).addMBB(overflowMBB);
10235   }
10236
10237   // Erase the pseudo instruction
10238   MI->eraseFromParent();
10239
10240   return endMBB;
10241 }
10242
10243 MachineBasicBlock *
10244 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10245                                                  MachineInstr *MI,
10246                                                  MachineBasicBlock *MBB) const {
10247   // Emit code to save XMM registers to the stack. The ABI says that the
10248   // number of registers to save is given in %al, so it's theoretically
10249   // possible to do an indirect jump trick to avoid saving all of them,
10250   // however this code takes a simpler approach and just executes all
10251   // of the stores if %al is non-zero. It's less code, and it's probably
10252   // easier on the hardware branch predictor, and stores aren't all that
10253   // expensive anyway.
10254
10255   // Create the new basic blocks. One block contains all the XMM stores,
10256   // and one block is the final destination regardless of whether any
10257   // stores were performed.
10258   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10259   MachineFunction *F = MBB->getParent();
10260   MachineFunction::iterator MBBIter = MBB;
10261   ++MBBIter;
10262   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10263   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10264   F->insert(MBBIter, XMMSaveMBB);
10265   F->insert(MBBIter, EndMBB);
10266
10267   // Transfer the remainder of MBB and its successor edges to EndMBB.
10268   EndMBB->splice(EndMBB->begin(), MBB,
10269                  llvm::next(MachineBasicBlock::iterator(MI)),
10270                  MBB->end());
10271   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10272
10273   // The original block will now fall through to the XMM save block.
10274   MBB->addSuccessor(XMMSaveMBB);
10275   // The XMMSaveMBB will fall through to the end block.
10276   XMMSaveMBB->addSuccessor(EndMBB);
10277
10278   // Now add the instructions.
10279   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10280   DebugLoc DL = MI->getDebugLoc();
10281
10282   unsigned CountReg = MI->getOperand(0).getReg();
10283   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10284   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10285
10286   if (!Subtarget->isTargetWin64()) {
10287     // If %al is 0, branch around the XMM save block.
10288     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10289     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10290     MBB->addSuccessor(EndMBB);
10291   }
10292
10293   // In the XMM save block, save all the XMM argument registers.
10294   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10295     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10296     MachineMemOperand *MMO =
10297       F->getMachineMemOperand(
10298           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10299         MachineMemOperand::MOStore,
10300         /*Size=*/16, /*Align=*/16);
10301     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10302       .addFrameIndex(RegSaveFrameIndex)
10303       .addImm(/*Scale=*/1)
10304       .addReg(/*IndexReg=*/0)
10305       .addImm(/*Disp=*/Offset)
10306       .addReg(/*Segment=*/0)
10307       .addReg(MI->getOperand(i).getReg())
10308       .addMemOperand(MMO);
10309   }
10310
10311   MI->eraseFromParent();   // The pseudo instruction is gone now.
10312
10313   return EndMBB;
10314 }
10315
10316 MachineBasicBlock *
10317 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10318                                      MachineBasicBlock *BB) const {
10319   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10320   DebugLoc DL = MI->getDebugLoc();
10321
10322   // To "insert" a SELECT_CC instruction, we actually have to insert the
10323   // diamond control-flow pattern.  The incoming instruction knows the
10324   // destination vreg to set, the condition code register to branch on, the
10325   // true/false values to select between, and a branch opcode to use.
10326   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10327   MachineFunction::iterator It = BB;
10328   ++It;
10329
10330   //  thisMBB:
10331   //  ...
10332   //   TrueVal = ...
10333   //   cmpTY ccX, r1, r2
10334   //   bCC copy1MBB
10335   //   fallthrough --> copy0MBB
10336   MachineBasicBlock *thisMBB = BB;
10337   MachineFunction *F = BB->getParent();
10338   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10339   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10340   F->insert(It, copy0MBB);
10341   F->insert(It, sinkMBB);
10342
10343   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10344   // live into the sink and copy blocks.
10345   const MachineFunction *MF = BB->getParent();
10346   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10347   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10348
10349   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10350     const MachineOperand &MO = MI->getOperand(I);
10351     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10352     unsigned Reg = MO.getReg();
10353     if (Reg != X86::EFLAGS) continue;
10354     copy0MBB->addLiveIn(Reg);
10355     sinkMBB->addLiveIn(Reg);
10356   }
10357
10358   // Transfer the remainder of BB and its successor edges to sinkMBB.
10359   sinkMBB->splice(sinkMBB->begin(), BB,
10360                   llvm::next(MachineBasicBlock::iterator(MI)),
10361                   BB->end());
10362   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10363
10364   // Add the true and fallthrough blocks as its successors.
10365   BB->addSuccessor(copy0MBB);
10366   BB->addSuccessor(sinkMBB);
10367
10368   // Create the conditional branch instruction.
10369   unsigned Opc =
10370     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10371   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10372
10373   //  copy0MBB:
10374   //   %FalseValue = ...
10375   //   # fallthrough to sinkMBB
10376   copy0MBB->addSuccessor(sinkMBB);
10377
10378   //  sinkMBB:
10379   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10380   //  ...
10381   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10382           TII->get(X86::PHI), MI->getOperand(0).getReg())
10383     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10384     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10385
10386   MI->eraseFromParent();   // The pseudo instruction is gone now.
10387   return sinkMBB;
10388 }
10389
10390 MachineBasicBlock *
10391 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10392                                           MachineBasicBlock *BB) const {
10393   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10394   DebugLoc DL = MI->getDebugLoc();
10395
10396   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10397   // non-trivial part is impdef of ESP.
10398   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10399   // mingw-w64.
10400
10401   const char *StackProbeSymbol =
10402       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10403
10404   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10405     .addExternalSymbol(StackProbeSymbol)
10406     .addReg(X86::EAX, RegState::Implicit)
10407     .addReg(X86::ESP, RegState::Implicit)
10408     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10409     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10410     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10411
10412   MI->eraseFromParent();   // The pseudo instruction is gone now.
10413   return BB;
10414 }
10415
10416 MachineBasicBlock *
10417 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10418                                       MachineBasicBlock *BB) const {
10419   // This is pretty easy.  We're taking the value that we received from
10420   // our load from the relocation, sticking it in either RDI (x86-64)
10421   // or EAX and doing an indirect call.  The return value will then
10422   // be in the normal return register.
10423   const X86InstrInfo *TII
10424     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10425   DebugLoc DL = MI->getDebugLoc();
10426   MachineFunction *F = BB->getParent();
10427
10428   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10429   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10430
10431   if (Subtarget->is64Bit()) {
10432     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10433                                       TII->get(X86::MOV64rm), X86::RDI)
10434     .addReg(X86::RIP)
10435     .addImm(0).addReg(0)
10436     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10437                       MI->getOperand(3).getTargetFlags())
10438     .addReg(0);
10439     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10440     addDirectMem(MIB, X86::RDI);
10441   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10442     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10443                                       TII->get(X86::MOV32rm), X86::EAX)
10444     .addReg(0)
10445     .addImm(0).addReg(0)
10446     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10447                       MI->getOperand(3).getTargetFlags())
10448     .addReg(0);
10449     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10450     addDirectMem(MIB, X86::EAX);
10451   } else {
10452     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10453                                       TII->get(X86::MOV32rm), X86::EAX)
10454     .addReg(TII->getGlobalBaseReg(F))
10455     .addImm(0).addReg(0)
10456     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10457                       MI->getOperand(3).getTargetFlags())
10458     .addReg(0);
10459     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10460     addDirectMem(MIB, X86::EAX);
10461   }
10462
10463   MI->eraseFromParent(); // The pseudo instruction is gone now.
10464   return BB;
10465 }
10466
10467 MachineBasicBlock *
10468 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10469                                                MachineBasicBlock *BB) const {
10470   switch (MI->getOpcode()) {
10471   default: assert(false && "Unexpected instr type to insert");
10472   case X86::TAILJMPd64:
10473   case X86::TAILJMPr64:
10474   case X86::TAILJMPm64:
10475     assert(!"TAILJMP64 would not be touched here.");
10476   case X86::TCRETURNdi64:
10477   case X86::TCRETURNri64:
10478   case X86::TCRETURNmi64:
10479     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10480     // On AMD64, additional defs should be added before register allocation.
10481     if (!Subtarget->isTargetWin64()) {
10482       MI->addRegisterDefined(X86::RSI);
10483       MI->addRegisterDefined(X86::RDI);
10484       MI->addRegisterDefined(X86::XMM6);
10485       MI->addRegisterDefined(X86::XMM7);
10486       MI->addRegisterDefined(X86::XMM8);
10487       MI->addRegisterDefined(X86::XMM9);
10488       MI->addRegisterDefined(X86::XMM10);
10489       MI->addRegisterDefined(X86::XMM11);
10490       MI->addRegisterDefined(X86::XMM12);
10491       MI->addRegisterDefined(X86::XMM13);
10492       MI->addRegisterDefined(X86::XMM14);
10493       MI->addRegisterDefined(X86::XMM15);
10494     }
10495     return BB;
10496   case X86::WIN_ALLOCA:
10497     return EmitLoweredWinAlloca(MI, BB);
10498   case X86::TLSCall_32:
10499   case X86::TLSCall_64:
10500     return EmitLoweredTLSCall(MI, BB);
10501   case X86::CMOV_GR8:
10502   case X86::CMOV_FR32:
10503   case X86::CMOV_FR64:
10504   case X86::CMOV_V4F32:
10505   case X86::CMOV_V2F64:
10506   case X86::CMOV_V2I64:
10507   case X86::CMOV_GR16:
10508   case X86::CMOV_GR32:
10509   case X86::CMOV_RFP32:
10510   case X86::CMOV_RFP64:
10511   case X86::CMOV_RFP80:
10512     return EmitLoweredSelect(MI, BB);
10513
10514   case X86::FP32_TO_INT16_IN_MEM:
10515   case X86::FP32_TO_INT32_IN_MEM:
10516   case X86::FP32_TO_INT64_IN_MEM:
10517   case X86::FP64_TO_INT16_IN_MEM:
10518   case X86::FP64_TO_INT32_IN_MEM:
10519   case X86::FP64_TO_INT64_IN_MEM:
10520   case X86::FP80_TO_INT16_IN_MEM:
10521   case X86::FP80_TO_INT32_IN_MEM:
10522   case X86::FP80_TO_INT64_IN_MEM: {
10523     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10524     DebugLoc DL = MI->getDebugLoc();
10525
10526     // Change the floating point control register to use "round towards zero"
10527     // mode when truncating to an integer value.
10528     MachineFunction *F = BB->getParent();
10529     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10530     addFrameReference(BuildMI(*BB, MI, DL,
10531                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10532
10533     // Load the old value of the high byte of the control word...
10534     unsigned OldCW =
10535       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10536     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10537                       CWFrameIdx);
10538
10539     // Set the high part to be round to zero...
10540     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10541       .addImm(0xC7F);
10542
10543     // Reload the modified control word now...
10544     addFrameReference(BuildMI(*BB, MI, DL,
10545                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10546
10547     // Restore the memory image of control word to original value
10548     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10549       .addReg(OldCW);
10550
10551     // Get the X86 opcode to use.
10552     unsigned Opc;
10553     switch (MI->getOpcode()) {
10554     default: llvm_unreachable("illegal opcode!");
10555     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10556     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10557     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10558     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10559     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10560     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10561     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10562     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10563     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10564     }
10565
10566     X86AddressMode AM;
10567     MachineOperand &Op = MI->getOperand(0);
10568     if (Op.isReg()) {
10569       AM.BaseType = X86AddressMode::RegBase;
10570       AM.Base.Reg = Op.getReg();
10571     } else {
10572       AM.BaseType = X86AddressMode::FrameIndexBase;
10573       AM.Base.FrameIndex = Op.getIndex();
10574     }
10575     Op = MI->getOperand(1);
10576     if (Op.isImm())
10577       AM.Scale = Op.getImm();
10578     Op = MI->getOperand(2);
10579     if (Op.isImm())
10580       AM.IndexReg = Op.getImm();
10581     Op = MI->getOperand(3);
10582     if (Op.isGlobal()) {
10583       AM.GV = Op.getGlobal();
10584     } else {
10585       AM.Disp = Op.getImm();
10586     }
10587     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10588                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10589
10590     // Reload the original control word now.
10591     addFrameReference(BuildMI(*BB, MI, DL,
10592                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10593
10594     MI->eraseFromParent();   // The pseudo instruction is gone now.
10595     return BB;
10596   }
10597     // String/text processing lowering.
10598   case X86::PCMPISTRM128REG:
10599   case X86::VPCMPISTRM128REG:
10600     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10601   case X86::PCMPISTRM128MEM:
10602   case X86::VPCMPISTRM128MEM:
10603     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10604   case X86::PCMPESTRM128REG:
10605   case X86::VPCMPESTRM128REG:
10606     return EmitPCMP(MI, BB, 5, false /* in mem */);
10607   case X86::PCMPESTRM128MEM:
10608   case X86::VPCMPESTRM128MEM:
10609     return EmitPCMP(MI, BB, 5, true /* in mem */);
10610
10611     // Thread synchronization.
10612   case X86::MONITOR:
10613     return EmitMonitor(MI, BB);
10614   case X86::MWAIT:
10615     return EmitMwait(MI, BB);
10616
10617     // Atomic Lowering.
10618   case X86::ATOMAND32:
10619     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10620                                                X86::AND32ri, X86::MOV32rm,
10621                                                X86::LCMPXCHG32,
10622                                                X86::NOT32r, X86::EAX,
10623                                                X86::GR32RegisterClass);
10624   case X86::ATOMOR32:
10625     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10626                                                X86::OR32ri, X86::MOV32rm,
10627                                                X86::LCMPXCHG32,
10628                                                X86::NOT32r, X86::EAX,
10629                                                X86::GR32RegisterClass);
10630   case X86::ATOMXOR32:
10631     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10632                                                X86::XOR32ri, X86::MOV32rm,
10633                                                X86::LCMPXCHG32,
10634                                                X86::NOT32r, X86::EAX,
10635                                                X86::GR32RegisterClass);
10636   case X86::ATOMNAND32:
10637     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10638                                                X86::AND32ri, X86::MOV32rm,
10639                                                X86::LCMPXCHG32,
10640                                                X86::NOT32r, X86::EAX,
10641                                                X86::GR32RegisterClass, true);
10642   case X86::ATOMMIN32:
10643     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10644   case X86::ATOMMAX32:
10645     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10646   case X86::ATOMUMIN32:
10647     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10648   case X86::ATOMUMAX32:
10649     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10650
10651   case X86::ATOMAND16:
10652     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10653                                                X86::AND16ri, X86::MOV16rm,
10654                                                X86::LCMPXCHG16,
10655                                                X86::NOT16r, X86::AX,
10656                                                X86::GR16RegisterClass);
10657   case X86::ATOMOR16:
10658     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10659                                                X86::OR16ri, X86::MOV16rm,
10660                                                X86::LCMPXCHG16,
10661                                                X86::NOT16r, X86::AX,
10662                                                X86::GR16RegisterClass);
10663   case X86::ATOMXOR16:
10664     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10665                                                X86::XOR16ri, X86::MOV16rm,
10666                                                X86::LCMPXCHG16,
10667                                                X86::NOT16r, X86::AX,
10668                                                X86::GR16RegisterClass);
10669   case X86::ATOMNAND16:
10670     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10671                                                X86::AND16ri, X86::MOV16rm,
10672                                                X86::LCMPXCHG16,
10673                                                X86::NOT16r, X86::AX,
10674                                                X86::GR16RegisterClass, true);
10675   case X86::ATOMMIN16:
10676     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10677   case X86::ATOMMAX16:
10678     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10679   case X86::ATOMUMIN16:
10680     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10681   case X86::ATOMUMAX16:
10682     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10683
10684   case X86::ATOMAND8:
10685     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10686                                                X86::AND8ri, X86::MOV8rm,
10687                                                X86::LCMPXCHG8,
10688                                                X86::NOT8r, X86::AL,
10689                                                X86::GR8RegisterClass);
10690   case X86::ATOMOR8:
10691     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10692                                                X86::OR8ri, X86::MOV8rm,
10693                                                X86::LCMPXCHG8,
10694                                                X86::NOT8r, X86::AL,
10695                                                X86::GR8RegisterClass);
10696   case X86::ATOMXOR8:
10697     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10698                                                X86::XOR8ri, X86::MOV8rm,
10699                                                X86::LCMPXCHG8,
10700                                                X86::NOT8r, X86::AL,
10701                                                X86::GR8RegisterClass);
10702   case X86::ATOMNAND8:
10703     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10704                                                X86::AND8ri, X86::MOV8rm,
10705                                                X86::LCMPXCHG8,
10706                                                X86::NOT8r, X86::AL,
10707                                                X86::GR8RegisterClass, true);
10708   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10709   // This group is for 64-bit host.
10710   case X86::ATOMAND64:
10711     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10712                                                X86::AND64ri32, X86::MOV64rm,
10713                                                X86::LCMPXCHG64,
10714                                                X86::NOT64r, X86::RAX,
10715                                                X86::GR64RegisterClass);
10716   case X86::ATOMOR64:
10717     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10718                                                X86::OR64ri32, X86::MOV64rm,
10719                                                X86::LCMPXCHG64,
10720                                                X86::NOT64r, X86::RAX,
10721                                                X86::GR64RegisterClass);
10722   case X86::ATOMXOR64:
10723     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10724                                                X86::XOR64ri32, X86::MOV64rm,
10725                                                X86::LCMPXCHG64,
10726                                                X86::NOT64r, X86::RAX,
10727                                                X86::GR64RegisterClass);
10728   case X86::ATOMNAND64:
10729     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10730                                                X86::AND64ri32, X86::MOV64rm,
10731                                                X86::LCMPXCHG64,
10732                                                X86::NOT64r, X86::RAX,
10733                                                X86::GR64RegisterClass, true);
10734   case X86::ATOMMIN64:
10735     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10736   case X86::ATOMMAX64:
10737     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10738   case X86::ATOMUMIN64:
10739     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10740   case X86::ATOMUMAX64:
10741     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10742
10743   // This group does 64-bit operations on a 32-bit host.
10744   case X86::ATOMAND6432:
10745     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10746                                                X86::AND32rr, X86::AND32rr,
10747                                                X86::AND32ri, X86::AND32ri,
10748                                                false);
10749   case X86::ATOMOR6432:
10750     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10751                                                X86::OR32rr, X86::OR32rr,
10752                                                X86::OR32ri, X86::OR32ri,
10753                                                false);
10754   case X86::ATOMXOR6432:
10755     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10756                                                X86::XOR32rr, X86::XOR32rr,
10757                                                X86::XOR32ri, X86::XOR32ri,
10758                                                false);
10759   case X86::ATOMNAND6432:
10760     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10761                                                X86::AND32rr, X86::AND32rr,
10762                                                X86::AND32ri, X86::AND32ri,
10763                                                true);
10764   case X86::ATOMADD6432:
10765     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10766                                                X86::ADD32rr, X86::ADC32rr,
10767                                                X86::ADD32ri, X86::ADC32ri,
10768                                                false);
10769   case X86::ATOMSUB6432:
10770     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10771                                                X86::SUB32rr, X86::SBB32rr,
10772                                                X86::SUB32ri, X86::SBB32ri,
10773                                                false);
10774   case X86::ATOMSWAP6432:
10775     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10776                                                X86::MOV32rr, X86::MOV32rr,
10777                                                X86::MOV32ri, X86::MOV32ri,
10778                                                false);
10779   case X86::VASTART_SAVE_XMM_REGS:
10780     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10781
10782   case X86::VAARG_64:
10783     return EmitVAARG64WithCustomInserter(MI, BB);
10784   }
10785 }
10786
10787 //===----------------------------------------------------------------------===//
10788 //                           X86 Optimization Hooks
10789 //===----------------------------------------------------------------------===//
10790
10791 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10792                                                        const APInt &Mask,
10793                                                        APInt &KnownZero,
10794                                                        APInt &KnownOne,
10795                                                        const SelectionDAG &DAG,
10796                                                        unsigned Depth) const {
10797   unsigned Opc = Op.getOpcode();
10798   assert((Opc >= ISD::BUILTIN_OP_END ||
10799           Opc == ISD::INTRINSIC_WO_CHAIN ||
10800           Opc == ISD::INTRINSIC_W_CHAIN ||
10801           Opc == ISD::INTRINSIC_VOID) &&
10802          "Should use MaskedValueIsZero if you don't know whether Op"
10803          " is a target node!");
10804
10805   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10806   switch (Opc) {
10807   default: break;
10808   case X86ISD::ADD:
10809   case X86ISD::SUB:
10810   case X86ISD::ADC:
10811   case X86ISD::SBB:
10812   case X86ISD::SMUL:
10813   case X86ISD::UMUL:
10814   case X86ISD::INC:
10815   case X86ISD::DEC:
10816   case X86ISD::OR:
10817   case X86ISD::XOR:
10818   case X86ISD::AND:
10819     // These nodes' second result is a boolean.
10820     if (Op.getResNo() == 0)
10821       break;
10822     // Fallthrough
10823   case X86ISD::SETCC:
10824     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10825                                        Mask.getBitWidth() - 1);
10826     break;
10827   }
10828 }
10829
10830 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10831                                                          unsigned Depth) const {
10832   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10833   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10834     return Op.getValueType().getScalarType().getSizeInBits();
10835
10836   // Fallback case.
10837   return 1;
10838 }
10839
10840 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10841 /// node is a GlobalAddress + offset.
10842 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10843                                        const GlobalValue* &GA,
10844                                        int64_t &Offset) const {
10845   if (N->getOpcode() == X86ISD::Wrapper) {
10846     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10847       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10848       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10849       return true;
10850     }
10851   }
10852   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10853 }
10854
10855 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10856 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10857 /// if the load addresses are consecutive, non-overlapping, and in the right
10858 /// order.
10859 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10860                                      TargetLowering::DAGCombinerInfo &DCI) {
10861   DebugLoc dl = N->getDebugLoc();
10862   EVT VT = N->getValueType(0);
10863
10864   if (VT.getSizeInBits() != 128)
10865     return SDValue();
10866
10867   // Don't create instructions with illegal types after legalize types has run.
10868   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10869   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10870     return SDValue();
10871
10872   SmallVector<SDValue, 16> Elts;
10873   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10874     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10875
10876   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10877 }
10878
10879 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10880 /// generation and convert it from being a bunch of shuffles and extracts
10881 /// to a simple store and scalar loads to extract the elements.
10882 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10883                                                 const TargetLowering &TLI) {
10884   SDValue InputVector = N->getOperand(0);
10885
10886   // Only operate on vectors of 4 elements, where the alternative shuffling
10887   // gets to be more expensive.
10888   if (InputVector.getValueType() != MVT::v4i32)
10889     return SDValue();
10890
10891   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10892   // single use which is a sign-extend or zero-extend, and all elements are
10893   // used.
10894   SmallVector<SDNode *, 4> Uses;
10895   unsigned ExtractedElements = 0;
10896   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10897        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10898     if (UI.getUse().getResNo() != InputVector.getResNo())
10899       return SDValue();
10900
10901     SDNode *Extract = *UI;
10902     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10903       return SDValue();
10904
10905     if (Extract->getValueType(0) != MVT::i32)
10906       return SDValue();
10907     if (!Extract->hasOneUse())
10908       return SDValue();
10909     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10910         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10911       return SDValue();
10912     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10913       return SDValue();
10914
10915     // Record which element was extracted.
10916     ExtractedElements |=
10917       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10918
10919     Uses.push_back(Extract);
10920   }
10921
10922   // If not all the elements were used, this may not be worthwhile.
10923   if (ExtractedElements != 15)
10924     return SDValue();
10925
10926   // Ok, we've now decided to do the transformation.
10927   DebugLoc dl = InputVector.getDebugLoc();
10928
10929   // Store the value to a temporary stack slot.
10930   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10931   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10932                             MachinePointerInfo(), false, false, 0);
10933
10934   // Replace each use (extract) with a load of the appropriate element.
10935   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10936        UE = Uses.end(); UI != UE; ++UI) {
10937     SDNode *Extract = *UI;
10938
10939     // Compute the element's address.
10940     SDValue Idx = Extract->getOperand(1);
10941     unsigned EltSize =
10942         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10943     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10944     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10945
10946     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10947                                      StackPtr, OffsetVal);
10948
10949     // Load the scalar.
10950     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10951                                      ScalarAddr, MachinePointerInfo(),
10952                                      false, false, 0);
10953
10954     // Replace the exact with the load.
10955     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10956   }
10957
10958   // The replacement was made in place; don't return anything.
10959   return SDValue();
10960 }
10961
10962 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10963 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10964                                     const X86Subtarget *Subtarget) {
10965   DebugLoc DL = N->getDebugLoc();
10966   SDValue Cond = N->getOperand(0);
10967   // Get the LHS/RHS of the select.
10968   SDValue LHS = N->getOperand(1);
10969   SDValue RHS = N->getOperand(2);
10970
10971   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10972   // instructions match the semantics of the common C idiom x<y?x:y but not
10973   // x<=y?x:y, because of how they handle negative zero (which can be
10974   // ignored in unsafe-math mode).
10975   if (Subtarget->hasSSE2() &&
10976       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10977       Cond.getOpcode() == ISD::SETCC) {
10978     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10979
10980     unsigned Opcode = 0;
10981     // Check for x CC y ? x : y.
10982     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10983         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10984       switch (CC) {
10985       default: break;
10986       case ISD::SETULT:
10987         // Converting this to a min would handle NaNs incorrectly, and swapping
10988         // the operands would cause it to handle comparisons between positive
10989         // and negative zero incorrectly.
10990         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10991           if (!UnsafeFPMath &&
10992               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10993             break;
10994           std::swap(LHS, RHS);
10995         }
10996         Opcode = X86ISD::FMIN;
10997         break;
10998       case ISD::SETOLE:
10999         // Converting this to a min would handle comparisons between positive
11000         // and negative zero incorrectly.
11001         if (!UnsafeFPMath &&
11002             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11003           break;
11004         Opcode = X86ISD::FMIN;
11005         break;
11006       case ISD::SETULE:
11007         // Converting this to a min would handle both negative zeros and NaNs
11008         // incorrectly, but we can swap the operands to fix both.
11009         std::swap(LHS, RHS);
11010       case ISD::SETOLT:
11011       case ISD::SETLT:
11012       case ISD::SETLE:
11013         Opcode = X86ISD::FMIN;
11014         break;
11015
11016       case ISD::SETOGE:
11017         // Converting this to a max would handle comparisons between positive
11018         // and negative zero incorrectly.
11019         if (!UnsafeFPMath &&
11020             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11021           break;
11022         Opcode = X86ISD::FMAX;
11023         break;
11024       case ISD::SETUGT:
11025         // Converting this to a max would handle NaNs incorrectly, and swapping
11026         // the operands would cause it to handle comparisons between positive
11027         // and negative zero incorrectly.
11028         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11029           if (!UnsafeFPMath &&
11030               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11031             break;
11032           std::swap(LHS, RHS);
11033         }
11034         Opcode = X86ISD::FMAX;
11035         break;
11036       case ISD::SETUGE:
11037         // Converting this to a max would handle both negative zeros and NaNs
11038         // incorrectly, but we can swap the operands to fix both.
11039         std::swap(LHS, RHS);
11040       case ISD::SETOGT:
11041       case ISD::SETGT:
11042       case ISD::SETGE:
11043         Opcode = X86ISD::FMAX;
11044         break;
11045       }
11046     // Check for x CC y ? y : x -- a min/max with reversed arms.
11047     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11048                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11049       switch (CC) {
11050       default: break;
11051       case ISD::SETOGE:
11052         // Converting this to a min would handle comparisons between positive
11053         // and negative zero incorrectly, and swapping the operands would
11054         // cause it to handle NaNs incorrectly.
11055         if (!UnsafeFPMath &&
11056             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11057           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11058             break;
11059           std::swap(LHS, RHS);
11060         }
11061         Opcode = X86ISD::FMIN;
11062         break;
11063       case ISD::SETUGT:
11064         // Converting this to a min would handle NaNs incorrectly.
11065         if (!UnsafeFPMath &&
11066             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11067           break;
11068         Opcode = X86ISD::FMIN;
11069         break;
11070       case ISD::SETUGE:
11071         // Converting this to a min would handle both negative zeros and NaNs
11072         // incorrectly, but we can swap the operands to fix both.
11073         std::swap(LHS, RHS);
11074       case ISD::SETOGT:
11075       case ISD::SETGT:
11076       case ISD::SETGE:
11077         Opcode = X86ISD::FMIN;
11078         break;
11079
11080       case ISD::SETULT:
11081         // Converting this to a max would handle NaNs incorrectly.
11082         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11083           break;
11084         Opcode = X86ISD::FMAX;
11085         break;
11086       case ISD::SETOLE:
11087         // Converting this to a max would handle comparisons between positive
11088         // and negative zero incorrectly, and swapping the operands would
11089         // cause it to handle NaNs incorrectly.
11090         if (!UnsafeFPMath &&
11091             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11092           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11093             break;
11094           std::swap(LHS, RHS);
11095         }
11096         Opcode = X86ISD::FMAX;
11097         break;
11098       case ISD::SETULE:
11099         // Converting this to a max would handle both negative zeros and NaNs
11100         // incorrectly, but we can swap the operands to fix both.
11101         std::swap(LHS, RHS);
11102       case ISD::SETOLT:
11103       case ISD::SETLT:
11104       case ISD::SETLE:
11105         Opcode = X86ISD::FMAX;
11106         break;
11107       }
11108     }
11109
11110     if (Opcode)
11111       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11112   }
11113
11114   // If this is a select between two integer constants, try to do some
11115   // optimizations.
11116   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11117     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11118       // Don't do this for crazy integer types.
11119       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11120         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11121         // so that TrueC (the true value) is larger than FalseC.
11122         bool NeedsCondInvert = false;
11123
11124         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11125             // Efficiently invertible.
11126             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11127              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11128               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11129           NeedsCondInvert = true;
11130           std::swap(TrueC, FalseC);
11131         }
11132
11133         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11134         if (FalseC->getAPIntValue() == 0 &&
11135             TrueC->getAPIntValue().isPowerOf2()) {
11136           if (NeedsCondInvert) // Invert the condition if needed.
11137             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11138                                DAG.getConstant(1, Cond.getValueType()));
11139
11140           // Zero extend the condition if needed.
11141           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11142
11143           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11144           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11145                              DAG.getConstant(ShAmt, MVT::i8));
11146         }
11147
11148         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11149         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11150           if (NeedsCondInvert) // Invert the condition if needed.
11151             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11152                                DAG.getConstant(1, Cond.getValueType()));
11153
11154           // Zero extend the condition if needed.
11155           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11156                              FalseC->getValueType(0), Cond);
11157           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11158                              SDValue(FalseC, 0));
11159         }
11160
11161         // Optimize cases that will turn into an LEA instruction.  This requires
11162         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11163         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11164           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11165           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11166
11167           bool isFastMultiplier = false;
11168           if (Diff < 10) {
11169             switch ((unsigned char)Diff) {
11170               default: break;
11171               case 1:  // result = add base, cond
11172               case 2:  // result = lea base(    , cond*2)
11173               case 3:  // result = lea base(cond, cond*2)
11174               case 4:  // result = lea base(    , cond*4)
11175               case 5:  // result = lea base(cond, cond*4)
11176               case 8:  // result = lea base(    , cond*8)
11177               case 9:  // result = lea base(cond, cond*8)
11178                 isFastMultiplier = true;
11179                 break;
11180             }
11181           }
11182
11183           if (isFastMultiplier) {
11184             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11185             if (NeedsCondInvert) // Invert the condition if needed.
11186               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11187                                  DAG.getConstant(1, Cond.getValueType()));
11188
11189             // Zero extend the condition if needed.
11190             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11191                                Cond);
11192             // Scale the condition by the difference.
11193             if (Diff != 1)
11194               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11195                                  DAG.getConstant(Diff, Cond.getValueType()));
11196
11197             // Add the base if non-zero.
11198             if (FalseC->getAPIntValue() != 0)
11199               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11200                                  SDValue(FalseC, 0));
11201             return Cond;
11202           }
11203         }
11204       }
11205   }
11206
11207   return SDValue();
11208 }
11209
11210 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11211 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11212                                   TargetLowering::DAGCombinerInfo &DCI) {
11213   DebugLoc DL = N->getDebugLoc();
11214
11215   // If the flag operand isn't dead, don't touch this CMOV.
11216   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11217     return SDValue();
11218
11219   // If this is a select between two integer constants, try to do some
11220   // optimizations.  Note that the operands are ordered the opposite of SELECT
11221   // operands.
11222   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11223     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11224       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11225       // larger than FalseC (the false value).
11226       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11227
11228       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11229         CC = X86::GetOppositeBranchCondition(CC);
11230         std::swap(TrueC, FalseC);
11231       }
11232
11233       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11234       // This is efficient for any integer data type (including i8/i16) and
11235       // shift amount.
11236       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11237         SDValue Cond = N->getOperand(3);
11238         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11239                            DAG.getConstant(CC, MVT::i8), Cond);
11240
11241         // Zero extend the condition if needed.
11242         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11243
11244         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11245         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11246                            DAG.getConstant(ShAmt, MVT::i8));
11247         if (N->getNumValues() == 2)  // Dead flag value?
11248           return DCI.CombineTo(N, Cond, SDValue());
11249         return Cond;
11250       }
11251
11252       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11253       // for any integer data type, including i8/i16.
11254       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11255         SDValue Cond = N->getOperand(3);
11256         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11257                            DAG.getConstant(CC, MVT::i8), Cond);
11258
11259         // Zero extend the condition if needed.
11260         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11261                            FalseC->getValueType(0), Cond);
11262         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11263                            SDValue(FalseC, 0));
11264
11265         if (N->getNumValues() == 2)  // Dead flag value?
11266           return DCI.CombineTo(N, Cond, SDValue());
11267         return Cond;
11268       }
11269
11270       // Optimize cases that will turn into an LEA instruction.  This requires
11271       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11272       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11273         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11274         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11275
11276         bool isFastMultiplier = false;
11277         if (Diff < 10) {
11278           switch ((unsigned char)Diff) {
11279           default: break;
11280           case 1:  // result = add base, cond
11281           case 2:  // result = lea base(    , cond*2)
11282           case 3:  // result = lea base(cond, cond*2)
11283           case 4:  // result = lea base(    , cond*4)
11284           case 5:  // result = lea base(cond, cond*4)
11285           case 8:  // result = lea base(    , cond*8)
11286           case 9:  // result = lea base(cond, cond*8)
11287             isFastMultiplier = true;
11288             break;
11289           }
11290         }
11291
11292         if (isFastMultiplier) {
11293           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11294           SDValue Cond = N->getOperand(3);
11295           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11296                              DAG.getConstant(CC, MVT::i8), Cond);
11297           // Zero extend the condition if needed.
11298           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11299                              Cond);
11300           // Scale the condition by the difference.
11301           if (Diff != 1)
11302             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11303                                DAG.getConstant(Diff, Cond.getValueType()));
11304
11305           // Add the base if non-zero.
11306           if (FalseC->getAPIntValue() != 0)
11307             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11308                                SDValue(FalseC, 0));
11309           if (N->getNumValues() == 2)  // Dead flag value?
11310             return DCI.CombineTo(N, Cond, SDValue());
11311           return Cond;
11312         }
11313       }
11314     }
11315   }
11316   return SDValue();
11317 }
11318
11319
11320 /// PerformMulCombine - Optimize a single multiply with constant into two
11321 /// in order to implement it with two cheaper instructions, e.g.
11322 /// LEA + SHL, LEA + LEA.
11323 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11324                                  TargetLowering::DAGCombinerInfo &DCI) {
11325   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11326     return SDValue();
11327
11328   EVT VT = N->getValueType(0);
11329   if (VT != MVT::i64)
11330     return SDValue();
11331
11332   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11333   if (!C)
11334     return SDValue();
11335   uint64_t MulAmt = C->getZExtValue();
11336   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11337     return SDValue();
11338
11339   uint64_t MulAmt1 = 0;
11340   uint64_t MulAmt2 = 0;
11341   if ((MulAmt % 9) == 0) {
11342     MulAmt1 = 9;
11343     MulAmt2 = MulAmt / 9;
11344   } else if ((MulAmt % 5) == 0) {
11345     MulAmt1 = 5;
11346     MulAmt2 = MulAmt / 5;
11347   } else if ((MulAmt % 3) == 0) {
11348     MulAmt1 = 3;
11349     MulAmt2 = MulAmt / 3;
11350   }
11351   if (MulAmt2 &&
11352       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11353     DebugLoc DL = N->getDebugLoc();
11354
11355     if (isPowerOf2_64(MulAmt2) &&
11356         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11357       // If second multiplifer is pow2, issue it first. We want the multiply by
11358       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11359       // is an add.
11360       std::swap(MulAmt1, MulAmt2);
11361
11362     SDValue NewMul;
11363     if (isPowerOf2_64(MulAmt1))
11364       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11365                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11366     else
11367       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11368                            DAG.getConstant(MulAmt1, VT));
11369
11370     if (isPowerOf2_64(MulAmt2))
11371       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11372                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11373     else
11374       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11375                            DAG.getConstant(MulAmt2, VT));
11376
11377     // Do not add new nodes to DAG combiner worklist.
11378     DCI.CombineTo(N, NewMul, false);
11379   }
11380   return SDValue();
11381 }
11382
11383 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11384   SDValue N0 = N->getOperand(0);
11385   SDValue N1 = N->getOperand(1);
11386   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11387   EVT VT = N0.getValueType();
11388
11389   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11390   // since the result of setcc_c is all zero's or all ones.
11391   if (N1C && N0.getOpcode() == ISD::AND &&
11392       N0.getOperand(1).getOpcode() == ISD::Constant) {
11393     SDValue N00 = N0.getOperand(0);
11394     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11395         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11396           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11397          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11398       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11399       APInt ShAmt = N1C->getAPIntValue();
11400       Mask = Mask.shl(ShAmt);
11401       if (Mask != 0)
11402         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11403                            N00, DAG.getConstant(Mask, VT));
11404     }
11405   }
11406
11407   return SDValue();
11408 }
11409
11410 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11411 ///                       when possible.
11412 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11413                                    const X86Subtarget *Subtarget) {
11414   EVT VT = N->getValueType(0);
11415   if (!VT.isVector() && VT.isInteger() &&
11416       N->getOpcode() == ISD::SHL)
11417     return PerformSHLCombine(N, DAG);
11418
11419   // On X86 with SSE2 support, we can transform this to a vector shift if
11420   // all elements are shifted by the same amount.  We can't do this in legalize
11421   // because the a constant vector is typically transformed to a constant pool
11422   // so we have no knowledge of the shift amount.
11423   if (!Subtarget->hasSSE2())
11424     return SDValue();
11425
11426   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11427     return SDValue();
11428
11429   SDValue ShAmtOp = N->getOperand(1);
11430   EVT EltVT = VT.getVectorElementType();
11431   DebugLoc DL = N->getDebugLoc();
11432   SDValue BaseShAmt = SDValue();
11433   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11434     unsigned NumElts = VT.getVectorNumElements();
11435     unsigned i = 0;
11436     for (; i != NumElts; ++i) {
11437       SDValue Arg = ShAmtOp.getOperand(i);
11438       if (Arg.getOpcode() == ISD::UNDEF) continue;
11439       BaseShAmt = Arg;
11440       break;
11441     }
11442     for (; i != NumElts; ++i) {
11443       SDValue Arg = ShAmtOp.getOperand(i);
11444       if (Arg.getOpcode() == ISD::UNDEF) continue;
11445       if (Arg != BaseShAmt) {
11446         return SDValue();
11447       }
11448     }
11449   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11450              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11451     SDValue InVec = ShAmtOp.getOperand(0);
11452     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11453       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11454       unsigned i = 0;
11455       for (; i != NumElts; ++i) {
11456         SDValue Arg = InVec.getOperand(i);
11457         if (Arg.getOpcode() == ISD::UNDEF) continue;
11458         BaseShAmt = Arg;
11459         break;
11460       }
11461     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11462        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11463          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11464          if (C->getZExtValue() == SplatIdx)
11465            BaseShAmt = InVec.getOperand(1);
11466        }
11467     }
11468     if (BaseShAmt.getNode() == 0)
11469       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11470                               DAG.getIntPtrConstant(0));
11471   } else
11472     return SDValue();
11473
11474   // The shift amount is an i32.
11475   if (EltVT.bitsGT(MVT::i32))
11476     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11477   else if (EltVT.bitsLT(MVT::i32))
11478     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11479
11480   // The shift amount is identical so we can do a vector shift.
11481   SDValue  ValOp = N->getOperand(0);
11482   switch (N->getOpcode()) {
11483   default:
11484     llvm_unreachable("Unknown shift opcode!");
11485     break;
11486   case ISD::SHL:
11487     if (VT == MVT::v2i64)
11488       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11489                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11490                          ValOp, BaseShAmt);
11491     if (VT == MVT::v4i32)
11492       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11493                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11494                          ValOp, BaseShAmt);
11495     if (VT == MVT::v8i16)
11496       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11497                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11498                          ValOp, BaseShAmt);
11499     break;
11500   case ISD::SRA:
11501     if (VT == MVT::v4i32)
11502       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11503                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11504                          ValOp, BaseShAmt);
11505     if (VT == MVT::v8i16)
11506       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11507                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11508                          ValOp, BaseShAmt);
11509     break;
11510   case ISD::SRL:
11511     if (VT == MVT::v2i64)
11512       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11513                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11514                          ValOp, BaseShAmt);
11515     if (VT == MVT::v4i32)
11516       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11517                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11518                          ValOp, BaseShAmt);
11519     if (VT ==  MVT::v8i16)
11520       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11521                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11522                          ValOp, BaseShAmt);
11523     break;
11524   }
11525   return SDValue();
11526 }
11527
11528
11529 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11530                                  TargetLowering::DAGCombinerInfo &DCI,
11531                                  const X86Subtarget *Subtarget) {
11532   if (DCI.isBeforeLegalizeOps())
11533     return SDValue();
11534
11535   // Want to form PANDN nodes, in the hopes of then easily combining them with
11536   // OR and AND nodes to form PBLEND/PSIGN.
11537   EVT VT = N->getValueType(0);
11538   if (VT != MVT::v2i64)
11539     return SDValue();
11540
11541   SDValue N0 = N->getOperand(0);
11542   SDValue N1 = N->getOperand(1);
11543   DebugLoc DL = N->getDebugLoc();
11544
11545   // Check LHS for vnot
11546   if (N0.getOpcode() == ISD::XOR &&
11547       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11548     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11549
11550   // Check RHS for vnot
11551   if (N1.getOpcode() == ISD::XOR &&
11552       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11553     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11554
11555   return SDValue();
11556 }
11557
11558 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11559                                 TargetLowering::DAGCombinerInfo &DCI,
11560                                 const X86Subtarget *Subtarget) {
11561   if (DCI.isBeforeLegalizeOps())
11562     return SDValue();
11563
11564   EVT VT = N->getValueType(0);
11565   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11566     return SDValue();
11567
11568   SDValue N0 = N->getOperand(0);
11569   SDValue N1 = N->getOperand(1);
11570
11571   // look for psign/blend
11572   if (Subtarget->hasSSSE3()) {
11573     if (VT == MVT::v2i64) {
11574       // Canonicalize pandn to RHS
11575       if (N0.getOpcode() == X86ISD::PANDN)
11576         std::swap(N0, N1);
11577       // or (and (m, x), (pandn m, y))
11578       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11579         SDValue Mask = N1.getOperand(0);
11580         SDValue X    = N1.getOperand(1);
11581         SDValue Y;
11582         if (N0.getOperand(0) == Mask)
11583           Y = N0.getOperand(1);
11584         if (N0.getOperand(1) == Mask)
11585           Y = N0.getOperand(0);
11586
11587         // Check to see if the mask appeared in both the AND and PANDN and
11588         if (!Y.getNode())
11589           return SDValue();
11590
11591         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11592         if (Mask.getOpcode() != ISD::BITCAST ||
11593             X.getOpcode() != ISD::BITCAST ||
11594             Y.getOpcode() != ISD::BITCAST)
11595           return SDValue();
11596
11597         // Look through mask bitcast.
11598         Mask = Mask.getOperand(0);
11599         EVT MaskVT = Mask.getValueType();
11600
11601         // Validate that the Mask operand is a vector sra node.  The sra node
11602         // will be an intrinsic.
11603         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11604           return SDValue();
11605
11606         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11607         // there is no psrai.b
11608         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11609         case Intrinsic::x86_sse2_psrai_w:
11610         case Intrinsic::x86_sse2_psrai_d:
11611           break;
11612         default: return SDValue();
11613         }
11614
11615         // Check that the SRA is all signbits.
11616         SDValue SraC = Mask.getOperand(2);
11617         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11618         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11619         if ((SraAmt + 1) != EltBits)
11620           return SDValue();
11621
11622         DebugLoc DL = N->getDebugLoc();
11623
11624         // Now we know we at least have a plendvb with the mask val.  See if
11625         // we can form a psignb/w/d.
11626         // psign = x.type == y.type == mask.type && y = sub(0, x);
11627         X = X.getOperand(0);
11628         Y = Y.getOperand(0);
11629         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11630             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11631             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11632           unsigned Opc = 0;
11633           switch (EltBits) {
11634           case 8: Opc = X86ISD::PSIGNB; break;
11635           case 16: Opc = X86ISD::PSIGNW; break;
11636           case 32: Opc = X86ISD::PSIGND; break;
11637           default: break;
11638           }
11639           if (Opc) {
11640             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11641             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11642           }
11643         }
11644         // PBLENDVB only available on SSE 4.1
11645         if (!Subtarget->hasSSE41())
11646           return SDValue();
11647
11648         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11649         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11650         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11651         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11652         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11653       }
11654     }
11655   }
11656
11657   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11658   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11659     std::swap(N0, N1);
11660   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11661     return SDValue();
11662   if (!N0.hasOneUse() || !N1.hasOneUse())
11663     return SDValue();
11664
11665   SDValue ShAmt0 = N0.getOperand(1);
11666   if (ShAmt0.getValueType() != MVT::i8)
11667     return SDValue();
11668   SDValue ShAmt1 = N1.getOperand(1);
11669   if (ShAmt1.getValueType() != MVT::i8)
11670     return SDValue();
11671   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11672     ShAmt0 = ShAmt0.getOperand(0);
11673   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11674     ShAmt1 = ShAmt1.getOperand(0);
11675
11676   DebugLoc DL = N->getDebugLoc();
11677   unsigned Opc = X86ISD::SHLD;
11678   SDValue Op0 = N0.getOperand(0);
11679   SDValue Op1 = N1.getOperand(0);
11680   if (ShAmt0.getOpcode() == ISD::SUB) {
11681     Opc = X86ISD::SHRD;
11682     std::swap(Op0, Op1);
11683     std::swap(ShAmt0, ShAmt1);
11684   }
11685
11686   unsigned Bits = VT.getSizeInBits();
11687   if (ShAmt1.getOpcode() == ISD::SUB) {
11688     SDValue Sum = ShAmt1.getOperand(0);
11689     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11690       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11691       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11692         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11693       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11694         return DAG.getNode(Opc, DL, VT,
11695                            Op0, Op1,
11696                            DAG.getNode(ISD::TRUNCATE, DL,
11697                                        MVT::i8, ShAmt0));
11698     }
11699   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11700     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11701     if (ShAmt0C &&
11702         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11703       return DAG.getNode(Opc, DL, VT,
11704                          N0.getOperand(0), N1.getOperand(0),
11705                          DAG.getNode(ISD::TRUNCATE, DL,
11706                                        MVT::i8, ShAmt0));
11707   }
11708
11709   return SDValue();
11710 }
11711
11712 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11713 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11714                                    const X86Subtarget *Subtarget) {
11715   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11716   // the FP state in cases where an emms may be missing.
11717   // A preferable solution to the general problem is to figure out the right
11718   // places to insert EMMS.  This qualifies as a quick hack.
11719
11720   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11721   StoreSDNode *St = cast<StoreSDNode>(N);
11722   EVT VT = St->getValue().getValueType();
11723   if (VT.getSizeInBits() != 64)
11724     return SDValue();
11725
11726   const Function *F = DAG.getMachineFunction().getFunction();
11727   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11728   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11729     && Subtarget->hasSSE2();
11730   if ((VT.isVector() ||
11731        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11732       isa<LoadSDNode>(St->getValue()) &&
11733       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11734       St->getChain().hasOneUse() && !St->isVolatile()) {
11735     SDNode* LdVal = St->getValue().getNode();
11736     LoadSDNode *Ld = 0;
11737     int TokenFactorIndex = -1;
11738     SmallVector<SDValue, 8> Ops;
11739     SDNode* ChainVal = St->getChain().getNode();
11740     // Must be a store of a load.  We currently handle two cases:  the load
11741     // is a direct child, and it's under an intervening TokenFactor.  It is
11742     // possible to dig deeper under nested TokenFactors.
11743     if (ChainVal == LdVal)
11744       Ld = cast<LoadSDNode>(St->getChain());
11745     else if (St->getValue().hasOneUse() &&
11746              ChainVal->getOpcode() == ISD::TokenFactor) {
11747       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11748         if (ChainVal->getOperand(i).getNode() == LdVal) {
11749           TokenFactorIndex = i;
11750           Ld = cast<LoadSDNode>(St->getValue());
11751         } else
11752           Ops.push_back(ChainVal->getOperand(i));
11753       }
11754     }
11755
11756     if (!Ld || !ISD::isNormalLoad(Ld))
11757       return SDValue();
11758
11759     // If this is not the MMX case, i.e. we are just turning i64 load/store
11760     // into f64 load/store, avoid the transformation if there are multiple
11761     // uses of the loaded value.
11762     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11763       return SDValue();
11764
11765     DebugLoc LdDL = Ld->getDebugLoc();
11766     DebugLoc StDL = N->getDebugLoc();
11767     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11768     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11769     // pair instead.
11770     if (Subtarget->is64Bit() || F64IsLegal) {
11771       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11772       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11773                                   Ld->getPointerInfo(), Ld->isVolatile(),
11774                                   Ld->isNonTemporal(), Ld->getAlignment());
11775       SDValue NewChain = NewLd.getValue(1);
11776       if (TokenFactorIndex != -1) {
11777         Ops.push_back(NewChain);
11778         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11779                                Ops.size());
11780       }
11781       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11782                           St->getPointerInfo(),
11783                           St->isVolatile(), St->isNonTemporal(),
11784                           St->getAlignment());
11785     }
11786
11787     // Otherwise, lower to two pairs of 32-bit loads / stores.
11788     SDValue LoAddr = Ld->getBasePtr();
11789     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11790                                  DAG.getConstant(4, MVT::i32));
11791
11792     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11793                                Ld->getPointerInfo(),
11794                                Ld->isVolatile(), Ld->isNonTemporal(),
11795                                Ld->getAlignment());
11796     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11797                                Ld->getPointerInfo().getWithOffset(4),
11798                                Ld->isVolatile(), Ld->isNonTemporal(),
11799                                MinAlign(Ld->getAlignment(), 4));
11800
11801     SDValue NewChain = LoLd.getValue(1);
11802     if (TokenFactorIndex != -1) {
11803       Ops.push_back(LoLd);
11804       Ops.push_back(HiLd);
11805       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11806                              Ops.size());
11807     }
11808
11809     LoAddr = St->getBasePtr();
11810     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11811                          DAG.getConstant(4, MVT::i32));
11812
11813     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11814                                 St->getPointerInfo(),
11815                                 St->isVolatile(), St->isNonTemporal(),
11816                                 St->getAlignment());
11817     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11818                                 St->getPointerInfo().getWithOffset(4),
11819                                 St->isVolatile(),
11820                                 St->isNonTemporal(),
11821                                 MinAlign(St->getAlignment(), 4));
11822     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11823   }
11824   return SDValue();
11825 }
11826
11827 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11828 /// X86ISD::FXOR nodes.
11829 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11830   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11831   // F[X]OR(0.0, x) -> x
11832   // F[X]OR(x, 0.0) -> x
11833   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11834     if (C->getValueAPF().isPosZero())
11835       return N->getOperand(1);
11836   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11837     if (C->getValueAPF().isPosZero())
11838       return N->getOperand(0);
11839   return SDValue();
11840 }
11841
11842 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11843 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11844   // FAND(0.0, x) -> 0.0
11845   // FAND(x, 0.0) -> 0.0
11846   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11847     if (C->getValueAPF().isPosZero())
11848       return N->getOperand(0);
11849   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11850     if (C->getValueAPF().isPosZero())
11851       return N->getOperand(1);
11852   return SDValue();
11853 }
11854
11855 static SDValue PerformBTCombine(SDNode *N,
11856                                 SelectionDAG &DAG,
11857                                 TargetLowering::DAGCombinerInfo &DCI) {
11858   // BT ignores high bits in the bit index operand.
11859   SDValue Op1 = N->getOperand(1);
11860   if (Op1.hasOneUse()) {
11861     unsigned BitWidth = Op1.getValueSizeInBits();
11862     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11863     APInt KnownZero, KnownOne;
11864     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11865                                           !DCI.isBeforeLegalizeOps());
11866     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11867     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11868         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11869       DCI.CommitTargetLoweringOpt(TLO);
11870   }
11871   return SDValue();
11872 }
11873
11874 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11875   SDValue Op = N->getOperand(0);
11876   if (Op.getOpcode() == ISD::BITCAST)
11877     Op = Op.getOperand(0);
11878   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11879   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11880       VT.getVectorElementType().getSizeInBits() ==
11881       OpVT.getVectorElementType().getSizeInBits()) {
11882     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11883   }
11884   return SDValue();
11885 }
11886
11887 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11888   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11889   //           (and (i32 x86isd::setcc_carry), 1)
11890   // This eliminates the zext. This transformation is necessary because
11891   // ISD::SETCC is always legalized to i8.
11892   DebugLoc dl = N->getDebugLoc();
11893   SDValue N0 = N->getOperand(0);
11894   EVT VT = N->getValueType(0);
11895   if (N0.getOpcode() == ISD::AND &&
11896       N0.hasOneUse() &&
11897       N0.getOperand(0).hasOneUse()) {
11898     SDValue N00 = N0.getOperand(0);
11899     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11900       return SDValue();
11901     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11902     if (!C || C->getZExtValue() != 1)
11903       return SDValue();
11904     return DAG.getNode(ISD::AND, dl, VT,
11905                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11906                                    N00.getOperand(0), N00.getOperand(1)),
11907                        DAG.getConstant(1, VT));
11908   }
11909
11910   return SDValue();
11911 }
11912
11913 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11914 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11915   unsigned X86CC = N->getConstantOperandVal(0);
11916   SDValue EFLAG = N->getOperand(1);
11917   DebugLoc DL = N->getDebugLoc();
11918
11919   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11920   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11921   // cases.
11922   if (X86CC == X86::COND_B)
11923     return DAG.getNode(ISD::AND, DL, MVT::i8,
11924                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11925                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11926                        DAG.getConstant(1, MVT::i8));
11927
11928   return SDValue();
11929 }
11930
11931 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11932 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11933                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11934   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11935   // the result is either zero or one (depending on the input carry bit).
11936   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11937   if (X86::isZeroNode(N->getOperand(0)) &&
11938       X86::isZeroNode(N->getOperand(1)) &&
11939       // We don't have a good way to replace an EFLAGS use, so only do this when
11940       // dead right now.
11941       SDValue(N, 1).use_empty()) {
11942     DebugLoc DL = N->getDebugLoc();
11943     EVT VT = N->getValueType(0);
11944     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11945     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11946                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11947                                            DAG.getConstant(X86::COND_B,MVT::i8),
11948                                            N->getOperand(2)),
11949                                DAG.getConstant(1, VT));
11950     return DCI.CombineTo(N, Res1, CarryOut);
11951   }
11952
11953   return SDValue();
11954 }
11955
11956 // fold (add Y, (sete  X, 0)) -> adc  0, Y
11957 //      (add Y, (setne X, 0)) -> sbb -1, Y
11958 //      (sub (sete  X, 0), Y) -> sbb  0, Y
11959 //      (sub (setne X, 0), Y) -> adc -1, Y
11960 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11961   DebugLoc DL = N->getDebugLoc();
11962
11963   // Look through ZExts.
11964   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11965   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11966     return SDValue();
11967
11968   SDValue SetCC = Ext.getOperand(0);
11969   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11970     return SDValue();
11971
11972   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11973   if (CC != X86::COND_E && CC != X86::COND_NE)
11974     return SDValue();
11975
11976   SDValue Cmp = SetCC.getOperand(1);
11977   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11978       !X86::isZeroNode(Cmp.getOperand(1)) ||
11979       !Cmp.getOperand(0).getValueType().isInteger())
11980     return SDValue();
11981
11982   SDValue CmpOp0 = Cmp.getOperand(0);
11983   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11984                                DAG.getConstant(1, CmpOp0.getValueType()));
11985
11986   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11987   if (CC == X86::COND_NE)
11988     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11989                        DL, OtherVal.getValueType(), OtherVal,
11990                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11991   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11992                      DL, OtherVal.getValueType(), OtherVal,
11993                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11994 }
11995
11996 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11997                                              DAGCombinerInfo &DCI) const {
11998   SelectionDAG &DAG = DCI.DAG;
11999   switch (N->getOpcode()) {
12000   default: break;
12001   case ISD::EXTRACT_VECTOR_ELT:
12002     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12003   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12004   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12005   case ISD::ADD:
12006   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12007   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12008   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12009   case ISD::SHL:
12010   case ISD::SRA:
12011   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12012   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12013   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12014   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12015   case X86ISD::FXOR:
12016   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12017   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12018   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12019   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12020   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12021   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12022   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12023   case X86ISD::SHUFPD:
12024   case X86ISD::PALIGN:
12025   case X86ISD::PUNPCKHBW:
12026   case X86ISD::PUNPCKHWD:
12027   case X86ISD::PUNPCKHDQ:
12028   case X86ISD::PUNPCKHQDQ:
12029   case X86ISD::UNPCKHPS:
12030   case X86ISD::UNPCKHPD:
12031   case X86ISD::PUNPCKLBW:
12032   case X86ISD::PUNPCKLWD:
12033   case X86ISD::PUNPCKLDQ:
12034   case X86ISD::PUNPCKLQDQ:
12035   case X86ISD::UNPCKLPS:
12036   case X86ISD::UNPCKLPD:
12037   case X86ISD::VUNPCKLPS:
12038   case X86ISD::VUNPCKLPD:
12039   case X86ISD::VUNPCKLPSY:
12040   case X86ISD::VUNPCKLPDY:
12041   case X86ISD::MOVHLPS:
12042   case X86ISD::MOVLHPS:
12043   case X86ISD::PSHUFD:
12044   case X86ISD::PSHUFHW:
12045   case X86ISD::PSHUFLW:
12046   case X86ISD::MOVSS:
12047   case X86ISD::MOVSD:
12048   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12049   }
12050
12051   return SDValue();
12052 }
12053
12054 /// isTypeDesirableForOp - Return true if the target has native support for
12055 /// the specified value type and it is 'desirable' to use the type for the
12056 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12057 /// instruction encodings are longer and some i16 instructions are slow.
12058 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12059   if (!isTypeLegal(VT))
12060     return false;
12061   if (VT != MVT::i16)
12062     return true;
12063
12064   switch (Opc) {
12065   default:
12066     return true;
12067   case ISD::LOAD:
12068   case ISD::SIGN_EXTEND:
12069   case ISD::ZERO_EXTEND:
12070   case ISD::ANY_EXTEND:
12071   case ISD::SHL:
12072   case ISD::SRL:
12073   case ISD::SUB:
12074   case ISD::ADD:
12075   case ISD::MUL:
12076   case ISD::AND:
12077   case ISD::OR:
12078   case ISD::XOR:
12079     return false;
12080   }
12081 }
12082
12083 /// IsDesirableToPromoteOp - This method query the target whether it is
12084 /// beneficial for dag combiner to promote the specified node. If true, it
12085 /// should return the desired promotion type by reference.
12086 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12087   EVT VT = Op.getValueType();
12088   if (VT != MVT::i16)
12089     return false;
12090
12091   bool Promote = false;
12092   bool Commute = false;
12093   switch (Op.getOpcode()) {
12094   default: break;
12095   case ISD::LOAD: {
12096     LoadSDNode *LD = cast<LoadSDNode>(Op);
12097     // If the non-extending load has a single use and it's not live out, then it
12098     // might be folded.
12099     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12100                                                      Op.hasOneUse()*/) {
12101       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12102              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12103         // The only case where we'd want to promote LOAD (rather then it being
12104         // promoted as an operand is when it's only use is liveout.
12105         if (UI->getOpcode() != ISD::CopyToReg)
12106           return false;
12107       }
12108     }
12109     Promote = true;
12110     break;
12111   }
12112   case ISD::SIGN_EXTEND:
12113   case ISD::ZERO_EXTEND:
12114   case ISD::ANY_EXTEND:
12115     Promote = true;
12116     break;
12117   case ISD::SHL:
12118   case ISD::SRL: {
12119     SDValue N0 = Op.getOperand(0);
12120     // Look out for (store (shl (load), x)).
12121     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12122       return false;
12123     Promote = true;
12124     break;
12125   }
12126   case ISD::ADD:
12127   case ISD::MUL:
12128   case ISD::AND:
12129   case ISD::OR:
12130   case ISD::XOR:
12131     Commute = true;
12132     // fallthrough
12133   case ISD::SUB: {
12134     SDValue N0 = Op.getOperand(0);
12135     SDValue N1 = Op.getOperand(1);
12136     if (!Commute && MayFoldLoad(N1))
12137       return false;
12138     // Avoid disabling potential load folding opportunities.
12139     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12140       return false;
12141     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12142       return false;
12143     Promote = true;
12144   }
12145   }
12146
12147   PVT = MVT::i32;
12148   return Promote;
12149 }
12150
12151 //===----------------------------------------------------------------------===//
12152 //                           X86 Inline Assembly Support
12153 //===----------------------------------------------------------------------===//
12154
12155 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12156   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12157
12158   std::string AsmStr = IA->getAsmString();
12159
12160   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12161   SmallVector<StringRef, 4> AsmPieces;
12162   SplitString(AsmStr, AsmPieces, ";\n");
12163
12164   switch (AsmPieces.size()) {
12165   default: return false;
12166   case 1:
12167     AsmStr = AsmPieces[0];
12168     AsmPieces.clear();
12169     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12170
12171     // FIXME: this should verify that we are targetting a 486 or better.  If not,
12172     // we will turn this bswap into something that will be lowered to logical ops
12173     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12174     // so don't worry about this.
12175     // bswap $0
12176     if (AsmPieces.size() == 2 &&
12177         (AsmPieces[0] == "bswap" ||
12178          AsmPieces[0] == "bswapq" ||
12179          AsmPieces[0] == "bswapl") &&
12180         (AsmPieces[1] == "$0" ||
12181          AsmPieces[1] == "${0:q}")) {
12182       // No need to check constraints, nothing other than the equivalent of
12183       // "=r,0" would be valid here.
12184       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12185       if (!Ty || Ty->getBitWidth() % 16 != 0)
12186         return false;
12187       return IntrinsicLowering::LowerToByteSwap(CI);
12188     }
12189     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12190     if (CI->getType()->isIntegerTy(16) &&
12191         AsmPieces.size() == 3 &&
12192         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12193         AsmPieces[1] == "$$8," &&
12194         AsmPieces[2] == "${0:w}" &&
12195         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12196       AsmPieces.clear();
12197       const std::string &ConstraintsStr = IA->getConstraintString();
12198       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12199       std::sort(AsmPieces.begin(), AsmPieces.end());
12200       if (AsmPieces.size() == 4 &&
12201           AsmPieces[0] == "~{cc}" &&
12202           AsmPieces[1] == "~{dirflag}" &&
12203           AsmPieces[2] == "~{flags}" &&
12204           AsmPieces[3] == "~{fpsr}") {
12205         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12206         if (!Ty || Ty->getBitWidth() % 16 != 0)
12207           return false;
12208         return IntrinsicLowering::LowerToByteSwap(CI);
12209       }
12210     }
12211     break;
12212   case 3:
12213     if (CI->getType()->isIntegerTy(32) &&
12214         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12215       SmallVector<StringRef, 4> Words;
12216       SplitString(AsmPieces[0], Words, " \t,");
12217       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12218           Words[2] == "${0:w}") {
12219         Words.clear();
12220         SplitString(AsmPieces[1], Words, " \t,");
12221         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12222             Words[2] == "$0") {
12223           Words.clear();
12224           SplitString(AsmPieces[2], Words, " \t,");
12225           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12226               Words[2] == "${0:w}") {
12227             AsmPieces.clear();
12228             const std::string &ConstraintsStr = IA->getConstraintString();
12229             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12230             std::sort(AsmPieces.begin(), AsmPieces.end());
12231             if (AsmPieces.size() == 4 &&
12232                 AsmPieces[0] == "~{cc}" &&
12233                 AsmPieces[1] == "~{dirflag}" &&
12234                 AsmPieces[2] == "~{flags}" &&
12235                 AsmPieces[3] == "~{fpsr}") {
12236               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12237               if (!Ty || Ty->getBitWidth() % 16 != 0)
12238                 return false;
12239               return IntrinsicLowering::LowerToByteSwap(CI);
12240             }
12241           }
12242         }
12243       }
12244     }
12245
12246     if (CI->getType()->isIntegerTy(64)) {
12247       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12248       if (Constraints.size() >= 2 &&
12249           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12250           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12251         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12252         SmallVector<StringRef, 4> Words;
12253         SplitString(AsmPieces[0], Words, " \t");
12254         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12255           Words.clear();
12256           SplitString(AsmPieces[1], Words, " \t");
12257           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12258             Words.clear();
12259             SplitString(AsmPieces[2], Words, " \t,");
12260             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12261                 Words[2] == "%edx") {
12262               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12263               if (!Ty || Ty->getBitWidth() % 16 != 0)
12264                 return false;
12265               return IntrinsicLowering::LowerToByteSwap(CI);
12266             }
12267           }
12268         }
12269       }
12270     }
12271     break;
12272   }
12273   return false;
12274 }
12275
12276
12277
12278 /// getConstraintType - Given a constraint letter, return the type of
12279 /// constraint it is for this target.
12280 X86TargetLowering::ConstraintType
12281 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12282   if (Constraint.size() == 1) {
12283     switch (Constraint[0]) {
12284     case 'R':
12285     case 'q':
12286     case 'Q':
12287     case 'f':
12288     case 't':
12289     case 'u':
12290     case 'y':
12291     case 'x':
12292     case 'Y':
12293       return C_RegisterClass;
12294     case 'a':
12295     case 'b':
12296     case 'c':
12297     case 'd':
12298     case 'S':
12299     case 'D':
12300     case 'A':
12301       return C_Register;
12302     case 'I':
12303     case 'J':
12304     case 'K':
12305     case 'L':
12306     case 'M':
12307     case 'N':
12308     case 'G':
12309     case 'C':
12310     case 'e':
12311     case 'Z':
12312       return C_Other;
12313     default:
12314       break;
12315     }
12316   }
12317   return TargetLowering::getConstraintType(Constraint);
12318 }
12319
12320 /// Examine constraint type and operand type and determine a weight value.
12321 /// This object must already have been set up with the operand type
12322 /// and the current alternative constraint selected.
12323 TargetLowering::ConstraintWeight
12324   X86TargetLowering::getSingleConstraintMatchWeight(
12325     AsmOperandInfo &info, const char *constraint) const {
12326   ConstraintWeight weight = CW_Invalid;
12327   Value *CallOperandVal = info.CallOperandVal;
12328     // If we don't have a value, we can't do a match,
12329     // but allow it at the lowest weight.
12330   if (CallOperandVal == NULL)
12331     return CW_Default;
12332   const Type *type = CallOperandVal->getType();
12333   // Look at the constraint type.
12334   switch (*constraint) {
12335   default:
12336     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12337   case 'R':
12338   case 'q':
12339   case 'Q':
12340   case 'a':
12341   case 'b':
12342   case 'c':
12343   case 'd':
12344   case 'S':
12345   case 'D':
12346   case 'A':
12347     if (CallOperandVal->getType()->isIntegerTy())
12348       weight = CW_SpecificReg;
12349     break;
12350   case 'f':
12351   case 't':
12352   case 'u':
12353       if (type->isFloatingPointTy())
12354         weight = CW_SpecificReg;
12355       break;
12356   case 'y':
12357       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12358         weight = CW_SpecificReg;
12359       break;
12360   case 'x':
12361   case 'Y':
12362     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12363       weight = CW_Register;
12364     break;
12365   case 'I':
12366     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12367       if (C->getZExtValue() <= 31)
12368         weight = CW_Constant;
12369     }
12370     break;
12371   case 'J':
12372     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12373       if (C->getZExtValue() <= 63)
12374         weight = CW_Constant;
12375     }
12376     break;
12377   case 'K':
12378     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12379       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12380         weight = CW_Constant;
12381     }
12382     break;
12383   case 'L':
12384     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12385       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12386         weight = CW_Constant;
12387     }
12388     break;
12389   case 'M':
12390     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12391       if (C->getZExtValue() <= 3)
12392         weight = CW_Constant;
12393     }
12394     break;
12395   case 'N':
12396     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12397       if (C->getZExtValue() <= 0xff)
12398         weight = CW_Constant;
12399     }
12400     break;
12401   case 'G':
12402   case 'C':
12403     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12404       weight = CW_Constant;
12405     }
12406     break;
12407   case 'e':
12408     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12409       if ((C->getSExtValue() >= -0x80000000LL) &&
12410           (C->getSExtValue() <= 0x7fffffffLL))
12411         weight = CW_Constant;
12412     }
12413     break;
12414   case 'Z':
12415     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12416       if (C->getZExtValue() <= 0xffffffff)
12417         weight = CW_Constant;
12418     }
12419     break;
12420   }
12421   return weight;
12422 }
12423
12424 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12425 /// with another that has more specific requirements based on the type of the
12426 /// corresponding operand.
12427 const char *X86TargetLowering::
12428 LowerXConstraint(EVT ConstraintVT) const {
12429   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12430   // 'f' like normal targets.
12431   if (ConstraintVT.isFloatingPoint()) {
12432     if (Subtarget->hasXMMInt())
12433       return "Y";
12434     if (Subtarget->hasXMM())
12435       return "x";
12436   }
12437
12438   return TargetLowering::LowerXConstraint(ConstraintVT);
12439 }
12440
12441 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12442 /// vector.  If it is invalid, don't add anything to Ops.
12443 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12444                                                      char Constraint,
12445                                                      std::vector<SDValue>&Ops,
12446                                                      SelectionDAG &DAG) const {
12447   SDValue Result(0, 0);
12448
12449   switch (Constraint) {
12450   default: break;
12451   case 'I':
12452     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12453       if (C->getZExtValue() <= 31) {
12454         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12455         break;
12456       }
12457     }
12458     return;
12459   case 'J':
12460     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12461       if (C->getZExtValue() <= 63) {
12462         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12463         break;
12464       }
12465     }
12466     return;
12467   case 'K':
12468     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12469       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12470         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12471         break;
12472       }
12473     }
12474     return;
12475   case 'N':
12476     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12477       if (C->getZExtValue() <= 255) {
12478         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12479         break;
12480       }
12481     }
12482     return;
12483   case 'e': {
12484     // 32-bit signed value
12485     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12486       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12487                                            C->getSExtValue())) {
12488         // Widen to 64 bits here to get it sign extended.
12489         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12490         break;
12491       }
12492     // FIXME gcc accepts some relocatable values here too, but only in certain
12493     // memory models; it's complicated.
12494     }
12495     return;
12496   }
12497   case 'Z': {
12498     // 32-bit unsigned value
12499     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12500       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12501                                            C->getZExtValue())) {
12502         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12503         break;
12504       }
12505     }
12506     // FIXME gcc accepts some relocatable values here too, but only in certain
12507     // memory models; it's complicated.
12508     return;
12509   }
12510   case 'i': {
12511     // Literal immediates are always ok.
12512     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12513       // Widen to 64 bits here to get it sign extended.
12514       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12515       break;
12516     }
12517
12518     // In any sort of PIC mode addresses need to be computed at runtime by
12519     // adding in a register or some sort of table lookup.  These can't
12520     // be used as immediates.
12521     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12522       return;
12523
12524     // If we are in non-pic codegen mode, we allow the address of a global (with
12525     // an optional displacement) to be used with 'i'.
12526     GlobalAddressSDNode *GA = 0;
12527     int64_t Offset = 0;
12528
12529     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12530     while (1) {
12531       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12532         Offset += GA->getOffset();
12533         break;
12534       } else if (Op.getOpcode() == ISD::ADD) {
12535         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12536           Offset += C->getZExtValue();
12537           Op = Op.getOperand(0);
12538           continue;
12539         }
12540       } else if (Op.getOpcode() == ISD::SUB) {
12541         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12542           Offset += -C->getZExtValue();
12543           Op = Op.getOperand(0);
12544           continue;
12545         }
12546       }
12547
12548       // Otherwise, this isn't something we can handle, reject it.
12549       return;
12550     }
12551
12552     const GlobalValue *GV = GA->getGlobal();
12553     // If we require an extra load to get this address, as in PIC mode, we
12554     // can't accept it.
12555     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12556                                                         getTargetMachine())))
12557       return;
12558
12559     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12560                                         GA->getValueType(0), Offset);
12561     break;
12562   }
12563   }
12564
12565   if (Result.getNode()) {
12566     Ops.push_back(Result);
12567     return;
12568   }
12569   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12570 }
12571
12572 std::vector<unsigned> X86TargetLowering::
12573 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12574                                   EVT VT) const {
12575   if (Constraint.size() == 1) {
12576     // FIXME: not handling fp-stack yet!
12577     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12578     default: break;  // Unknown constraint letter
12579     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12580       if (Subtarget->is64Bit()) {
12581         if (VT == MVT::i32)
12582           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12583                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12584                                        X86::R10D,X86::R11D,X86::R12D,
12585                                        X86::R13D,X86::R14D,X86::R15D,
12586                                        X86::EBP, X86::ESP, 0);
12587         else if (VT == MVT::i16)
12588           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12589                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12590                                        X86::R10W,X86::R11W,X86::R12W,
12591                                        X86::R13W,X86::R14W,X86::R15W,
12592                                        X86::BP,  X86::SP, 0);
12593         else if (VT == MVT::i8)
12594           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12595                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12596                                        X86::R10B,X86::R11B,X86::R12B,
12597                                        X86::R13B,X86::R14B,X86::R15B,
12598                                        X86::BPL, X86::SPL, 0);
12599
12600         else if (VT == MVT::i64)
12601           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12602                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12603                                        X86::R10, X86::R11, X86::R12,
12604                                        X86::R13, X86::R14, X86::R15,
12605                                        X86::RBP, X86::RSP, 0);
12606
12607         break;
12608       }
12609       // 32-bit fallthrough
12610     case 'Q':   // Q_REGS
12611       if (VT == MVT::i32)
12612         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12613       else if (VT == MVT::i16)
12614         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12615       else if (VT == MVT::i8)
12616         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12617       else if (VT == MVT::i64)
12618         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12619       break;
12620     }
12621   }
12622
12623   return std::vector<unsigned>();
12624 }
12625
12626 std::pair<unsigned, const TargetRegisterClass*>
12627 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12628                                                 EVT VT) const {
12629   // First, see if this is a constraint that directly corresponds to an LLVM
12630   // register class.
12631   if (Constraint.size() == 1) {
12632     // GCC Constraint Letters
12633     switch (Constraint[0]) {
12634     default: break;
12635     case 'r':   // GENERAL_REGS
12636     case 'l':   // INDEX_REGS
12637       if (VT == MVT::i8)
12638         return std::make_pair(0U, X86::GR8RegisterClass);
12639       if (VT == MVT::i16)
12640         return std::make_pair(0U, X86::GR16RegisterClass);
12641       if (VT == MVT::i32 || !Subtarget->is64Bit())
12642         return std::make_pair(0U, X86::GR32RegisterClass);
12643       return std::make_pair(0U, X86::GR64RegisterClass);
12644     case 'R':   // LEGACY_REGS
12645       if (VT == MVT::i8)
12646         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12647       if (VT == MVT::i16)
12648         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12649       if (VT == MVT::i32 || !Subtarget->is64Bit())
12650         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12651       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12652     case 'f':  // FP Stack registers.
12653       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12654       // value to the correct fpstack register class.
12655       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12656         return std::make_pair(0U, X86::RFP32RegisterClass);
12657       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12658         return std::make_pair(0U, X86::RFP64RegisterClass);
12659       return std::make_pair(0U, X86::RFP80RegisterClass);
12660     case 'y':   // MMX_REGS if MMX allowed.
12661       if (!Subtarget->hasMMX()) break;
12662       return std::make_pair(0U, X86::VR64RegisterClass);
12663     case 'Y':   // SSE_REGS if SSE2 allowed
12664       if (!Subtarget->hasXMMInt()) break;
12665       // FALL THROUGH.
12666     case 'x':   // SSE_REGS if SSE1 allowed
12667       if (!Subtarget->hasXMM()) break;
12668
12669       switch (VT.getSimpleVT().SimpleTy) {
12670       default: break;
12671       // Scalar SSE types.
12672       case MVT::f32:
12673       case MVT::i32:
12674         return std::make_pair(0U, X86::FR32RegisterClass);
12675       case MVT::f64:
12676       case MVT::i64:
12677         return std::make_pair(0U, X86::FR64RegisterClass);
12678       // Vector types.
12679       case MVT::v16i8:
12680       case MVT::v8i16:
12681       case MVT::v4i32:
12682       case MVT::v2i64:
12683       case MVT::v4f32:
12684       case MVT::v2f64:
12685         return std::make_pair(0U, X86::VR128RegisterClass);
12686       }
12687       break;
12688     }
12689   }
12690
12691   // Use the default implementation in TargetLowering to convert the register
12692   // constraint into a member of a register class.
12693   std::pair<unsigned, const TargetRegisterClass*> Res;
12694   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12695
12696   // Not found as a standard register?
12697   if (Res.second == 0) {
12698     // Map st(0) -> st(7) -> ST0
12699     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12700         tolower(Constraint[1]) == 's' &&
12701         tolower(Constraint[2]) == 't' &&
12702         Constraint[3] == '(' &&
12703         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12704         Constraint[5] == ')' &&
12705         Constraint[6] == '}') {
12706
12707       Res.first = X86::ST0+Constraint[4]-'0';
12708       Res.second = X86::RFP80RegisterClass;
12709       return Res;
12710     }
12711
12712     // GCC allows "st(0)" to be called just plain "st".
12713     if (StringRef("{st}").equals_lower(Constraint)) {
12714       Res.first = X86::ST0;
12715       Res.second = X86::RFP80RegisterClass;
12716       return Res;
12717     }
12718
12719     // flags -> EFLAGS
12720     if (StringRef("{flags}").equals_lower(Constraint)) {
12721       Res.first = X86::EFLAGS;
12722       Res.second = X86::CCRRegisterClass;
12723       return Res;
12724     }
12725
12726     // 'A' means EAX + EDX.
12727     if (Constraint == "A") {
12728       Res.first = X86::EAX;
12729       Res.second = X86::GR32_ADRegisterClass;
12730       return Res;
12731     }
12732     return Res;
12733   }
12734
12735   // Otherwise, check to see if this is a register class of the wrong value
12736   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12737   // turn into {ax},{dx}.
12738   if (Res.second->hasType(VT))
12739     return Res;   // Correct type already, nothing to do.
12740
12741   // All of the single-register GCC register classes map their values onto
12742   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12743   // really want an 8-bit or 32-bit register, map to the appropriate register
12744   // class and return the appropriate register.
12745   if (Res.second == X86::GR16RegisterClass) {
12746     if (VT == MVT::i8) {
12747       unsigned DestReg = 0;
12748       switch (Res.first) {
12749       default: break;
12750       case X86::AX: DestReg = X86::AL; break;
12751       case X86::DX: DestReg = X86::DL; break;
12752       case X86::CX: DestReg = X86::CL; break;
12753       case X86::BX: DestReg = X86::BL; break;
12754       }
12755       if (DestReg) {
12756         Res.first = DestReg;
12757         Res.second = X86::GR8RegisterClass;
12758       }
12759     } else if (VT == MVT::i32) {
12760       unsigned DestReg = 0;
12761       switch (Res.first) {
12762       default: break;
12763       case X86::AX: DestReg = X86::EAX; break;
12764       case X86::DX: DestReg = X86::EDX; break;
12765       case X86::CX: DestReg = X86::ECX; break;
12766       case X86::BX: DestReg = X86::EBX; break;
12767       case X86::SI: DestReg = X86::ESI; break;
12768       case X86::DI: DestReg = X86::EDI; break;
12769       case X86::BP: DestReg = X86::EBP; break;
12770       case X86::SP: DestReg = X86::ESP; break;
12771       }
12772       if (DestReg) {
12773         Res.first = DestReg;
12774         Res.second = X86::GR32RegisterClass;
12775       }
12776     } else if (VT == MVT::i64) {
12777       unsigned DestReg = 0;
12778       switch (Res.first) {
12779       default: break;
12780       case X86::AX: DestReg = X86::RAX; break;
12781       case X86::DX: DestReg = X86::RDX; break;
12782       case X86::CX: DestReg = X86::RCX; break;
12783       case X86::BX: DestReg = X86::RBX; break;
12784       case X86::SI: DestReg = X86::RSI; break;
12785       case X86::DI: DestReg = X86::RDI; break;
12786       case X86::BP: DestReg = X86::RBP; break;
12787       case X86::SP: DestReg = X86::RSP; break;
12788       }
12789       if (DestReg) {
12790         Res.first = DestReg;
12791         Res.second = X86::GR64RegisterClass;
12792       }
12793     }
12794   } else if (Res.second == X86::FR32RegisterClass ||
12795              Res.second == X86::FR64RegisterClass ||
12796              Res.second == X86::VR128RegisterClass) {
12797     // Handle references to XMM physical registers that got mapped into the
12798     // wrong class.  This can happen with constraints like {xmm0} where the
12799     // target independent register mapper will just pick the first match it can
12800     // find, ignoring the required type.
12801     if (VT == MVT::f32)
12802       Res.second = X86::FR32RegisterClass;
12803     else if (VT == MVT::f64)
12804       Res.second = X86::FR64RegisterClass;
12805     else if (X86::VR128RegisterClass->hasType(VT))
12806       Res.second = X86::VR128RegisterClass;
12807   }
12808
12809   return Res;
12810 }