Ger rid of some dead code.
[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 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/CommandLine.h"
42 using namespace llvm;
43
44 static cl::opt<bool>
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
46
47 // Forward declarations.
48 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
49                        SDValue V2);
50
51 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
52   : TargetLowering(TM) {
53   Subtarget = &TM.getSubtarget<X86Subtarget>();
54   X86ScalarSSEf64 = Subtarget->hasSSE2();
55   X86ScalarSSEf32 = Subtarget->hasSSE1();
56   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
57
58   RegInfo = TM.getRegisterInfo();
59   TD = getTargetData();
60
61   // Set up the TargetLowering object.
62
63   // X86 is weird, it always uses i8 for shift amounts and setcc results.
64   setShiftAmountType(MVT::i8);
65   setBooleanContents(ZeroOrOneBooleanContent);
66   setSchedulingPreference(SchedulingForRegPressure);
67   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
68   setStackPointerRegisterToSaveRestore(X86StackPtr);
69
70   if (Subtarget->isTargetDarwin()) {
71     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
72     setUseUnderscoreSetJmp(false);
73     setUseUnderscoreLongJmp(false);
74   } else if (Subtarget->isTargetMingw()) {
75     // MS runtime is weird: it exports _setjmp, but longjmp!
76     setUseUnderscoreSetJmp(true);
77     setUseUnderscoreLongJmp(false);
78   } else {
79     setUseUnderscoreSetJmp(true);
80     setUseUnderscoreLongJmp(true);
81   }
82
83   // Set up the register classes.
84   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
85   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
86   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
87   if (Subtarget->is64Bit())
88     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
89
90   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
91
92   // We don't accept any truncstore of integer registers.
93   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
94   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
95   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
96   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
97   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
98   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
99
100   // SETOEQ and SETUNE require checking two conditions.
101   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
102   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
103   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
104   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
105   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
106   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
107
108   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
109   // operation.
110   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
111   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
112   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
113
114   if (Subtarget->is64Bit()) {
115     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
116     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
117   } else if (!UseSoftFloat) {
118     if (X86ScalarSSEf64) {
119       // We have an impenetrably clever algorithm for ui64->double only.
120       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
121     }
122     // We have an algorithm for SSE2, and we turn this into a 64-bit
123     // FILD for other targets.
124     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
125   }
126
127   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
128   // this operation.
129   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
130   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
131
132   if (!UseSoftFloat && !NoImplicitFloat) {
133     // SSE has no i16 to fp conversion, only i32
134     if (X86ScalarSSEf32) {
135       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
136       // f32 and f64 cases are Legal, f80 case is not
137       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
138     } else {
139       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
140       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
141     }
142   } else {
143     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
144     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
145   }
146
147   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
148   // are Legal, f80 is custom lowered.
149   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
150   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
151
152   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
153   // this operation.
154   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
155   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
156
157   if (X86ScalarSSEf32) {
158     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
159     // f32 and f64 cases are Legal, f80 case is not
160     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
161   } else {
162     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
163     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
164   }
165
166   // Handle FP_TO_UINT by promoting the destination to a larger signed
167   // conversion.
168   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
169   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
170   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
171
172   if (Subtarget->is64Bit()) {
173     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
174     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
175   } else if (!UseSoftFloat) {
176     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
177       // Expand FP_TO_UINT into a select.
178       // FIXME: We would like to use a Custom expander here eventually to do
179       // the optimal thing for SSE vs. the default expansion in the legalizer.
180       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
181     else
182       // With SSE3 we can use fisttpll to convert to a signed i64; without
183       // SSE, we're stuck with a fistpll.
184       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
185   }
186
187   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
188   if (!X86ScalarSSEf64) {
189     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
190     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
191   }
192
193   // Scalar integer divide and remainder are lowered to use operations that
194   // produce two results, to match the available instructions. This exposes
195   // the two-result form to trivial CSE, which is able to combine x/y and x%y
196   // into a single instruction.
197   //
198   // Scalar integer multiply-high is also lowered to use two-result
199   // operations, to match the available instructions. However, plain multiply
200   // (low) operations are left as Legal, as there are single-result
201   // instructions for this in x86. Using the two-result multiply instructions
202   // when both high and low results are needed must be arranged by dagcombine.
203   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
204   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
205   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
206   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
207   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
208   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
209   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
210   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
211   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
212   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
213   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
214   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
215   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
216   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
217   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
218   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
219   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
220   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
221   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
222   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
223   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
224   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
225   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
226   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
227
228   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
229   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
230   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
231   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
232   if (Subtarget->is64Bit())
233     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
234   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
235   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
236   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
237   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
238   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
239   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
240   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
241   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
242
243   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
244   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
245   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
246   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
247   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
248   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
249   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
250   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
251   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
252   if (Subtarget->is64Bit()) {
253     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
254     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
255     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
256   }
257
258   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
259   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
260
261   // These should be promoted to a larger select which is supported.
262   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
263   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
264   // X86 wants to expand cmov itself.
265   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
266   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
267   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
268   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
269   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
270   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
271   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
272   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
273   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
274   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
275   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
276   if (Subtarget->is64Bit()) {
277     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
278     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
279   }
280   // X86 ret instruction may pop stack.
281   setOperationAction(ISD::RET             , MVT::Other, Custom);
282   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
283
284   // Darwin ABI issue.
285   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
286   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
287   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
288   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
289   if (Subtarget->is64Bit())
290     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
291   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
292   if (Subtarget->is64Bit()) {
293     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
294     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
295     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
296     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
297   }
298   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
299   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
300   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
301   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
302   if (Subtarget->is64Bit()) {
303     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
304     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
305     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
306   }
307
308   if (Subtarget->hasSSE1())
309     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
310
311   if (!Subtarget->hasSSE2())
312     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
313
314   // Expand certain atomics
315   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
316   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
317   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
318   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
319
320   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
321   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
322   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
323   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
324
325   if (!Subtarget->is64Bit()) {
326     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
327     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
328     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
329     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
330     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
331     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
332     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
333   }
334
335   // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
336   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
337   // FIXME - use subtarget debug flags
338   if (!Subtarget->isTargetDarwin() &&
339       !Subtarget->isTargetELF() &&
340       !Subtarget->isTargetCygMing()) {
341     setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
342     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
343   }
344
345   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
346   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
347   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
348   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
349   if (Subtarget->is64Bit()) {
350     setExceptionPointerRegister(X86::RAX);
351     setExceptionSelectorRegister(X86::RDX);
352   } else {
353     setExceptionPointerRegister(X86::EAX);
354     setExceptionSelectorRegister(X86::EDX);
355   }
356   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
357   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
358
359   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
360
361   setOperationAction(ISD::TRAP, MVT::Other, Legal);
362
363   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
364   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
365   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
366   if (Subtarget->is64Bit()) {
367     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
368     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
369   } else {
370     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
371     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
372   }
373
374   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
375   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
376   if (Subtarget->is64Bit())
377     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
378   if (Subtarget->isTargetCygMing())
379     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
380   else
381     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
382
383   if (!UseSoftFloat && X86ScalarSSEf64) {
384     // f32 and f64 use SSE.
385     // Set up the FP register classes.
386     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
387     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
388
389     // Use ANDPD to simulate FABS.
390     setOperationAction(ISD::FABS , MVT::f64, Custom);
391     setOperationAction(ISD::FABS , MVT::f32, Custom);
392
393     // Use XORP to simulate FNEG.
394     setOperationAction(ISD::FNEG , MVT::f64, Custom);
395     setOperationAction(ISD::FNEG , MVT::f32, Custom);
396
397     // Use ANDPD and ORPD to simulate FCOPYSIGN.
398     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
399     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
400
401     // We don't support sin/cos/fmod
402     setOperationAction(ISD::FSIN , MVT::f64, Expand);
403     setOperationAction(ISD::FCOS , MVT::f64, Expand);
404     setOperationAction(ISD::FSIN , MVT::f32, Expand);
405     setOperationAction(ISD::FCOS , MVT::f32, Expand);
406
407     // Expand FP immediates into loads from the stack, except for the special
408     // cases we handle.
409     addLegalFPImmediate(APFloat(+0.0)); // xorpd
410     addLegalFPImmediate(APFloat(+0.0f)); // xorps
411   } else if (!UseSoftFloat && X86ScalarSSEf32) {
412     // Use SSE for f32, x87 for f64.
413     // Set up the FP register classes.
414     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
415     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
416
417     // Use ANDPS to simulate FABS.
418     setOperationAction(ISD::FABS , MVT::f32, Custom);
419
420     // Use XORP to simulate FNEG.
421     setOperationAction(ISD::FNEG , MVT::f32, Custom);
422
423     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
424
425     // Use ANDPS and ORPS to simulate FCOPYSIGN.
426     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
427     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
428
429     // We don't support sin/cos/fmod
430     setOperationAction(ISD::FSIN , MVT::f32, Expand);
431     setOperationAction(ISD::FCOS , MVT::f32, Expand);
432
433     // Special cases we handle for FP constants.
434     addLegalFPImmediate(APFloat(+0.0f)); // xorps
435     addLegalFPImmediate(APFloat(+0.0)); // FLD0
436     addLegalFPImmediate(APFloat(+1.0)); // FLD1
437     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
438     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
439
440     if (!UnsafeFPMath) {
441       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
442       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
443     }
444   } else if (!UseSoftFloat) {
445     // f32 and f64 in x87.
446     // Set up the FP register classes.
447     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
448     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
449
450     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
451     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
452     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
453     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
454
455     if (!UnsafeFPMath) {
456       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
457       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
458     }
459     addLegalFPImmediate(APFloat(+0.0)); // FLD0
460     addLegalFPImmediate(APFloat(+1.0)); // FLD1
461     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
462     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
463     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
464     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
465     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
466     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
467   }
468
469   // Long double always uses X87.
470   if (!UseSoftFloat) {
471     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
472     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
473     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
474     {
475       bool ignored;
476       APFloat TmpFlt(+0.0);
477       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
478                      &ignored);
479       addLegalFPImmediate(TmpFlt);  // FLD0
480       TmpFlt.changeSign();
481       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
482       APFloat TmpFlt2(+1.0);
483       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
484                       &ignored);
485       addLegalFPImmediate(TmpFlt2);  // FLD1
486       TmpFlt2.changeSign();
487       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
488     }
489
490     if (!UnsafeFPMath) {
491       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
492       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
493     }
494   }
495
496   // Always use a library call for pow.
497   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
498   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
499   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
500
501   setOperationAction(ISD::FLOG, MVT::f80, Expand);
502   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
503   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
504   setOperationAction(ISD::FEXP, MVT::f80, Expand);
505   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
506
507   // First set operation action for all vector types to either promote
508   // (for widening) or expand (for scalarization). Then we will selectively
509   // turn on ones that can be effectively codegen'd.
510   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
511        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
512     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
513     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
514     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
515     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
516     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
517     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
518     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
519     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
520     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
521     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
522     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
523     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
524     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
525     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
526     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
527     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
528     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
529     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
530     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
531     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
532     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
533     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
534     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
535     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
536     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
537     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
538     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
539     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
540     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
541     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
542     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
543     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
544     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
545     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
546     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
547     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
548     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
549     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
556   }
557
558   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
559   // with -msoft-float, disable use of MMX as well.
560   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
561     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
562     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
563     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
564     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
565     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
566
567     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
568     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
569     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
570     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
571
572     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
573     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
574     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
575     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
576
577     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
578     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
579
580     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
581     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
582     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
583     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
584     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
585     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
586     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
587
588     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
589     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
590     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
591     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
592     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
593     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
594     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
595
596     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
597     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
598     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
599     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
600     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
601     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
602     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
603
604     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
605     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
606     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
607     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
608     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
609     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
610     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
611     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
612     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
613
614     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
615     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
616     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
617     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
618     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
619
620     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
621     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
622     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
623     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
624
625     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
626     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
627     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
628     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
629
630     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
631
632     setTruncStoreAction(MVT::v8i16,             MVT::v8i8, Expand);
633     setOperationAction(ISD::TRUNCATE,           MVT::v8i8, Expand);
634     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
635     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
636     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
637     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
638   }
639
640   if (!UseSoftFloat && Subtarget->hasSSE1()) {
641     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
642
643     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
644     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
645     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
646     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
647     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
648     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
649     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
650     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
651     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
652     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
653     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
654     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
655   }
656
657   if (!UseSoftFloat && Subtarget->hasSSE2()) {
658     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
659
660     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
661     // registers cannot be used even for integer operations.
662     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
663     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
664     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
665     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
666
667     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
668     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
669     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
670     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
671     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
672     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
673     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
674     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
675     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
676     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
677     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
678     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
679     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
680     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
681     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
682     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
683
684     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
685     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
686     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
687     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
688
689     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
690     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
691     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
692     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
693     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
694
695     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
696     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
697       MVT VT = (MVT::SimpleValueType)i;
698       // Do not attempt to custom lower non-power-of-2 vectors
699       if (!isPowerOf2_32(VT.getVectorNumElements()))
700         continue;
701       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
702       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
703       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
704     }
705
706     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
707     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
708     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
709     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
710     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
711     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
712
713     if (Subtarget->is64Bit()) {
714       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
715       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
716     }
717
718     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
719     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
720       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
721       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v2i64);
722       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
723       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v2i64);
724       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
725       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v2i64);
726       setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
727       AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v2i64);
728       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
729       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
730     }
731
732     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
733
734     // Custom lower v2i64 and v2f64 selects.
735     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
736     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
737     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
738     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
739
740   }
741
742   if (Subtarget->hasSSE41()) {
743     // FIXME: Do we need to handle scalar-to-vector here?
744     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
745
746     // i8 and i16 vectors are custom , because the source register and source
747     // source memory operand types are not the same width.  f32 vectors are
748     // custom since the immediate controlling the insert encodes additional
749     // information.
750     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
751     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
752     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
753     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
754
755     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
756     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
757     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
758     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
759
760     if (Subtarget->is64Bit()) {
761       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
762       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
763     }
764   }
765
766   if (Subtarget->hasSSE42()) {
767     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
768   }
769
770   // We want to custom lower some of our intrinsics.
771   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
772
773   // Add/Sub/Mul with overflow operations are custom lowered.
774   setOperationAction(ISD::SADDO, MVT::i32, Custom);
775   setOperationAction(ISD::SADDO, MVT::i64, Custom);
776   setOperationAction(ISD::UADDO, MVT::i32, Custom);
777   setOperationAction(ISD::UADDO, MVT::i64, Custom);
778   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
779   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
780   setOperationAction(ISD::USUBO, MVT::i32, Custom);
781   setOperationAction(ISD::USUBO, MVT::i64, Custom);
782   setOperationAction(ISD::SMULO, MVT::i32, Custom);
783   setOperationAction(ISD::SMULO, MVT::i64, Custom);
784   setOperationAction(ISD::UMULO, MVT::i32, Custom);
785   setOperationAction(ISD::UMULO, MVT::i64, Custom);
786
787   if (!Subtarget->is64Bit()) {
788     // These libcalls are not available in 32-bit.
789     setLibcallName(RTLIB::SHL_I128, 0);
790     setLibcallName(RTLIB::SRL_I128, 0);
791     setLibcallName(RTLIB::SRA_I128, 0);
792   }
793
794   // We have target-specific dag combine patterns for the following nodes:
795   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
796   setTargetDAGCombine(ISD::BUILD_VECTOR);
797   setTargetDAGCombine(ISD::SELECT);
798   setTargetDAGCombine(ISD::SHL);
799   setTargetDAGCombine(ISD::SRA);
800   setTargetDAGCombine(ISD::SRL);
801   setTargetDAGCombine(ISD::STORE);
802   if (Subtarget->is64Bit())
803     setTargetDAGCombine(ISD::MUL);
804
805   computeRegisterProperties();
806
807   // FIXME: These should be based on subtarget info. Plus, the values should
808   // be smaller when we are in optimizing for size mode.
809   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
810   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
811   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
812   allowUnalignedMemoryAccesses = true; // x86 supports it!
813   setPrefLoopAlignment(16);
814   benefitFromCodePlacementOpt = true;
815 }
816
817
818 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
819   return MVT::i8;
820 }
821
822
823 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
824 /// the desired ByVal argument alignment.
825 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
826   if (MaxAlign == 16)
827     return;
828   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
829     if (VTy->getBitWidth() == 128)
830       MaxAlign = 16;
831   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
832     unsigned EltAlign = 0;
833     getMaxByValAlign(ATy->getElementType(), EltAlign);
834     if (EltAlign > MaxAlign)
835       MaxAlign = EltAlign;
836   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
837     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
838       unsigned EltAlign = 0;
839       getMaxByValAlign(STy->getElementType(i), EltAlign);
840       if (EltAlign > MaxAlign)
841         MaxAlign = EltAlign;
842       if (MaxAlign == 16)
843         break;
844     }
845   }
846   return;
847 }
848
849 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
850 /// function arguments in the caller parameter area. For X86, aggregates
851 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
852 /// are at 4-byte boundaries.
853 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
854   if (Subtarget->is64Bit()) {
855     // Max of 8 and alignment of type.
856     unsigned TyAlign = TD->getABITypeAlignment(Ty);
857     if (TyAlign > 8)
858       return TyAlign;
859     return 8;
860   }
861
862   unsigned Align = 4;
863   if (Subtarget->hasSSE1())
864     getMaxByValAlign(Ty, Align);
865   return Align;
866 }
867
868 /// getOptimalMemOpType - Returns the target specific optimal type for load
869 /// and store operations as a result of memset, memcpy, and memmove
870 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
871 /// determining it.
872 MVT
873 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
874                                        bool isSrcConst, bool isSrcStr) const {
875   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
876   // linux.  This is because the stack realignment code can't handle certain
877   // cases like PR2962.  This should be removed when PR2962 is fixed.
878   if (!NoImplicitFloat && Subtarget->getStackAlignment() >= 16) {
879     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
880       return MVT::v4i32;
881     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
882       return MVT::v4f32;
883   }
884   if (Subtarget->is64Bit() && Size >= 8)
885     return MVT::i64;
886   return MVT::i32;
887 }
888
889 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
890 /// jumptable.
891 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
892                                                       SelectionDAG &DAG) const {
893   if (usesGlobalOffsetTable())
894     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
895   if (!Subtarget->isPICStyleRIPRel())
896     // This doesn't have DebugLoc associated with it, but is not really the
897     // same as a Register.
898     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
899                        getPointerTy());
900   return Table;
901 }
902
903 //===----------------------------------------------------------------------===//
904 //               Return Value Calling Convention Implementation
905 //===----------------------------------------------------------------------===//
906
907 #include "X86GenCallingConv.inc"
908
909 /// LowerRET - Lower an ISD::RET node.
910 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
911   DebugLoc dl = Op.getDebugLoc();
912   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
913
914   SmallVector<CCValAssign, 16> RVLocs;
915   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
916   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
917   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
918   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
919
920   // If this is the first return lowered for this function, add the regs to the
921   // liveout set for the function.
922   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
923     for (unsigned i = 0; i != RVLocs.size(); ++i)
924       if (RVLocs[i].isRegLoc())
925         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
926   }
927   SDValue Chain = Op.getOperand(0);
928
929   // Handle tail call return.
930   Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
931   if (Chain.getOpcode() == X86ISD::TAILCALL) {
932     SDValue TailCall = Chain;
933     SDValue TargetAddress = TailCall.getOperand(1);
934     SDValue StackAdjustment = TailCall.getOperand(2);
935     assert(((TargetAddress.getOpcode() == ISD::Register &&
936                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
937                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
938               TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
939               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
940              "Expecting an global address, external symbol, or register");
941     assert(StackAdjustment.getOpcode() == ISD::Constant &&
942            "Expecting a const value");
943
944     SmallVector<SDValue,8> Operands;
945     Operands.push_back(Chain.getOperand(0));
946     Operands.push_back(TargetAddress);
947     Operands.push_back(StackAdjustment);
948     // Copy registers used by the call. Last operand is a flag so it is not
949     // copied.
950     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
951       Operands.push_back(Chain.getOperand(i));
952     }
953     return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
954                        Operands.size());
955   }
956
957   // Regular return.
958   SDValue Flag;
959
960   SmallVector<SDValue, 6> RetOps;
961   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
962   // Operand #1 = Bytes To Pop
963   RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
964
965   // Copy the result values into the output registers.
966   for (unsigned i = 0; i != RVLocs.size(); ++i) {
967     CCValAssign &VA = RVLocs[i];
968     assert(VA.isRegLoc() && "Can only return in registers!");
969     SDValue ValToCopy = Op.getOperand(i*2+1);
970
971     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
972     // the RET instruction and handled by the FP Stackifier.
973     if (VA.getLocReg() == X86::ST0 ||
974         VA.getLocReg() == X86::ST1) {
975       // If this is a copy from an xmm register to ST(0), use an FPExtend to
976       // change the value to the FP stack register class.
977       if (isScalarFPTypeInSSEReg(VA.getValVT()))
978         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
979       RetOps.push_back(ValToCopy);
980       // Don't emit a copytoreg.
981       continue;
982     }
983
984     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
985     // which is returned in RAX / RDX.
986     if (Subtarget->is64Bit()) {
987       MVT ValVT = ValToCopy.getValueType();
988       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
989         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
990         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
991           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
992       }
993     }
994
995     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
996     Flag = Chain.getValue(1);
997   }
998
999   // The x86-64 ABI for returning structs by value requires that we copy
1000   // the sret argument into %rax for the return. We saved the argument into
1001   // a virtual register in the entry block, so now we copy the value out
1002   // and into %rax.
1003   if (Subtarget->is64Bit() &&
1004       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1005     MachineFunction &MF = DAG.getMachineFunction();
1006     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1007     unsigned Reg = FuncInfo->getSRetReturnReg();
1008     if (!Reg) {
1009       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1010       FuncInfo->setSRetReturnReg(Reg);
1011     }
1012     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1013
1014     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1015     Flag = Chain.getValue(1);
1016   }
1017
1018   RetOps[0] = Chain;  // Update chain.
1019
1020   // Add the flag if we have it.
1021   if (Flag.getNode())
1022     RetOps.push_back(Flag);
1023
1024   return DAG.getNode(X86ISD::RET_FLAG, dl,
1025                      MVT::Other, &RetOps[0], RetOps.size());
1026 }
1027
1028
1029 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1030 /// appropriate copies out of appropriate physical registers.  This assumes that
1031 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1032 /// being lowered.  The returns a SDNode with the same number of values as the
1033 /// ISD::CALL.
1034 SDNode *X86TargetLowering::
1035 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1036                 unsigned CallingConv, SelectionDAG &DAG) {
1037
1038   DebugLoc dl = TheCall->getDebugLoc();
1039   // Assign locations to each value returned by this call.
1040   SmallVector<CCValAssign, 16> RVLocs;
1041   bool isVarArg = TheCall->isVarArg();
1042   bool Is64Bit = Subtarget->is64Bit();
1043   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1044   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1045
1046   SmallVector<SDValue, 8> ResultVals;
1047
1048   // Copy all of the result registers out of their specified physreg.
1049   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1050     CCValAssign &VA = RVLocs[i];
1051     MVT CopyVT = VA.getValVT();
1052
1053     // If this is x86-64, and we disabled SSE, we can't return FP values
1054     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1055         ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1056       cerr << "SSE register return with SSE disabled\n";
1057       exit(1);
1058     }
1059
1060     // If this is a call to a function that returns an fp value on the floating
1061     // point stack, but where we prefer to use the value in xmm registers, copy
1062     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1063     if ((VA.getLocReg() == X86::ST0 ||
1064          VA.getLocReg() == X86::ST1) &&
1065         isScalarFPTypeInSSEReg(VA.getValVT())) {
1066       CopyVT = MVT::f80;
1067     }
1068
1069     SDValue Val;
1070     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1071       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1072       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1073         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1074                                    MVT::v2i64, InFlag).getValue(1);
1075         Val = Chain.getValue(0);
1076         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1077                           Val, DAG.getConstant(0, MVT::i64));        
1078       } else {
1079         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1080                                    MVT::i64, InFlag).getValue(1);
1081         Val = Chain.getValue(0);
1082       }
1083       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1084     } else {
1085       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1086                                  CopyVT, InFlag).getValue(1);
1087       Val = Chain.getValue(0);
1088     }
1089     InFlag = Chain.getValue(2);
1090
1091     if (CopyVT != VA.getValVT()) {
1092       // Round the F80 the right size, which also moves to the appropriate xmm
1093       // register.
1094       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1095                         // This truncation won't change the value.
1096                         DAG.getIntPtrConstant(1));
1097     }
1098
1099     ResultVals.push_back(Val);
1100   }
1101
1102   // Merge everything together with a MERGE_VALUES node.
1103   ResultVals.push_back(Chain);
1104   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1105                      &ResultVals[0], ResultVals.size()).getNode();
1106 }
1107
1108
1109 //===----------------------------------------------------------------------===//
1110 //                C & StdCall & Fast Calling Convention implementation
1111 //===----------------------------------------------------------------------===//
1112 //  StdCall calling convention seems to be standard for many Windows' API
1113 //  routines and around. It differs from C calling convention just a little:
1114 //  callee should clean up the stack, not caller. Symbols should be also
1115 //  decorated in some fancy way :) It doesn't support any vector arguments.
1116 //  For info on fast calling convention see Fast Calling Convention (tail call)
1117 //  implementation LowerX86_32FastCCCallTo.
1118
1119 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1120 /// semantics.
1121 static bool CallIsStructReturn(CallSDNode *TheCall) {
1122   unsigned NumOps = TheCall->getNumArgs();
1123   if (!NumOps)
1124     return false;
1125
1126   return TheCall->getArgFlags(0).isSRet();
1127 }
1128
1129 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1130 /// return semantics.
1131 static bool ArgsAreStructReturn(SDValue Op) {
1132   unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1133   if (!NumArgs)
1134     return false;
1135
1136   return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1137 }
1138
1139 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1140 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1141 /// calls.
1142 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1143   if (IsVarArg)
1144     return false;
1145
1146   switch (CallingConv) {
1147   default:
1148     return false;
1149   case CallingConv::X86_StdCall:
1150     return !Subtarget->is64Bit();
1151   case CallingConv::X86_FastCall:
1152     return !Subtarget->is64Bit();
1153   case CallingConv::Fast:
1154     return PerformTailCallOpt;
1155   }
1156 }
1157
1158 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1159 /// given CallingConvention value.
1160 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1161   if (Subtarget->is64Bit()) {
1162     if (Subtarget->isTargetWin64())
1163       return CC_X86_Win64_C;
1164     else if (CC == CallingConv::Fast && PerformTailCallOpt)
1165       return CC_X86_64_TailCall;
1166     else
1167       return CC_X86_64_C;
1168   }
1169
1170   if (CC == CallingConv::X86_FastCall)
1171     return CC_X86_32_FastCall;
1172   else if (CC == CallingConv::Fast)
1173     return CC_X86_32_FastCC;
1174   else
1175     return CC_X86_32_C;
1176 }
1177
1178 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1179 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1180 NameDecorationStyle
1181 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1182   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1183   if (CC == CallingConv::X86_FastCall)
1184     return FastCall;
1185   else if (CC == CallingConv::X86_StdCall)
1186     return StdCall;
1187   return None;
1188 }
1189
1190
1191 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1192 /// in a register before calling.
1193 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1194   return !IsTailCall && !Is64Bit &&
1195     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1196     Subtarget->isPICStyleGOT();
1197 }
1198
1199 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1200 /// address to be loaded in a register.
1201 bool
1202 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1203   return !Is64Bit && IsTailCall &&
1204     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1205     Subtarget->isPICStyleGOT();
1206 }
1207
1208 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1209 /// by "Src" to address "Dst" with size and alignment information specified by
1210 /// the specific parameter attribute. The copy will be passed as a byval
1211 /// function parameter.
1212 static SDValue
1213 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1214                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1215                           DebugLoc dl) {
1216   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1217   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1218                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1219 }
1220
1221 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1222                                               const CCValAssign &VA,
1223                                               MachineFrameInfo *MFI,
1224                                               unsigned CC,
1225                                               SDValue Root, unsigned i) {
1226   // Create the nodes corresponding to a load from this parameter slot.
1227   ISD::ArgFlagsTy Flags =
1228     cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1229   bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1230   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1231
1232   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1233   // changed with more analysis.
1234   // In case of tail call optimization mark all arguments mutable. Since they
1235   // could be overwritten by lowering of arguments in case of a tail call.
1236   int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1237                                   VA.getLocMemOffset(), isImmutable);
1238   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1239   if (Flags.isByVal())
1240     return FIN;
1241   return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1242                      PseudoSourceValue::getFixedStack(FI), 0);
1243 }
1244
1245 SDValue
1246 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1247   MachineFunction &MF = DAG.getMachineFunction();
1248   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1249   DebugLoc dl = Op.getDebugLoc();
1250
1251   const Function* Fn = MF.getFunction();
1252   if (Fn->hasExternalLinkage() &&
1253       Subtarget->isTargetCygMing() &&
1254       Fn->getName() == "main")
1255     FuncInfo->setForceFramePointer(true);
1256
1257   // Decorate the function name.
1258   FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1259
1260   MachineFrameInfo *MFI = MF.getFrameInfo();
1261   SDValue Root = Op.getOperand(0);
1262   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1263   unsigned CC = MF.getFunction()->getCallingConv();
1264   bool Is64Bit = Subtarget->is64Bit();
1265   bool IsWin64 = Subtarget->isTargetWin64();
1266
1267   assert(!(isVarArg && CC == CallingConv::Fast) &&
1268          "Var args not supported with calling convention fastcc");
1269
1270   // Assign locations to all of the incoming arguments.
1271   SmallVector<CCValAssign, 16> ArgLocs;
1272   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1273   CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1274
1275   SmallVector<SDValue, 8> ArgValues;
1276   unsigned LastVal = ~0U;
1277   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1278     CCValAssign &VA = ArgLocs[i];
1279     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1280     // places.
1281     assert(VA.getValNo() != LastVal &&
1282            "Don't support value assigned to multiple locs yet");
1283     LastVal = VA.getValNo();
1284
1285     if (VA.isRegLoc()) {
1286       MVT RegVT = VA.getLocVT();
1287       TargetRegisterClass *RC = NULL;
1288       if (RegVT == MVT::i32)
1289         RC = X86::GR32RegisterClass;
1290       else if (Is64Bit && RegVT == MVT::i64)
1291         RC = X86::GR64RegisterClass;
1292       else if (RegVT == MVT::f32)
1293         RC = X86::FR32RegisterClass;
1294       else if (RegVT == MVT::f64)
1295         RC = X86::FR64RegisterClass;
1296       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1297         RC = X86::VR128RegisterClass;
1298       else if (RegVT.isVector()) {
1299         assert(RegVT.getSizeInBits() == 64);
1300         if (!Is64Bit)
1301           RC = X86::VR64RegisterClass;     // MMX values are passed in MMXs.
1302         else {
1303           // Darwin calling convention passes MMX values in either GPRs or
1304           // XMMs in x86-64. Other targets pass them in memory.
1305           if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1306             RC = X86::VR128RegisterClass;  // MMX values are passed in XMMs.
1307             RegVT = MVT::v2i64;
1308           } else {
1309             RC = X86::GR64RegisterClass;   // v1i64 values are passed in GPRs.
1310             RegVT = MVT::i64;
1311           }
1312         }
1313       } else {
1314         assert(0 && "Unknown argument type!");
1315       }
1316
1317       unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1318       SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1319
1320       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1321       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1322       // right size.
1323       if (VA.getLocInfo() == CCValAssign::SExt)
1324         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1325                                DAG.getValueType(VA.getValVT()));
1326       else if (VA.getLocInfo() == CCValAssign::ZExt)
1327         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1328                                DAG.getValueType(VA.getValVT()));
1329
1330       if (VA.getLocInfo() != CCValAssign::Full)
1331         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1332
1333       // Handle MMX values passed in GPRs.
1334       if (Is64Bit && RegVT != VA.getLocVT()) {
1335         if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1336           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1337         else if (RC == X86::VR128RegisterClass) {
1338           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1339                                  ArgValue, DAG.getConstant(0, MVT::i64));
1340           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1341         }
1342       }
1343
1344       ArgValues.push_back(ArgValue);
1345     } else {
1346       assert(VA.isMemLoc());
1347       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1348     }
1349   }
1350
1351   // The x86-64 ABI for returning structs by value requires that we copy
1352   // the sret argument into %rax for the return. Save the argument into
1353   // a virtual register so that we can access it from the return points.
1354   if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1355     MachineFunction &MF = DAG.getMachineFunction();
1356     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1357     unsigned Reg = FuncInfo->getSRetReturnReg();
1358     if (!Reg) {
1359       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1360       FuncInfo->setSRetReturnReg(Reg);
1361     }
1362     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1363     Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1364   }
1365
1366   unsigned StackSize = CCInfo.getNextStackOffset();
1367   // align stack specially for tail calls
1368   if (PerformTailCallOpt && CC == CallingConv::Fast)
1369     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1370
1371   // If the function takes variable number of arguments, make a frame index for
1372   // the start of the first vararg value... for expansion of llvm.va_start.
1373   if (isVarArg) {
1374     if (Is64Bit || CC != CallingConv::X86_FastCall) {
1375       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1376     }
1377     if (Is64Bit) {
1378       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1379
1380       // FIXME: We should really autogenerate these arrays
1381       static const unsigned GPR64ArgRegsWin64[] = {
1382         X86::RCX, X86::RDX, X86::R8,  X86::R9
1383       };
1384       static const unsigned XMMArgRegsWin64[] = {
1385         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1386       };
1387       static const unsigned GPR64ArgRegs64Bit[] = {
1388         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1389       };
1390       static const unsigned XMMArgRegs64Bit[] = {
1391         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1392         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1393       };
1394       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1395
1396       if (IsWin64) {
1397         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1398         GPR64ArgRegs = GPR64ArgRegsWin64;
1399         XMMArgRegs = XMMArgRegsWin64;
1400       } else {
1401         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1402         GPR64ArgRegs = GPR64ArgRegs64Bit;
1403         XMMArgRegs = XMMArgRegs64Bit;
1404       }
1405       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1406                                                        TotalNumIntRegs);
1407       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1408                                                        TotalNumXMMRegs);
1409
1410       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1411              "SSE register cannot be used when SSE is disabled!");
1412       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloat) &&
1413              "SSE register cannot be used when SSE is disabled!");
1414       if (UseSoftFloat || NoImplicitFloat || !Subtarget->hasSSE1())
1415         // Kernel mode asks for SSE to be disabled, so don't push them
1416         // on the stack.
1417         TotalNumXMMRegs = 0;
1418
1419       // For X86-64, if there are vararg parameters that are passed via
1420       // registers, then we must store them to their spots on the stack so they
1421       // may be loaded by deferencing the result of va_next.
1422       VarArgsGPOffset = NumIntRegs * 8;
1423       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1424       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1425                                                  TotalNumXMMRegs * 16, 16);
1426
1427       // Store the integer parameter registers.
1428       SmallVector<SDValue, 8> MemOps;
1429       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1430       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1431                                   DAG.getIntPtrConstant(VarArgsGPOffset));
1432       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1433         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1434                                      X86::GR64RegisterClass);
1435         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1436         SDValue Store =
1437           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1438                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1439         MemOps.push_back(Store);
1440         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1441                           DAG.getIntPtrConstant(8));
1442       }
1443
1444       // Now store the XMM (fp + vector) parameter registers.
1445       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1446                         DAG.getIntPtrConstant(VarArgsFPOffset));
1447       for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1448         unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1449                                      X86::VR128RegisterClass);
1450         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1451         SDValue Store =
1452           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1453                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1454         MemOps.push_back(Store);
1455         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1456                           DAG.getIntPtrConstant(16));
1457       }
1458       if (!MemOps.empty())
1459           Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1460                              &MemOps[0], MemOps.size());
1461     }
1462   }
1463
1464   ArgValues.push_back(Root);
1465
1466   // Some CCs need callee pop.
1467   if (IsCalleePop(isVarArg, CC)) {
1468     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1469     BytesCallerReserves = 0;
1470   } else {
1471     BytesToPopOnReturn  = 0; // Callee pops nothing.
1472     // If this is an sret function, the return should pop the hidden pointer.
1473     if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1474       BytesToPopOnReturn = 4;
1475     BytesCallerReserves = StackSize;
1476   }
1477
1478   if (!Is64Bit) {
1479     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1480     if (CC == CallingConv::X86_FastCall)
1481       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1482   }
1483
1484   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1485
1486   // Return the new list of results.
1487   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1488                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1489 }
1490
1491 SDValue
1492 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1493                                     const SDValue &StackPtr,
1494                                     const CCValAssign &VA,
1495                                     SDValue Chain,
1496                                     SDValue Arg, ISD::ArgFlagsTy Flags) {
1497   DebugLoc dl = TheCall->getDebugLoc();
1498   unsigned LocMemOffset = VA.getLocMemOffset();
1499   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1500   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1501   if (Flags.isByVal()) {
1502     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1503   }
1504   return DAG.getStore(Chain, dl, Arg, PtrOff,
1505                       PseudoSourceValue::getStack(), LocMemOffset);
1506 }
1507
1508 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1509 /// optimization is performed and it is required.
1510 SDValue
1511 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1512                                            SDValue &OutRetAddr,
1513                                            SDValue Chain,
1514                                            bool IsTailCall,
1515                                            bool Is64Bit,
1516                                            int FPDiff,
1517                                            DebugLoc dl) {
1518   if (!IsTailCall || FPDiff==0) return Chain;
1519
1520   // Adjust the Return address stack slot.
1521   MVT VT = getPointerTy();
1522   OutRetAddr = getReturnAddressFrameIndex(DAG);
1523
1524   // Load the "old" Return address.
1525   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1526   return SDValue(OutRetAddr.getNode(), 1);
1527 }
1528
1529 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1530 /// optimization is performed and it is required (FPDiff!=0).
1531 static SDValue
1532 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1533                          SDValue Chain, SDValue RetAddrFrIdx,
1534                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1535   // Store the return address to the appropriate stack slot.
1536   if (!FPDiff) return Chain;
1537   // Calculate the new stack slot for the return address.
1538   int SlotSize = Is64Bit ? 8 : 4;
1539   int NewReturnAddrFI =
1540     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1541   MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1542   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1543   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1544                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1545   return Chain;
1546 }
1547
1548 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1549   MachineFunction &MF = DAG.getMachineFunction();
1550   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1551   SDValue Chain       = TheCall->getChain();
1552   unsigned CC         = TheCall->getCallingConv();
1553   bool isVarArg       = TheCall->isVarArg();
1554   bool IsTailCall     = TheCall->isTailCall() &&
1555                         CC == CallingConv::Fast && PerformTailCallOpt;
1556   SDValue Callee      = TheCall->getCallee();
1557   bool Is64Bit        = Subtarget->is64Bit();
1558   bool IsStructRet    = CallIsStructReturn(TheCall);
1559   DebugLoc dl         = TheCall->getDebugLoc();
1560
1561   assert(!(isVarArg && CC == CallingConv::Fast) &&
1562          "Var args not supported with calling convention fastcc");
1563
1564   // Analyze operands of the call, assigning locations to each operand.
1565   SmallVector<CCValAssign, 16> ArgLocs;
1566   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1567   CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1568
1569   // Get a count of how many bytes are to be pushed on the stack.
1570   unsigned NumBytes = CCInfo.getNextStackOffset();
1571   if (PerformTailCallOpt && CC == CallingConv::Fast)
1572     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1573
1574   int FPDiff = 0;
1575   if (IsTailCall) {
1576     // Lower arguments at fp - stackoffset + fpdiff.
1577     unsigned NumBytesCallerPushed =
1578       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1579     FPDiff = NumBytesCallerPushed - NumBytes;
1580
1581     // Set the delta of movement of the returnaddr stackslot.
1582     // But only set if delta is greater than previous delta.
1583     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1584       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1585   }
1586
1587   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1588
1589   SDValue RetAddrFrIdx;
1590   // Load return adress for tail calls.
1591   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1592                                   FPDiff, dl);
1593
1594   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1595   SmallVector<SDValue, 8> MemOpChains;
1596   SDValue StackPtr;
1597
1598   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1599   // of tail call optimization arguments are handle later.
1600   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1601     CCValAssign &VA = ArgLocs[i];
1602     SDValue Arg = TheCall->getArg(i);
1603     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1604     bool isByVal = Flags.isByVal();
1605
1606     // Promote the value if needed.
1607     switch (VA.getLocInfo()) {
1608     default: assert(0 && "Unknown loc info!");
1609     case CCValAssign::Full: break;
1610     case CCValAssign::SExt:
1611       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1612       break;
1613     case CCValAssign::ZExt:
1614       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1615       break;
1616     case CCValAssign::AExt:
1617       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1618       break;
1619     }
1620
1621     if (VA.isRegLoc()) {
1622       if (Is64Bit) {
1623         MVT RegVT = VA.getLocVT();
1624         if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1625           switch (VA.getLocReg()) {
1626           default:
1627             break;
1628           case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1629           case X86::R8: {
1630             // Special case: passing MMX values in GPR registers.
1631             Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1632             break;
1633           }
1634           case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1635           case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1636             // Special case: passing MMX values in XMM registers.
1637             Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1638             Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1639             Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1640             break;
1641           }
1642           }
1643       }
1644       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1645     } else {
1646       if (!IsTailCall || (IsTailCall && isByVal)) {
1647         assert(VA.isMemLoc());
1648         if (StackPtr.getNode() == 0)
1649           StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1650
1651         MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1652                                                Chain, Arg, Flags));
1653       }
1654     }
1655   }
1656
1657   if (!MemOpChains.empty())
1658     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1659                         &MemOpChains[0], MemOpChains.size());
1660
1661   // Build a sequence of copy-to-reg nodes chained together with token chain
1662   // and flag operands which copy the outgoing args into registers.
1663   SDValue InFlag;
1664   // Tail call byval lowering might overwrite argument registers so in case of
1665   // tail call optimization the copies to registers are lowered later.
1666   if (!IsTailCall)
1667     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1668       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1669                                RegsToPass[i].second, InFlag);
1670       InFlag = Chain.getValue(1);
1671     }
1672
1673   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1674   // GOT pointer.
1675   if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1676     Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1677                              DAG.getNode(X86ISD::GlobalBaseReg,
1678                                          DebugLoc::getUnknownLoc(),
1679                                          getPointerTy()),
1680                              InFlag);
1681     InFlag = Chain.getValue(1);
1682   }
1683   // If we are tail calling and generating PIC/GOT style code load the address
1684   // of the callee into ecx. The value in ecx is used as target of the tail
1685   // jump. This is done to circumvent the ebx/callee-saved problem for tail
1686   // calls on PIC/GOT architectures. Normally we would just put the address of
1687   // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1688   // restored (since ebx is callee saved) before jumping to the target@PLT.
1689   if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1690     // Note: The actual moving to ecx is done further down.
1691     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1692     if (G && !G->getGlobal()->hasHiddenVisibility() &&
1693         !G->getGlobal()->hasProtectedVisibility())
1694       Callee =  LowerGlobalAddress(Callee, DAG);
1695     else if (isa<ExternalSymbolSDNode>(Callee))
1696       Callee = LowerExternalSymbol(Callee,DAG);
1697   }
1698
1699   if (Is64Bit && isVarArg) {
1700     // From AMD64 ABI document:
1701     // For calls that may call functions that use varargs or stdargs
1702     // (prototype-less calls or calls to functions containing ellipsis (...) in
1703     // the declaration) %al is used as hidden argument to specify the number
1704     // of SSE registers used. The contents of %al do not need to match exactly
1705     // the number of registers, but must be an ubound on the number of SSE
1706     // registers used and is in the range 0 - 8 inclusive.
1707
1708     // FIXME: Verify this on Win64
1709     // Count the number of XMM registers allocated.
1710     static const unsigned XMMArgRegs[] = {
1711       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1712       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1713     };
1714     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1715     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1716            && "SSE registers cannot be used when SSE is disabled");
1717
1718     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1719                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1720     InFlag = Chain.getValue(1);
1721   }
1722
1723
1724   // For tail calls lower the arguments to the 'real' stack slot.
1725   if (IsTailCall) {
1726     SmallVector<SDValue, 8> MemOpChains2;
1727     SDValue FIN;
1728     int FI = 0;
1729     // Do not flag preceeding copytoreg stuff together with the following stuff.
1730     InFlag = SDValue();
1731     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1732       CCValAssign &VA = ArgLocs[i];
1733       if (!VA.isRegLoc()) {
1734         assert(VA.isMemLoc());
1735         SDValue Arg = TheCall->getArg(i);
1736         ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1737         // Create frame index.
1738         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1739         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1740         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1741         FIN = DAG.getFrameIndex(FI, getPointerTy());
1742
1743         if (Flags.isByVal()) {
1744           // Copy relative to framepointer.
1745           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1746           if (StackPtr.getNode() == 0)
1747             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1748                                           getPointerTy());
1749           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1750
1751           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1752                                                            Flags, DAG, dl));
1753         } else {
1754           // Store relative to framepointer.
1755           MemOpChains2.push_back(
1756             DAG.getStore(Chain, dl, Arg, FIN,
1757                          PseudoSourceValue::getFixedStack(FI), 0));
1758         }
1759       }
1760     }
1761
1762     if (!MemOpChains2.empty())
1763       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1764                           &MemOpChains2[0], MemOpChains2.size());
1765
1766     // Copy arguments to their registers.
1767     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1768       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1769                                RegsToPass[i].second, InFlag);
1770       InFlag = Chain.getValue(1);
1771     }
1772     InFlag =SDValue();
1773
1774     // Store the return address to the appropriate stack slot.
1775     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1776                                      FPDiff, dl);
1777   }
1778
1779   // If the callee is a GlobalAddress node (quite common, every direct call is)
1780   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1781   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1782     // We should use extra load for direct calls to dllimported functions in
1783     // non-JIT mode.
1784     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1785                                         getTargetMachine(), true))
1786       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1787                                           G->getOffset());
1788   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1789     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1790   } else if (IsTailCall) {
1791     unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1792
1793     Chain = DAG.getCopyToReg(Chain,  dl,
1794                              DAG.getRegister(Opc, getPointerTy()),
1795                              Callee,InFlag);
1796     Callee = DAG.getRegister(Opc, getPointerTy());
1797     // Add register as live out.
1798     DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1799   }
1800
1801   // Returns a chain & a flag for retval copy to use.
1802   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1803   SmallVector<SDValue, 8> Ops;
1804
1805   if (IsTailCall) {
1806     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1807                            DAG.getIntPtrConstant(0, true), InFlag);
1808     InFlag = Chain.getValue(1);
1809
1810     // Returns a chain & a flag for retval copy to use.
1811     NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1812     Ops.clear();
1813   }
1814
1815   Ops.push_back(Chain);
1816   Ops.push_back(Callee);
1817
1818   if (IsTailCall)
1819     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1820
1821   // Add argument registers to the end of the list so that they are known live
1822   // into the call.
1823   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1824     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1825                                   RegsToPass[i].second.getValueType()));
1826
1827   // Add an implicit use GOT pointer in EBX.
1828   if (!IsTailCall && !Is64Bit &&
1829       getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1830       Subtarget->isPICStyleGOT())
1831     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1832
1833   // Add an implicit use of AL for x86 vararg functions.
1834   if (Is64Bit && isVarArg)
1835     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1836
1837   if (InFlag.getNode())
1838     Ops.push_back(InFlag);
1839
1840   if (IsTailCall) {
1841     assert(InFlag.getNode() &&
1842            "Flag must be set. Depend on flag being set in LowerRET");
1843     Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1844                         TheCall->getVTList(), &Ops[0], Ops.size());
1845
1846     return SDValue(Chain.getNode(), Op.getResNo());
1847   }
1848
1849   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1850   InFlag = Chain.getValue(1);
1851
1852   // Create the CALLSEQ_END node.
1853   unsigned NumBytesForCalleeToPush;
1854   if (IsCalleePop(isVarArg, CC))
1855     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1856   else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1857     // If this is is a call to a struct-return function, the callee
1858     // pops the hidden struct pointer, so we have to push it back.
1859     // This is common for Darwin/X86, Linux & Mingw32 targets.
1860     NumBytesForCalleeToPush = 4;
1861   else
1862     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1863
1864   // Returns a flag for retval copy to use.
1865   Chain = DAG.getCALLSEQ_END(Chain,
1866                              DAG.getIntPtrConstant(NumBytes, true),
1867                              DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1868                                                    true),
1869                              InFlag);
1870   InFlag = Chain.getValue(1);
1871
1872   // Handle result values, copying them out of physregs into vregs that we
1873   // return.
1874   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1875                  Op.getResNo());
1876 }
1877
1878
1879 //===----------------------------------------------------------------------===//
1880 //                Fast Calling Convention (tail call) implementation
1881 //===----------------------------------------------------------------------===//
1882
1883 //  Like std call, callee cleans arguments, convention except that ECX is
1884 //  reserved for storing the tail called function address. Only 2 registers are
1885 //  free for argument passing (inreg). Tail call optimization is performed
1886 //  provided:
1887 //                * tailcallopt is enabled
1888 //                * caller/callee are fastcc
1889 //  On X86_64 architecture with GOT-style position independent code only local
1890 //  (within module) calls are supported at the moment.
1891 //  To keep the stack aligned according to platform abi the function
1892 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1893 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1894 //  If a tail called function callee has more arguments than the caller the
1895 //  caller needs to make sure that there is room to move the RETADDR to. This is
1896 //  achieved by reserving an area the size of the argument delta right after the
1897 //  original REtADDR, but before the saved framepointer or the spilled registers
1898 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1899 //  stack layout:
1900 //    arg1
1901 //    arg2
1902 //    RETADDR
1903 //    [ new RETADDR
1904 //      move area ]
1905 //    (possible EBP)
1906 //    ESI
1907 //    EDI
1908 //    local1 ..
1909
1910 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1911 /// for a 16 byte align requirement.
1912 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1913                                                         SelectionDAG& DAG) {
1914   MachineFunction &MF = DAG.getMachineFunction();
1915   const TargetMachine &TM = MF.getTarget();
1916   const TargetFrameInfo &TFI = *TM.getFrameInfo();
1917   unsigned StackAlignment = TFI.getStackAlignment();
1918   uint64_t AlignMask = StackAlignment - 1;
1919   int64_t Offset = StackSize;
1920   uint64_t SlotSize = TD->getPointerSize();
1921   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1922     // Number smaller than 12 so just add the difference.
1923     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1924   } else {
1925     // Mask out lower bits, add stackalignment once plus the 12 bytes.
1926     Offset = ((~AlignMask) & Offset) + StackAlignment +
1927       (StackAlignment-SlotSize);
1928   }
1929   return Offset;
1930 }
1931
1932 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1933 /// following the call is a return. A function is eligible if caller/callee
1934 /// calling conventions match, currently only fastcc supports tail calls, and
1935 /// the function CALL is immediatly followed by a RET.
1936 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1937                                                       SDValue Ret,
1938                                                       SelectionDAG& DAG) const {
1939   if (!PerformTailCallOpt)
1940     return false;
1941
1942   if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1943     MachineFunction &MF = DAG.getMachineFunction();
1944     unsigned CallerCC = MF.getFunction()->getCallingConv();
1945     unsigned CalleeCC= TheCall->getCallingConv();
1946     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1947       SDValue Callee = TheCall->getCallee();
1948       // On x86/32Bit PIC/GOT  tail calls are supported.
1949       if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1950           !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1951         return true;
1952
1953       // Can only do local tail calls (in same module, hidden or protected) on
1954       // x86_64 PIC/GOT at the moment.
1955       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1956         return G->getGlobal()->hasHiddenVisibility()
1957             || G->getGlobal()->hasProtectedVisibility();
1958     }
1959   }
1960
1961   return false;
1962 }
1963
1964 FastISel *
1965 X86TargetLowering::createFastISel(MachineFunction &mf,
1966                                   MachineModuleInfo *mmo,
1967                                   DwarfWriter *dw,
1968                                   DenseMap<const Value *, unsigned> &vm,
1969                                   DenseMap<const BasicBlock *,
1970                                            MachineBasicBlock *> &bm,
1971                                   DenseMap<const AllocaInst *, int> &am
1972 #ifndef NDEBUG
1973                                   , SmallSet<Instruction*, 8> &cil
1974 #endif
1975                                   ) {
1976   return X86::createFastISel(mf, mmo, dw, vm, bm, am
1977 #ifndef NDEBUG
1978                              , cil
1979 #endif
1980                              );
1981 }
1982
1983
1984 //===----------------------------------------------------------------------===//
1985 //                           Other Lowering Hooks
1986 //===----------------------------------------------------------------------===//
1987
1988
1989 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1990   MachineFunction &MF = DAG.getMachineFunction();
1991   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1992   int ReturnAddrIndex = FuncInfo->getRAIndex();
1993
1994   if (ReturnAddrIndex == 0) {
1995     // Set up a frame object for the return address.
1996     uint64_t SlotSize = TD->getPointerSize();
1997     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1998     FuncInfo->setRAIndex(ReturnAddrIndex);
1999   }
2000
2001   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2002 }
2003
2004
2005 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2006 /// specific condition code, returning the condition code and the LHS/RHS of the
2007 /// comparison to make.
2008 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2009                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2010   if (!isFP) {
2011     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2012       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2013         // X > -1   -> X == 0, jump !sign.
2014         RHS = DAG.getConstant(0, RHS.getValueType());
2015         return X86::COND_NS;
2016       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2017         // X < 0   -> X == 0, jump on sign.
2018         return X86::COND_S;
2019       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2020         // X < 1   -> X <= 0
2021         RHS = DAG.getConstant(0, RHS.getValueType());
2022         return X86::COND_LE;
2023       }
2024     }
2025
2026     switch (SetCCOpcode) {
2027     default: assert(0 && "Invalid integer condition!");
2028     case ISD::SETEQ:  return X86::COND_E;
2029     case ISD::SETGT:  return X86::COND_G;
2030     case ISD::SETGE:  return X86::COND_GE;
2031     case ISD::SETLT:  return X86::COND_L;
2032     case ISD::SETLE:  return X86::COND_LE;
2033     case ISD::SETNE:  return X86::COND_NE;
2034     case ISD::SETULT: return X86::COND_B;
2035     case ISD::SETUGT: return X86::COND_A;
2036     case ISD::SETULE: return X86::COND_BE;
2037     case ISD::SETUGE: return X86::COND_AE;
2038     }
2039   }
2040
2041   // First determine if it is required or is profitable to flip the operands.
2042
2043   // If LHS is a foldable load, but RHS is not, flip the condition.
2044   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2045       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2046     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2047     std::swap(LHS, RHS);
2048   }
2049
2050   switch (SetCCOpcode) {
2051   default: break;
2052   case ISD::SETOLT:
2053   case ISD::SETOLE:
2054   case ISD::SETUGT:
2055   case ISD::SETUGE:
2056     std::swap(LHS, RHS);
2057     break;
2058   }
2059
2060   // On a floating point condition, the flags are set as follows:
2061   // ZF  PF  CF   op
2062   //  0 | 0 | 0 | X > Y
2063   //  0 | 0 | 1 | X < Y
2064   //  1 | 0 | 0 | X == Y
2065   //  1 | 1 | 1 | unordered
2066   switch (SetCCOpcode) {
2067   default: assert(0 && "Condcode should be pre-legalized away");
2068   case ISD::SETUEQ:
2069   case ISD::SETEQ:   return X86::COND_E;
2070   case ISD::SETOLT:              // flipped
2071   case ISD::SETOGT:
2072   case ISD::SETGT:   return X86::COND_A;
2073   case ISD::SETOLE:              // flipped
2074   case ISD::SETOGE:
2075   case ISD::SETGE:   return X86::COND_AE;
2076   case ISD::SETUGT:              // flipped
2077   case ISD::SETULT:
2078   case ISD::SETLT:   return X86::COND_B;
2079   case ISD::SETUGE:              // flipped
2080   case ISD::SETULE:
2081   case ISD::SETLE:   return X86::COND_BE;
2082   case ISD::SETONE:
2083   case ISD::SETNE:   return X86::COND_NE;
2084   case ISD::SETUO:   return X86::COND_P;
2085   case ISD::SETO:    return X86::COND_NP;
2086   }
2087 }
2088
2089 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2090 /// code. Current x86 isa includes the following FP cmov instructions:
2091 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2092 static bool hasFPCMov(unsigned X86CC) {
2093   switch (X86CC) {
2094   default:
2095     return false;
2096   case X86::COND_B:
2097   case X86::COND_BE:
2098   case X86::COND_E:
2099   case X86::COND_P:
2100   case X86::COND_A:
2101   case X86::COND_AE:
2102   case X86::COND_NE:
2103   case X86::COND_NP:
2104     return true;
2105   }
2106 }
2107
2108 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2109 /// the specified range (L, H].
2110 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2111   return (Val < 0) || (Val >= Low && Val < Hi);
2112 }
2113
2114 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2115 /// specified value.
2116 static bool isUndefOrEqual(int Val, int CmpVal) {
2117   if (Val < 0 || Val == CmpVal)
2118     return true;
2119   return false;
2120 }
2121
2122 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2123 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2124 /// the second operand.
2125 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2126   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2127     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2128   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2129     return (Mask[0] < 2 && Mask[1] < 2);
2130   return false;
2131 }
2132
2133 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2134   SmallVector<int, 8> M; 
2135   N->getMask(M);
2136   return ::isPSHUFDMask(M, N->getValueType(0));
2137 }
2138
2139 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2140 /// is suitable for input to PSHUFHW.
2141 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2142   if (VT != MVT::v8i16)
2143     return false;
2144   
2145   // Lower quadword copied in order or undef.
2146   for (int i = 0; i != 4; ++i)
2147     if (Mask[i] >= 0 && Mask[i] != i)
2148       return false;
2149   
2150   // Upper quadword shuffled.
2151   for (int i = 4; i != 8; ++i)
2152     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2153       return false;
2154   
2155   return true;
2156 }
2157
2158 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2159   SmallVector<int, 8> M; 
2160   N->getMask(M);
2161   return ::isPSHUFHWMask(M, N->getValueType(0));
2162 }
2163
2164 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2165 /// is suitable for input to PSHUFLW.
2166 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2167   if (VT != MVT::v8i16)
2168     return false;
2169   
2170   // Upper quadword copied in order.
2171   for (int i = 4; i != 8; ++i)
2172     if (Mask[i] >= 0 && Mask[i] != i)
2173       return false;
2174   
2175   // Lower quadword shuffled.
2176   for (int i = 0; i != 4; ++i)
2177     if (Mask[i] >= 4)
2178       return false;
2179   
2180   return true;
2181 }
2182
2183 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2184   SmallVector<int, 8> M; 
2185   N->getMask(M);
2186   return ::isPSHUFLWMask(M, N->getValueType(0));
2187 }
2188
2189 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2190 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2191 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2192   int NumElems = VT.getVectorNumElements();
2193   if (NumElems != 2 && NumElems != 4)
2194     return false;
2195   
2196   int Half = NumElems / 2;
2197   for (int i = 0; i < Half; ++i)
2198     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2199       return false;
2200   for (int i = Half; i < NumElems; ++i)
2201     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2202       return false;
2203   
2204   return true;
2205 }
2206
2207 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2208   SmallVector<int, 8> M;
2209   N->getMask(M);
2210   return ::isSHUFPMask(M, N->getValueType(0));
2211 }
2212
2213 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2214 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2215 /// half elements to come from vector 1 (which would equal the dest.) and
2216 /// the upper half to come from vector 2.
2217 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2218   int NumElems = VT.getVectorNumElements();
2219   
2220   if (NumElems != 2 && NumElems != 4) 
2221     return false;
2222   
2223   int Half = NumElems / 2;
2224   for (int i = 0; i < Half; ++i)
2225     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2226       return false;
2227   for (int i = Half; i < NumElems; ++i)
2228     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2229       return false;
2230   return true;
2231 }
2232
2233 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2234   SmallVector<int, 8> M;
2235   N->getMask(M);
2236   return isCommutedSHUFPMask(M, N->getValueType(0));
2237 }
2238
2239 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2240 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2241 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2242   if (N->getValueType(0).getVectorNumElements() != 4)
2243     return false;
2244
2245   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2246   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2247          isUndefOrEqual(N->getMaskElt(1), 7) &&
2248          isUndefOrEqual(N->getMaskElt(2), 2) &&
2249          isUndefOrEqual(N->getMaskElt(3), 3);
2250 }
2251
2252 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2253 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2254 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2255   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2256
2257   if (NumElems != 2 && NumElems != 4)
2258     return false;
2259
2260   for (unsigned i = 0; i < NumElems/2; ++i)
2261     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2262       return false;
2263
2264   for (unsigned i = NumElems/2; i < NumElems; ++i)
2265     if (!isUndefOrEqual(N->getMaskElt(i), i))
2266       return false;
2267
2268   return true;
2269 }
2270
2271 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2272 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2273 /// and MOVLHPS.
2274 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2275   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2276
2277   if (NumElems != 2 && NumElems != 4)
2278     return false;
2279
2280   for (unsigned i = 0; i < NumElems/2; ++i)
2281     if (!isUndefOrEqual(N->getMaskElt(i), i))
2282       return false;
2283
2284   for (unsigned i = 0; i < NumElems/2; ++i)
2285     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2286       return false;
2287
2288   return true;
2289 }
2290
2291 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2292 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2293 /// <2, 3, 2, 3>
2294 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2295   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2296   
2297   if (NumElems != 4)
2298     return false;
2299   
2300   return isUndefOrEqual(N->getMaskElt(0), 2) && 
2301          isUndefOrEqual(N->getMaskElt(1), 3) &&
2302          isUndefOrEqual(N->getMaskElt(2), 2) && 
2303          isUndefOrEqual(N->getMaskElt(3), 3);
2304 }
2305
2306 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2307 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2308 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2309                          bool V2IsSplat = false) {
2310   int NumElts = VT.getVectorNumElements();
2311   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2312     return false;
2313   
2314   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2315     int BitI  = Mask[i];
2316     int BitI1 = Mask[i+1];
2317     if (!isUndefOrEqual(BitI, j))
2318       return false;
2319     if (V2IsSplat) {
2320       if (!isUndefOrEqual(BitI1, NumElts))
2321         return false;
2322     } else {
2323       if (!isUndefOrEqual(BitI1, j + NumElts))
2324         return false;
2325     }
2326   }
2327   return true;
2328 }
2329
2330 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2331   SmallVector<int, 8> M;
2332   N->getMask(M);
2333   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2334 }
2335
2336 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2337 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2338 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT, 
2339                          bool V2IsSplat = false) {
2340   int NumElts = VT.getVectorNumElements();
2341   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2342     return false;
2343   
2344   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2345     int BitI  = Mask[i];
2346     int BitI1 = Mask[i+1];
2347     if (!isUndefOrEqual(BitI, j + NumElts/2))
2348       return false;
2349     if (V2IsSplat) {
2350       if (isUndefOrEqual(BitI1, NumElts))
2351         return false;
2352     } else {
2353       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2354         return false;
2355     }
2356   }
2357   return true;
2358 }
2359
2360 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2361   SmallVector<int, 8> M;
2362   N->getMask(M);
2363   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2364 }
2365
2366 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2367 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2368 /// <0, 0, 1, 1>
2369 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2370   int NumElems = VT.getVectorNumElements();
2371   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2372     return false;
2373   
2374   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2375     int BitI  = Mask[i];
2376     int BitI1 = Mask[i+1];
2377     if (!isUndefOrEqual(BitI, j))
2378       return false;
2379     if (!isUndefOrEqual(BitI1, j))
2380       return false;
2381   }
2382   return true;
2383 }
2384
2385 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2386   SmallVector<int, 8> M;
2387   N->getMask(M);
2388   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2389 }
2390
2391 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2392 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2393 /// <2, 2, 3, 3>
2394 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2395   int NumElems = VT.getVectorNumElements();
2396   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2397     return false;
2398   
2399   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2400     int BitI  = Mask[i];
2401     int BitI1 = Mask[i+1];
2402     if (!isUndefOrEqual(BitI, j))
2403       return false;
2404     if (!isUndefOrEqual(BitI1, j))
2405       return false;
2406   }
2407   return true;
2408 }
2409
2410 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2411   SmallVector<int, 8> M;
2412   N->getMask(M);
2413   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2414 }
2415
2416 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2417 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2418 /// MOVSD, and MOVD, i.e. setting the lowest element.
2419 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2420   int NumElts = VT.getVectorNumElements();
2421   if (NumElts != 2 && NumElts != 4)
2422     return false;
2423   
2424   if (!isUndefOrEqual(Mask[0], NumElts))
2425     return false;
2426   
2427   for (int i = 1; i < NumElts; ++i)
2428     if (!isUndefOrEqual(Mask[i], i))
2429       return false;
2430   
2431   return true;
2432 }
2433
2434 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2435   SmallVector<int, 8> M;
2436   N->getMask(M);
2437   return ::isMOVLMask(M, N->getValueType(0));
2438 }
2439
2440 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2441 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2442 /// element of vector 2 and the other elements to come from vector 1 in order.
2443 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2444                                bool V2IsSplat = false, bool V2IsUndef = false) {
2445   int NumOps = VT.getVectorNumElements();
2446   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2447     return false;
2448   
2449   if (!isUndefOrEqual(Mask[0], 0))
2450     return false;
2451   
2452   for (int i = 1; i < NumOps; ++i)
2453     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2454           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2455           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2456       return false;
2457   
2458   return true;
2459 }
2460
2461 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2462                            bool V2IsUndef = false) {
2463   SmallVector<int, 8> M;
2464   N->getMask(M);
2465   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2466 }
2467
2468 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2469 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2470 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2471   if (N->getValueType(0).getVectorNumElements() != 4)
2472     return false;
2473
2474   // Expect 1, 1, 3, 3
2475   for (unsigned i = 0; i < 2; ++i) {
2476     int Elt = N->getMaskElt(i);
2477     if (Elt >= 0 && Elt != 1)
2478       return false;
2479   }
2480
2481   bool HasHi = false;
2482   for (unsigned i = 2; i < 4; ++i) {
2483     int Elt = N->getMaskElt(i);
2484     if (Elt >= 0 && Elt != 3)
2485       return false;
2486     if (Elt == 3)
2487       HasHi = true;
2488   }
2489   // Don't use movshdup if it can be done with a shufps.
2490   // FIXME: verify that matching u, u, 3, 3 is what we want.
2491   return HasHi;
2492 }
2493
2494 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2495 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2496 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2497   if (N->getValueType(0).getVectorNumElements() != 4)
2498     return false;
2499
2500   // Expect 0, 0, 2, 2
2501   for (unsigned i = 0; i < 2; ++i)
2502     if (N->getMaskElt(i) > 0)
2503       return false;
2504
2505   bool HasHi = false;
2506   for (unsigned i = 2; i < 4; ++i) {
2507     int Elt = N->getMaskElt(i);
2508     if (Elt >= 0 && Elt != 2)
2509       return false;
2510     if (Elt == 2)
2511       HasHi = true;
2512   }
2513   // Don't use movsldup if it can be done with a shufps.
2514   return HasHi;
2515 }
2516
2517 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2518 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2519 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2520   int e = N->getValueType(0).getVectorNumElements() / 2;
2521   
2522   for (int i = 0; i < e; ++i)
2523     if (!isUndefOrEqual(N->getMaskElt(i), i))
2524       return false;
2525   for (int i = 0; i < e; ++i)
2526     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2527       return false;
2528   return true;
2529 }
2530
2531 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2532 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2533 /// instructions.
2534 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2535   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2536   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2537
2538   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2539   unsigned Mask = 0;
2540   for (int i = 0; i < NumOperands; ++i) {
2541     int Val = SVOp->getMaskElt(NumOperands-i-1);
2542     if (Val < 0) Val = 0;
2543     if (Val >= NumOperands) Val -= NumOperands;
2544     Mask |= Val;
2545     if (i != NumOperands - 1)
2546       Mask <<= Shift;
2547   }
2548   return Mask;
2549 }
2550
2551 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2552 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2553 /// instructions.
2554 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2555   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2556   unsigned Mask = 0;
2557   // 8 nodes, but we only care about the last 4.
2558   for (unsigned i = 7; i >= 4; --i) {
2559     int Val = SVOp->getMaskElt(i);
2560     if (Val >= 0)
2561       Mask |= (Val - 4);
2562     if (i != 4)
2563       Mask <<= 2;
2564   }
2565   return Mask;
2566 }
2567
2568 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2569 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2570 /// instructions.
2571 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2572   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2573   unsigned Mask = 0;
2574   // 8 nodes, but we only care about the first 4.
2575   for (int i = 3; i >= 0; --i) {
2576     int Val = SVOp->getMaskElt(i);
2577     if (Val >= 0)
2578       Mask |= Val;
2579     if (i != 0)
2580       Mask <<= 2;
2581   }
2582   return Mask;
2583 }
2584
2585 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2586 /// their permute mask.
2587 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2588                                     SelectionDAG &DAG) {
2589   MVT VT = SVOp->getValueType(0);
2590   unsigned NumElems = VT.getVectorNumElements();
2591   SmallVector<int, 8> MaskVec;
2592   
2593   for (unsigned i = 0; i != NumElems; ++i) {
2594     int idx = SVOp->getMaskElt(i);
2595     if (idx < 0)
2596       MaskVec.push_back(idx);
2597     else if (idx < (int)NumElems)
2598       MaskVec.push_back(idx + NumElems);
2599     else
2600       MaskVec.push_back(idx - NumElems);
2601   }
2602   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2603                               SVOp->getOperand(0), &MaskVec[0]);
2604 }
2605
2606 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2607 /// the two vector operands have swapped position.
2608 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2609   unsigned NumElems = VT.getVectorNumElements();
2610   for (unsigned i = 0; i != NumElems; ++i) {
2611     int idx = Mask[i];
2612     if (idx < 0)
2613       continue;
2614     else if (idx < (int)NumElems)
2615       Mask[i] = idx + NumElems;
2616     else
2617       Mask[i] = idx - NumElems;
2618   }
2619 }
2620
2621 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2622 /// match movhlps. The lower half elements should come from upper half of
2623 /// V1 (and in order), and the upper half elements should come from the upper
2624 /// half of V2 (and in order).
2625 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2626   if (Op->getValueType(0).getVectorNumElements() != 4)
2627     return false;
2628   for (unsigned i = 0, e = 2; i != e; ++i)
2629     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2630       return false;
2631   for (unsigned i = 2; i != 4; ++i)
2632     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2633       return false;
2634   return true;
2635 }
2636
2637 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2638 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2639 /// required.
2640 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2641   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2642     return false;
2643   N = N->getOperand(0).getNode();
2644   if (!ISD::isNON_EXTLoad(N))
2645     return false;
2646   if (LD)
2647     *LD = cast<LoadSDNode>(N);
2648   return true;
2649 }
2650
2651 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2652 /// match movlp{s|d}. The lower half elements should come from lower half of
2653 /// V1 (and in order), and the upper half elements should come from the upper
2654 /// half of V2 (and in order). And since V1 will become the source of the
2655 /// MOVLP, it must be either a vector load or a scalar load to vector.
2656 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2657                                ShuffleVectorSDNode *Op) {
2658   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2659     return false;
2660   // Is V2 is a vector load, don't do this transformation. We will try to use
2661   // load folding shufps op.
2662   if (ISD::isNON_EXTLoad(V2))
2663     return false;
2664
2665   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2666   
2667   if (NumElems != 2 && NumElems != 4)
2668     return false;
2669   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2670     if (!isUndefOrEqual(Op->getMaskElt(i), i))
2671       return false;
2672   for (unsigned i = NumElems/2; i != NumElems; ++i)
2673     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2674       return false;
2675   return true;
2676 }
2677
2678 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2679 /// all the same.
2680 static bool isSplatVector(SDNode *N) {
2681   if (N->getOpcode() != ISD::BUILD_VECTOR)
2682     return false;
2683
2684   SDValue SplatValue = N->getOperand(0);
2685   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2686     if (N->getOperand(i) != SplatValue)
2687       return false;
2688   return true;
2689 }
2690
2691 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2692 /// constant +0.0.
2693 static inline bool isZeroNode(SDValue Elt) {
2694   return ((isa<ConstantSDNode>(Elt) &&
2695            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2696           (isa<ConstantFPSDNode>(Elt) &&
2697            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2698 }
2699
2700 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2701 /// to an zero vector. 
2702 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2703 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2704   SDValue V1 = N->getOperand(0);
2705   SDValue V2 = N->getOperand(1);
2706   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2707   for (unsigned i = 0; i != NumElems; ++i) {
2708     int Idx = N->getMaskElt(i);
2709     if (Idx >= (int)NumElems) {
2710       unsigned Opc = V2.getOpcode();
2711       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2712         continue;
2713       if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2714         return false;
2715     } else if (Idx >= 0) {
2716       unsigned Opc = V1.getOpcode();
2717       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2718         continue;
2719       if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2720         return false;
2721     }
2722   }
2723   return true;
2724 }
2725
2726 /// getZeroVector - Returns a vector of specified type with all zero elements.
2727 ///
2728 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2729                              DebugLoc dl) {
2730   assert(VT.isVector() && "Expected a vector type");
2731
2732   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2733   // type.  This ensures they get CSE'd.
2734   SDValue Vec;
2735   if (VT.getSizeInBits() == 64) { // MMX
2736     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2737     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2738   } else if (HasSSE2) {  // SSE2
2739     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2740     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2741   } else { // SSE1
2742     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2743     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2744   }
2745   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2746 }
2747
2748 /// getOnesVector - Returns a vector of specified type with all bits set.
2749 ///
2750 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2751   assert(VT.isVector() && "Expected a vector type");
2752
2753   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2754   // type.  This ensures they get CSE'd.
2755   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2756   SDValue Vec;
2757   if (VT.getSizeInBits() == 64)  // MMX
2758     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2759   else                                              // SSE
2760     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2761   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2762 }
2763
2764
2765 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2766 /// that point to V2 points to its first element.
2767 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2768   MVT VT = SVOp->getValueType(0);
2769   unsigned NumElems = VT.getVectorNumElements();
2770   
2771   bool Changed = false;
2772   SmallVector<int, 8> MaskVec;
2773   SVOp->getMask(MaskVec);
2774   
2775   for (unsigned i = 0; i != NumElems; ++i) {
2776     if (MaskVec[i] > (int)NumElems) {
2777       MaskVec[i] = NumElems;
2778       Changed = true;
2779     }
2780   }
2781   if (Changed)
2782     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2783                                 SVOp->getOperand(1), &MaskVec[0]);
2784   return SDValue(SVOp, 0);
2785 }
2786
2787 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2788 /// operation of specified width.
2789 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2790                        SDValue V2) {
2791   unsigned NumElems = VT.getVectorNumElements();
2792   SmallVector<int, 8> Mask;
2793   Mask.push_back(NumElems);
2794   for (unsigned i = 1; i != NumElems; ++i)
2795     Mask.push_back(i);
2796   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2797 }
2798
2799 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2800 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2801                           SDValue V2) {
2802   unsigned NumElems = VT.getVectorNumElements();
2803   SmallVector<int, 8> Mask;
2804   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2805     Mask.push_back(i);
2806     Mask.push_back(i + NumElems);
2807   }
2808   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2809 }
2810
2811 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2812 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2813                           SDValue V2) {
2814   unsigned NumElems = VT.getVectorNumElements();
2815   unsigned Half = NumElems/2;
2816   SmallVector<int, 8> Mask;
2817   for (unsigned i = 0; i != Half; ++i) {
2818     Mask.push_back(i + Half);
2819     Mask.push_back(i + NumElems + Half);
2820   }
2821   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2822 }
2823
2824 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2825 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG, 
2826                             bool HasSSE2) {
2827   if (SV->getValueType(0).getVectorNumElements() <= 4)
2828     return SDValue(SV, 0);
2829   
2830   MVT PVT = MVT::v4f32;
2831   MVT VT = SV->getValueType(0);
2832   DebugLoc dl = SV->getDebugLoc();
2833   SDValue V1 = SV->getOperand(0);
2834   int NumElems = VT.getVectorNumElements();
2835   int EltNo = SV->getSplatIndex();
2836
2837   // unpack elements to the correct location
2838   while (NumElems > 4) {
2839     if (EltNo < NumElems/2) {
2840       V1 = getUnpackl(DAG, dl, VT, V1, V1);
2841     } else {
2842       V1 = getUnpackh(DAG, dl, VT, V1, V1);
2843       EltNo -= NumElems/2;
2844     }
2845     NumElems >>= 1;
2846   }
2847   
2848   // Perform the splat.
2849   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2850   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2851   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2852   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2853 }
2854
2855 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2856 /// vector of zero or undef vector.  This produces a shuffle where the low
2857 /// element of V2 is swizzled into the zero/undef vector, landing at element
2858 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2859 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2860                                              bool isZero, bool HasSSE2,
2861                                              SelectionDAG &DAG) {
2862   MVT VT = V2.getValueType();
2863   SDValue V1 = isZero
2864     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2865   unsigned NumElems = VT.getVectorNumElements();
2866   SmallVector<int, 16> MaskVec;
2867   for (unsigned i = 0; i != NumElems; ++i)
2868     // If this is the insertion idx, put the low elt of V2 here.
2869     MaskVec.push_back(i == Idx ? NumElems : i);
2870   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
2871 }
2872
2873 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2874 /// a shuffle that is zero.
2875 static
2876 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
2877                                   bool Low, SelectionDAG &DAG) {
2878   unsigned NumZeros = 0;
2879   for (int i = 0; i < NumElems; ++i) {
2880     unsigned Index = Low ? i : NumElems-i-1;
2881     int Idx = SVOp->getMaskElt(Index);
2882     if (Idx < 0) {
2883       ++NumZeros;
2884       continue;
2885     }
2886     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
2887     if (Elt.getNode() && isZeroNode(Elt))
2888       ++NumZeros;
2889     else
2890       break;
2891   }
2892   return NumZeros;
2893 }
2894
2895 /// isVectorShift - Returns true if the shuffle can be implemented as a
2896 /// logical left or right shift of a vector.
2897 /// FIXME: split into pslldqi, psrldqi, palignr variants.
2898 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
2899                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2900   int NumElems = SVOp->getValueType(0).getVectorNumElements();
2901
2902   isLeft = true;
2903   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
2904   if (!NumZeros) {
2905     isLeft = false;
2906     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
2907     if (!NumZeros)
2908       return false;
2909   }
2910   bool SeenV1 = false;
2911   bool SeenV2 = false;
2912   for (int i = NumZeros; i < NumElems; ++i) {
2913     int Val = isLeft ? (i - NumZeros) : i;
2914     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
2915     if (Idx < 0)
2916       continue;
2917     if (Idx < NumElems)
2918       SeenV1 = true;
2919     else {
2920       Idx -= NumElems;
2921       SeenV2 = true;
2922     }
2923     if (Idx != Val)
2924       return false;
2925   }
2926   if (SeenV1 && SeenV2)
2927     return false;
2928
2929   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
2930   ShAmt = NumZeros;
2931   return true;
2932 }
2933
2934
2935 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2936 ///
2937 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2938                                        unsigned NumNonZero, unsigned NumZero,
2939                                        SelectionDAG &DAG, TargetLowering &TLI) {
2940   if (NumNonZero > 8)
2941     return SDValue();
2942
2943   DebugLoc dl = Op.getDebugLoc();
2944   SDValue V(0, 0);
2945   bool First = true;
2946   for (unsigned i = 0; i < 16; ++i) {
2947     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2948     if (ThisIsNonZero && First) {
2949       if (NumZero)
2950         V = getZeroVector(MVT::v8i16, true, DAG, dl);
2951       else
2952         V = DAG.getUNDEF(MVT::v8i16);
2953       First = false;
2954     }
2955
2956     if ((i & 1) != 0) {
2957       SDValue ThisElt(0, 0), LastElt(0, 0);
2958       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2959       if (LastIsNonZero) {
2960         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
2961                               MVT::i16, Op.getOperand(i-1));
2962       }
2963       if (ThisIsNonZero) {
2964         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
2965         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
2966                               ThisElt, DAG.getConstant(8, MVT::i8));
2967         if (LastIsNonZero)
2968           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
2969       } else
2970         ThisElt = LastElt;
2971
2972       if (ThisElt.getNode())
2973         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
2974                         DAG.getIntPtrConstant(i/2));
2975     }
2976   }
2977
2978   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
2979 }
2980
2981 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2982 ///
2983 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
2984                                        unsigned NumNonZero, unsigned NumZero,
2985                                        SelectionDAG &DAG, TargetLowering &TLI) {
2986   if (NumNonZero > 4)
2987     return SDValue();
2988
2989   DebugLoc dl = Op.getDebugLoc();
2990   SDValue V(0, 0);
2991   bool First = true;
2992   for (unsigned i = 0; i < 8; ++i) {
2993     bool isNonZero = (NonZeros & (1 << i)) != 0;
2994     if (isNonZero) {
2995       if (First) {
2996         if (NumZero)
2997           V = getZeroVector(MVT::v8i16, true, DAG, dl);
2998         else
2999           V = DAG.getUNDEF(MVT::v8i16);
3000         First = false;
3001       }
3002       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3003                       MVT::v8i16, V, Op.getOperand(i),
3004                       DAG.getIntPtrConstant(i));
3005     }
3006   }
3007
3008   return V;
3009 }
3010
3011 /// getVShift - Return a vector logical shift node.
3012 ///
3013 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3014                          unsigned NumBits, SelectionDAG &DAG,
3015                          const TargetLowering &TLI, DebugLoc dl) {
3016   bool isMMX = VT.getSizeInBits() == 64;
3017   MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3018   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3019   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3020   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3021                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3022                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3023 }
3024
3025 SDValue
3026 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3027   DebugLoc dl = Op.getDebugLoc();
3028   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3029   if (ISD::isBuildVectorAllZeros(Op.getNode())
3030       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3031     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3032     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3033     // eliminated on x86-32 hosts.
3034     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3035       return Op;
3036
3037     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3038       return getOnesVector(Op.getValueType(), DAG, dl);
3039     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3040   }
3041
3042   MVT VT = Op.getValueType();
3043   MVT EVT = VT.getVectorElementType();
3044   unsigned EVTBits = EVT.getSizeInBits();
3045
3046   unsigned NumElems = Op.getNumOperands();
3047   unsigned NumZero  = 0;
3048   unsigned NumNonZero = 0;
3049   unsigned NonZeros = 0;
3050   bool IsAllConstants = true;
3051   SmallSet<SDValue, 8> Values;
3052   for (unsigned i = 0; i < NumElems; ++i) {
3053     SDValue Elt = Op.getOperand(i);
3054     if (Elt.getOpcode() == ISD::UNDEF)
3055       continue;
3056     Values.insert(Elt);
3057     if (Elt.getOpcode() != ISD::Constant &&
3058         Elt.getOpcode() != ISD::ConstantFP)
3059       IsAllConstants = false;
3060     if (isZeroNode(Elt))
3061       NumZero++;
3062     else {
3063       NonZeros |= (1 << i);
3064       NumNonZero++;
3065     }
3066   }
3067
3068   if (NumNonZero == 0) {
3069     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3070     return DAG.getUNDEF(VT);
3071   }
3072
3073   // Special case for single non-zero, non-undef, element.
3074   if (NumNonZero == 1 && NumElems <= 4) {
3075     unsigned Idx = CountTrailingZeros_32(NonZeros);
3076     SDValue Item = Op.getOperand(Idx);
3077
3078     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3079     // the value are obviously zero, truncate the value to i32 and do the
3080     // insertion that way.  Only do this if the value is non-constant or if the
3081     // value is a constant being inserted into element 0.  It is cheaper to do
3082     // a constant pool load than it is to do a movd + shuffle.
3083     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3084         (!IsAllConstants || Idx == 0)) {
3085       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3086         // Handle MMX and SSE both.
3087         MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3088         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3089
3090         // Truncate the value (which may itself be a constant) to i32, and
3091         // convert it to a vector with movd (S2V+shuffle to zero extend).
3092         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3093         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3094         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3095                                            Subtarget->hasSSE2(), DAG);
3096
3097         // Now we have our 32-bit value zero extended in the low element of
3098         // a vector.  If Idx != 0, swizzle it into place.
3099         if (Idx != 0) {
3100           SmallVector<int, 4> Mask;
3101           Mask.push_back(Idx);
3102           for (unsigned i = 1; i != VecElts; ++i)
3103             Mask.push_back(i);
3104           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3105                                       DAG.getUNDEF(Item.getValueType()), 
3106                                       &Mask[0]);
3107         }
3108         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3109       }
3110     }
3111
3112     // If we have a constant or non-constant insertion into the low element of
3113     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3114     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3115     // depending on what the source datatype is.  Because we can only get here
3116     // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3117     if (Idx == 0 &&
3118         // Don't do this for i64 values on x86-32.
3119         (EVT != MVT::i64 || Subtarget->is64Bit())) {
3120       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3121       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3122       return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3123                                          Subtarget->hasSSE2(), DAG);
3124     }
3125
3126     // Is it a vector logical left shift?
3127     if (NumElems == 2 && Idx == 1 &&
3128         isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3129       unsigned NumBits = VT.getSizeInBits();
3130       return getVShift(true, VT,
3131                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3132                                    VT, Op.getOperand(1)),
3133                        NumBits/2, DAG, *this, dl);
3134     }
3135
3136     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3137       return SDValue();
3138
3139     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3140     // is a non-constant being inserted into an element other than the low one,
3141     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3142     // movd/movss) to move this into the low element, then shuffle it into
3143     // place.
3144     if (EVTBits == 32) {
3145       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3146
3147       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3148       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3149                                          Subtarget->hasSSE2(), DAG);
3150       SmallVector<int, 8> MaskVec;
3151       for (unsigned i = 0; i < NumElems; i++)
3152         MaskVec.push_back(i == Idx ? 0 : 1);
3153       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3154     }
3155   }
3156
3157   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3158   if (Values.size() == 1)
3159     return SDValue();
3160
3161   // A vector full of immediates; various special cases are already
3162   // handled, so this is best done with a single constant-pool load.
3163   if (IsAllConstants)
3164     return SDValue();
3165
3166   // Let legalizer expand 2-wide build_vectors.
3167   if (EVTBits == 64) {
3168     if (NumNonZero == 1) {
3169       // One half is zero or undef.
3170       unsigned Idx = CountTrailingZeros_32(NonZeros);
3171       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3172                                  Op.getOperand(Idx));
3173       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3174                                          Subtarget->hasSSE2(), DAG);
3175     }
3176     return SDValue();
3177   }
3178
3179   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3180   if (EVTBits == 8 && NumElems == 16) {
3181     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3182                                         *this);
3183     if (V.getNode()) return V;
3184   }
3185
3186   if (EVTBits == 16 && NumElems == 8) {
3187     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3188                                         *this);
3189     if (V.getNode()) return V;
3190   }
3191
3192   // If element VT is == 32 bits, turn it into a number of shuffles.
3193   SmallVector<SDValue, 8> V;
3194   V.resize(NumElems);
3195   if (NumElems == 4 && NumZero > 0) {
3196     for (unsigned i = 0; i < 4; ++i) {
3197       bool isZero = !(NonZeros & (1 << i));
3198       if (isZero)
3199         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3200       else
3201         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3202     }
3203
3204     for (unsigned i = 0; i < 2; ++i) {
3205       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3206         default: break;
3207         case 0:
3208           V[i] = V[i*2];  // Must be a zero vector.
3209           break;
3210         case 1:
3211           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3212           break;
3213         case 2:
3214           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3215           break;
3216         case 3:
3217           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3218           break;
3219       }
3220     }
3221
3222     SmallVector<int, 8> MaskVec;
3223     bool Reverse = (NonZeros & 0x3) == 2;
3224     for (unsigned i = 0; i < 2; ++i)
3225       MaskVec.push_back(Reverse ? 1-i : i);
3226     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3227     for (unsigned i = 0; i < 2; ++i)
3228       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3229     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3230   }
3231
3232   if (Values.size() > 2) {
3233     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3234     // values to be inserted is equal to the number of elements, in which case
3235     // use the unpack code below in the hopes of matching the consecutive elts
3236     // load merge pattern for shuffles. 
3237     // FIXME: We could probably just check that here directly.
3238     if (Values.size() < NumElems && VT.getSizeInBits() == 128 && 
3239         getSubtarget()->hasSSE41()) {
3240       V[0] = DAG.getUNDEF(VT);
3241       for (unsigned i = 0; i < NumElems; ++i)
3242         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3243           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3244                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3245       return V[0];
3246     }
3247     // Expand into a number of unpckl*.
3248     // e.g. for v4f32
3249     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3250     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3251     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3252     for (unsigned i = 0; i < NumElems; ++i)
3253       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3254     NumElems >>= 1;
3255     while (NumElems != 0) {
3256       for (unsigned i = 0; i < NumElems; ++i)
3257         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3258       NumElems >>= 1;
3259     }
3260     return V[0];
3261   }
3262
3263   return SDValue();
3264 }
3265
3266 // v8i16 shuffles - Prefer shuffles in the following order:
3267 // 1. [all]   pshuflw, pshufhw, optional move
3268 // 2. [ssse3] 1 x pshufb
3269 // 3. [ssse3] 2 x pshufb + 1 x por
3270 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3271 static
3272 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3273                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3274   SDValue V1 = SVOp->getOperand(0);
3275   SDValue V2 = SVOp->getOperand(1);
3276   DebugLoc dl = SVOp->getDebugLoc();
3277   SmallVector<int, 8> MaskVals;
3278
3279   // Determine if more than 1 of the words in each of the low and high quadwords
3280   // of the result come from the same quadword of one of the two inputs.  Undef
3281   // mask values count as coming from any quadword, for better codegen.
3282   SmallVector<unsigned, 4> LoQuad(4);
3283   SmallVector<unsigned, 4> HiQuad(4);
3284   BitVector InputQuads(4);
3285   for (unsigned i = 0; i < 8; ++i) {
3286     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3287     int EltIdx = SVOp->getMaskElt(i);
3288     MaskVals.push_back(EltIdx);
3289     if (EltIdx < 0) {
3290       ++Quad[0];
3291       ++Quad[1];
3292       ++Quad[2];
3293       ++Quad[3];
3294       continue;
3295     }
3296     ++Quad[EltIdx / 4];
3297     InputQuads.set(EltIdx / 4);
3298   }
3299
3300   int BestLoQuad = -1;
3301   unsigned MaxQuad = 1;
3302   for (unsigned i = 0; i < 4; ++i) {
3303     if (LoQuad[i] > MaxQuad) {
3304       BestLoQuad = i;
3305       MaxQuad = LoQuad[i];
3306     }
3307   }
3308
3309   int BestHiQuad = -1;
3310   MaxQuad = 1;
3311   for (unsigned i = 0; i < 4; ++i) {
3312     if (HiQuad[i] > MaxQuad) {
3313       BestHiQuad = i;
3314       MaxQuad = HiQuad[i];
3315     }
3316   }
3317
3318   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3319   // of the two input vectors, shuffle them into one input vector so only a 
3320   // single pshufb instruction is necessary. If There are more than 2 input
3321   // quads, disable the next transformation since it does not help SSSE3.
3322   bool V1Used = InputQuads[0] || InputQuads[1];
3323   bool V2Used = InputQuads[2] || InputQuads[3];
3324   if (TLI.getSubtarget()->hasSSSE3()) {
3325     if (InputQuads.count() == 2 && V1Used && V2Used) {
3326       BestLoQuad = InputQuads.find_first();
3327       BestHiQuad = InputQuads.find_next(BestLoQuad);
3328     }
3329     if (InputQuads.count() > 2) {
3330       BestLoQuad = -1;
3331       BestHiQuad = -1;
3332     }
3333   }
3334
3335   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3336   // the shuffle mask.  If a quad is scored as -1, that means that it contains
3337   // words from all 4 input quadwords.
3338   SDValue NewV;
3339   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3340     SmallVector<int, 8> MaskV;
3341     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3342     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3343     NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 
3344                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3345                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3346     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3347
3348     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3349     // source words for the shuffle, to aid later transformations.
3350     bool AllWordsInNewV = true;
3351     bool InOrder[2] = { true, true };
3352     for (unsigned i = 0; i != 8; ++i) {
3353       int idx = MaskVals[i];
3354       if (idx != (int)i)
3355         InOrder[i/4] = false;
3356       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3357         continue;
3358       AllWordsInNewV = false;
3359       break;
3360     }
3361
3362     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3363     if (AllWordsInNewV) {
3364       for (int i = 0; i != 8; ++i) {
3365         int idx = MaskVals[i];
3366         if (idx < 0)
3367           continue;
3368         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 
3369         if ((idx != i) && idx < 4)
3370           pshufhw = false;
3371         if ((idx != i) && idx > 3)
3372           pshuflw = false;
3373       }
3374       V1 = NewV;
3375       V2Used = false;
3376       BestLoQuad = 0;
3377       BestHiQuad = 1;
3378     }
3379
3380     // If we've eliminated the use of V2, and the new mask is a pshuflw or
3381     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
3382     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3383       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 
3384                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3385     }
3386   }
3387   
3388   // If we have SSSE3, and all words of the result are from 1 input vector,
3389   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
3390   // is present, fall back to case 4.
3391   if (TLI.getSubtarget()->hasSSSE3()) {
3392     SmallVector<SDValue,16> pshufbMask;
3393     
3394     // If we have elements from both input vectors, set the high bit of the
3395     // shuffle mask element to zero out elements that come from V2 in the V1 
3396     // mask, and elements that come from V1 in the V2 mask, so that the two
3397     // results can be OR'd together.
3398     bool TwoInputs = V1Used && V2Used;
3399     for (unsigned i = 0; i != 8; ++i) {
3400       int EltIdx = MaskVals[i] * 2;
3401       if (TwoInputs && (EltIdx >= 16)) {
3402         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3403         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3404         continue;
3405       }
3406       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
3407       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3408     }
3409     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3410     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 
3411                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3412                                  MVT::v16i8, &pshufbMask[0], 16));
3413     if (!TwoInputs)
3414       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3415     
3416     // Calculate the shuffle mask for the second input, shuffle it, and
3417     // OR it with the first shuffled input.
3418     pshufbMask.clear();
3419     for (unsigned i = 0; i != 8; ++i) {
3420       int EltIdx = MaskVals[i] * 2;
3421       if (EltIdx < 16) {
3422         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3423         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3424         continue;
3425       }
3426       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3427       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3428     }
3429     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3430     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 
3431                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3432                                  MVT::v16i8, &pshufbMask[0], 16));
3433     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3434     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3435   }
3436
3437   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3438   // and update MaskVals with new element order.
3439   BitVector InOrder(8);
3440   if (BestLoQuad >= 0) {
3441     SmallVector<int, 8> MaskV;
3442     for (int i = 0; i != 4; ++i) {
3443       int idx = MaskVals[i];
3444       if (idx < 0) {
3445         MaskV.push_back(-1);
3446         InOrder.set(i);
3447       } else if ((idx / 4) == BestLoQuad) {
3448         MaskV.push_back(idx & 3);
3449         InOrder.set(i);
3450       } else {
3451         MaskV.push_back(-1);
3452       }
3453     }
3454     for (unsigned i = 4; i != 8; ++i)
3455       MaskV.push_back(i);
3456     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3457                                 &MaskV[0]);
3458   }
3459   
3460   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3461   // and update MaskVals with the new element order.
3462   if (BestHiQuad >= 0) {
3463     SmallVector<int, 8> MaskV;
3464     for (unsigned i = 0; i != 4; ++i)
3465       MaskV.push_back(i);
3466     for (unsigned i = 4; i != 8; ++i) {
3467       int idx = MaskVals[i];
3468       if (idx < 0) {
3469         MaskV.push_back(-1);
3470         InOrder.set(i);
3471       } else if ((idx / 4) == BestHiQuad) {
3472         MaskV.push_back((idx & 3) + 4);
3473         InOrder.set(i);
3474       } else {
3475         MaskV.push_back(-1);
3476       }
3477     }
3478     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3479                                 &MaskV[0]);
3480   }
3481   
3482   // In case BestHi & BestLo were both -1, which means each quadword has a word
3483   // from each of the four input quadwords, calculate the InOrder bitvector now
3484   // before falling through to the insert/extract cleanup.
3485   if (BestLoQuad == -1 && BestHiQuad == -1) {
3486     NewV = V1;
3487     for (int i = 0; i != 8; ++i)
3488       if (MaskVals[i] < 0 || MaskVals[i] == i)
3489         InOrder.set(i);
3490   }
3491   
3492   // The other elements are put in the right place using pextrw and pinsrw.
3493   for (unsigned i = 0; i != 8; ++i) {
3494     if (InOrder[i])
3495       continue;
3496     int EltIdx = MaskVals[i];
3497     if (EltIdx < 0)
3498       continue;
3499     SDValue ExtOp = (EltIdx < 8)
3500     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3501                   DAG.getIntPtrConstant(EltIdx))
3502     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3503                   DAG.getIntPtrConstant(EltIdx - 8));
3504     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3505                        DAG.getIntPtrConstant(i));
3506   }
3507   return NewV;
3508 }
3509
3510 // v16i8 shuffles - Prefer shuffles in the following order:
3511 // 1. [ssse3] 1 x pshufb
3512 // 2. [ssse3] 2 x pshufb + 1 x por
3513 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
3514 static
3515 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3516                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3517   SDValue V1 = SVOp->getOperand(0);
3518   SDValue V2 = SVOp->getOperand(1);
3519   DebugLoc dl = SVOp->getDebugLoc();
3520   SmallVector<int, 16> MaskVals;
3521   SVOp->getMask(MaskVals);
3522   
3523   // If we have SSSE3, case 1 is generated when all result bytes come from
3524   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is 
3525   // present, fall back to case 3.
3526   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3527   bool V1Only = true;
3528   bool V2Only = true;
3529   for (unsigned i = 0; i < 16; ++i) {
3530     int EltIdx = MaskVals[i];
3531     if (EltIdx < 0)
3532       continue;
3533     if (EltIdx < 16)
3534       V2Only = false;
3535     else
3536       V1Only = false;
3537   }
3538   
3539   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3540   if (TLI.getSubtarget()->hasSSSE3()) {
3541     SmallVector<SDValue,16> pshufbMask;
3542     
3543     // If all result elements are from one input vector, then only translate
3544     // undef mask values to 0x80 (zero out result) in the pshufb mask. 
3545     //
3546     // Otherwise, we have elements from both input vectors, and must zero out
3547     // elements that come from V2 in the first mask, and V1 in the second mask
3548     // so that we can OR them together.
3549     bool TwoInputs = !(V1Only || V2Only);
3550     for (unsigned i = 0; i != 16; ++i) {
3551       int EltIdx = MaskVals[i];
3552       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3553         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3554         continue;
3555       }
3556       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3557     }
3558     // If all the elements are from V2, assign it to V1 and return after
3559     // building the first pshufb.
3560     if (V2Only)
3561       V1 = V2;
3562     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3563                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3564                                  MVT::v16i8, &pshufbMask[0], 16));
3565     if (!TwoInputs)
3566       return V1;
3567     
3568     // Calculate the shuffle mask for the second input, shuffle it, and
3569     // OR it with the first shuffled input.
3570     pshufbMask.clear();
3571     for (unsigned i = 0; i != 16; ++i) {
3572       int EltIdx = MaskVals[i];
3573       if (EltIdx < 16) {
3574         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3575         continue;
3576       }
3577       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3578     }
3579     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3580                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3581                                  MVT::v16i8, &pshufbMask[0], 16));
3582     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3583   }
3584   
3585   // No SSSE3 - Calculate in place words and then fix all out of place words
3586   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
3587   // the 16 different words that comprise the two doublequadword input vectors.
3588   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3589   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3590   SDValue NewV = V2Only ? V2 : V1;
3591   for (int i = 0; i != 8; ++i) {
3592     int Elt0 = MaskVals[i*2];
3593     int Elt1 = MaskVals[i*2+1];
3594     
3595     // This word of the result is all undef, skip it.
3596     if (Elt0 < 0 && Elt1 < 0)
3597       continue;
3598     
3599     // This word of the result is already in the correct place, skip it.
3600     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3601       continue;
3602     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3603       continue;
3604     
3605     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3606     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3607     SDValue InsElt;
3608
3609     // If Elt0 and Elt1 are defined, are consecutive, and can be load
3610     // using a single extract together, load it and store it.
3611     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3612       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3613                            DAG.getIntPtrConstant(Elt1 / 2));
3614       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3615                         DAG.getIntPtrConstant(i));
3616       continue;
3617     }
3618
3619     // If Elt1 is defined, extract it from the appropriate source.  If the
3620     // source byte is not also odd, shift the extracted word left 8 bits
3621     // otherwise clear the bottom 8 bits if we need to do an or.
3622     if (Elt1 >= 0) {
3623       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3624                            DAG.getIntPtrConstant(Elt1 / 2));
3625       if ((Elt1 & 1) == 0)
3626         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3627                              DAG.getConstant(8, TLI.getShiftAmountTy()));
3628       else if (Elt0 >= 0)
3629         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3630                              DAG.getConstant(0xFF00, MVT::i16));
3631     }
3632     // If Elt0 is defined, extract it from the appropriate source.  If the
3633     // source byte is not also even, shift the extracted word right 8 bits. If
3634     // Elt1 was also defined, OR the extracted values together before
3635     // inserting them in the result.
3636     if (Elt0 >= 0) {
3637       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3638                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3639       if ((Elt0 & 1) != 0)
3640         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3641                               DAG.getConstant(8, TLI.getShiftAmountTy()));
3642       else if (Elt1 >= 0)
3643         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3644                              DAG.getConstant(0x00FF, MVT::i16));
3645       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3646                          : InsElt0;
3647     }
3648     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3649                        DAG.getIntPtrConstant(i));
3650   }
3651   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3652 }
3653
3654 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3655 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3656 /// done when every pair / quad of shuffle mask elements point to elements in
3657 /// the right sequence. e.g.
3658 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3659 static
3660 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3661                                  SelectionDAG &DAG,
3662                                  TargetLowering &TLI, DebugLoc dl) {
3663   MVT VT = SVOp->getValueType(0);
3664   SDValue V1 = SVOp->getOperand(0);
3665   SDValue V2 = SVOp->getOperand(1);
3666   unsigned NumElems = VT.getVectorNumElements();
3667   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3668   MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3669   MVT MaskEltVT = MaskVT.getVectorElementType();
3670   MVT NewVT = MaskVT;
3671   switch (VT.getSimpleVT()) {
3672   default: assert(false && "Unexpected!");
3673   case MVT::v4f32: NewVT = MVT::v2f64; break;
3674   case MVT::v4i32: NewVT = MVT::v2i64; break;
3675   case MVT::v8i16: NewVT = MVT::v4i32; break;
3676   case MVT::v16i8: NewVT = MVT::v4i32; break;
3677   }
3678
3679   if (NewWidth == 2) {
3680     if (VT.isInteger())
3681       NewVT = MVT::v2i64;
3682     else
3683       NewVT = MVT::v2f64;
3684   }
3685   int Scale = NumElems / NewWidth;
3686   SmallVector<int, 8> MaskVec;
3687   for (unsigned i = 0; i < NumElems; i += Scale) {
3688     int StartIdx = -1;
3689     for (int j = 0; j < Scale; ++j) {
3690       int EltIdx = SVOp->getMaskElt(i+j);
3691       if (EltIdx < 0)
3692         continue;
3693       if (StartIdx == -1)
3694         StartIdx = EltIdx - (EltIdx % Scale);
3695       if (EltIdx != StartIdx + j)
3696         return SDValue();
3697     }
3698     if (StartIdx == -1)
3699       MaskVec.push_back(-1);
3700     else
3701       MaskVec.push_back(StartIdx / Scale);
3702   }
3703
3704   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3705   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3706   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3707 }
3708
3709 /// getVZextMovL - Return a zero-extending vector move low node.
3710 ///
3711 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3712                             SDValue SrcOp, SelectionDAG &DAG,
3713                             const X86Subtarget *Subtarget, DebugLoc dl) {
3714   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3715     LoadSDNode *LD = NULL;
3716     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3717       LD = dyn_cast<LoadSDNode>(SrcOp);
3718     if (!LD) {
3719       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3720       // instead.
3721       MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3722       if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3723           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3724           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3725           SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3726         // PR2108
3727         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3728         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3729                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3730                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3731                                                    OpVT,
3732                                                    SrcOp.getOperand(0)
3733                                                           .getOperand(0))));
3734       }
3735     }
3736   }
3737
3738   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3739                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3740                                  DAG.getNode(ISD::BIT_CONVERT, dl,
3741                                              OpVT, SrcOp)));
3742 }
3743
3744 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3745 /// shuffles.
3746 static SDValue
3747 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3748   SDValue V1 = SVOp->getOperand(0);
3749   SDValue V2 = SVOp->getOperand(1);
3750   DebugLoc dl = SVOp->getDebugLoc();
3751   MVT VT = SVOp->getValueType(0);
3752   
3753   SmallVector<std::pair<int, int>, 8> Locs;
3754   Locs.resize(4);
3755   SmallVector<int, 8> Mask1(4U, -1);
3756   SmallVector<int, 8> PermMask;
3757   SVOp->getMask(PermMask);
3758
3759   unsigned NumHi = 0;
3760   unsigned NumLo = 0;
3761   for (unsigned i = 0; i != 4; ++i) {
3762     int Idx = PermMask[i];
3763     if (Idx < 0) {
3764       Locs[i] = std::make_pair(-1, -1);
3765     } else {
3766       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3767       if (Idx < 4) {
3768         Locs[i] = std::make_pair(0, NumLo);
3769         Mask1[NumLo] = Idx;
3770         NumLo++;
3771       } else {
3772         Locs[i] = std::make_pair(1, NumHi);
3773         if (2+NumHi < 4)
3774           Mask1[2+NumHi] = Idx;
3775         NumHi++;
3776       }
3777     }
3778   }
3779
3780   if (NumLo <= 2 && NumHi <= 2) {
3781     // If no more than two elements come from either vector. This can be
3782     // implemented with two shuffles. First shuffle gather the elements.
3783     // The second shuffle, which takes the first shuffle as both of its
3784     // vector operands, put the elements into the right order.
3785     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3786
3787     SmallVector<int, 8> Mask2(4U, -1);
3788     
3789     for (unsigned i = 0; i != 4; ++i) {
3790       if (Locs[i].first == -1)
3791         continue;
3792       else {
3793         unsigned Idx = (i < 2) ? 0 : 4;
3794         Idx += Locs[i].first * 2 + Locs[i].second;
3795         Mask2[i] = Idx;
3796       }
3797     }
3798
3799     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3800   } else if (NumLo == 3 || NumHi == 3) {
3801     // Otherwise, we must have three elements from one vector, call it X, and
3802     // one element from the other, call it Y.  First, use a shufps to build an
3803     // intermediate vector with the one element from Y and the element from X
3804     // that will be in the same half in the final destination (the indexes don't
3805     // matter). Then, use a shufps to build the final vector, taking the half
3806     // containing the element from Y from the intermediate, and the other half
3807     // from X.
3808     if (NumHi == 3) {
3809       // Normalize it so the 3 elements come from V1.
3810       CommuteVectorShuffleMask(PermMask, VT);
3811       std::swap(V1, V2);
3812     }
3813
3814     // Find the element from V2.
3815     unsigned HiIndex;
3816     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3817       int Val = PermMask[HiIndex];
3818       if (Val < 0)
3819         continue;
3820       if (Val >= 4)
3821         break;
3822     }
3823
3824     Mask1[0] = PermMask[HiIndex];
3825     Mask1[1] = -1;
3826     Mask1[2] = PermMask[HiIndex^1];
3827     Mask1[3] = -1;
3828     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3829
3830     if (HiIndex >= 2) {
3831       Mask1[0] = PermMask[0];
3832       Mask1[1] = PermMask[1];
3833       Mask1[2] = HiIndex & 1 ? 6 : 4;
3834       Mask1[3] = HiIndex & 1 ? 4 : 6;
3835       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3836     } else {
3837       Mask1[0] = HiIndex & 1 ? 2 : 0;
3838       Mask1[1] = HiIndex & 1 ? 0 : 2;
3839       Mask1[2] = PermMask[2];
3840       Mask1[3] = PermMask[3];
3841       if (Mask1[2] >= 0)
3842         Mask1[2] += 4;
3843       if (Mask1[3] >= 0)
3844         Mask1[3] += 4;
3845       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3846     }
3847   }
3848
3849   // Break it into (shuffle shuffle_hi, shuffle_lo).
3850   Locs.clear();
3851   SmallVector<int,8> LoMask(4U, -1);
3852   SmallVector<int,8> HiMask(4U, -1);
3853
3854   SmallVector<int,8> *MaskPtr = &LoMask;
3855   unsigned MaskIdx = 0;
3856   unsigned LoIdx = 0;
3857   unsigned HiIdx = 2;
3858   for (unsigned i = 0; i != 4; ++i) {
3859     if (i == 2) {
3860       MaskPtr = &HiMask;
3861       MaskIdx = 1;
3862       LoIdx = 0;
3863       HiIdx = 2;
3864     }
3865     int Idx = PermMask[i];
3866     if (Idx < 0) {
3867       Locs[i] = std::make_pair(-1, -1);
3868     } else if (Idx < 4) {
3869       Locs[i] = std::make_pair(MaskIdx, LoIdx);
3870       (*MaskPtr)[LoIdx] = Idx;
3871       LoIdx++;
3872     } else {
3873       Locs[i] = std::make_pair(MaskIdx, HiIdx);
3874       (*MaskPtr)[HiIdx] = Idx;
3875       HiIdx++;
3876     }
3877   }
3878
3879   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
3880   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
3881   SmallVector<int, 8> MaskOps;
3882   for (unsigned i = 0; i != 4; ++i) {
3883     if (Locs[i].first == -1) {
3884       MaskOps.push_back(-1);
3885     } else {
3886       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3887       MaskOps.push_back(Idx);
3888     }
3889   }
3890   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
3891 }
3892
3893 SDValue
3894 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3895   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3896   SDValue V1 = Op.getOperand(0);
3897   SDValue V2 = Op.getOperand(1);
3898   MVT VT = Op.getValueType();
3899   DebugLoc dl = Op.getDebugLoc();
3900   unsigned NumElems = VT.getVectorNumElements();
3901   bool isMMX = VT.getSizeInBits() == 64;
3902   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3903   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3904   bool V1IsSplat = false;
3905   bool V2IsSplat = false;
3906
3907   if (isZeroShuffle(SVOp))
3908     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3909
3910   // Promote splats to v4f32.
3911   if (SVOp->isSplat()) {
3912     if (isMMX || NumElems < 4) 
3913       return Op;
3914     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
3915   }
3916
3917   // If the shuffle can be profitably rewritten as a narrower shuffle, then
3918   // do it!
3919   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3920     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3921     if (NewOp.getNode())
3922       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3923                          LowerVECTOR_SHUFFLE(NewOp, DAG));
3924   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3925     // FIXME: Figure out a cleaner way to do this.
3926     // Try to make use of movq to zero out the top part.
3927     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3928       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3929       if (NewOp.getNode()) {
3930         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
3931           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
3932                               DAG, Subtarget, dl);
3933       }
3934     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3935       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3936       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
3937         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3938                             DAG, Subtarget, dl);
3939     }
3940   }
3941   
3942   if (X86::isPSHUFDMask(SVOp))
3943     return Op;
3944   
3945   // Check if this can be converted into a logical shift.
3946   bool isLeft = false;
3947   unsigned ShAmt = 0;
3948   SDValue ShVal;
3949   bool isShift = getSubtarget()->hasSSE2() &&
3950   isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
3951   if (isShift && ShVal.hasOneUse()) {
3952     // If the shifted value has multiple uses, it may be cheaper to use
3953     // v_set0 + movlhps or movhlps, etc.
3954     MVT EVT = VT.getVectorElementType();
3955     ShAmt *= EVT.getSizeInBits();
3956     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3957   }
3958   
3959   if (X86::isMOVLMask(SVOp)) {
3960     if (V1IsUndef)
3961       return V2;
3962     if (ISD::isBuildVectorAllZeros(V1.getNode()))
3963       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
3964     if (!isMMX)
3965       return Op;
3966   }
3967   
3968   // FIXME: fold these into legal mask.
3969   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
3970                  X86::isMOVSLDUPMask(SVOp) ||
3971                  X86::isMOVHLPSMask(SVOp) ||
3972                  X86::isMOVHPMask(SVOp) ||
3973                  X86::isMOVLPMask(SVOp)))
3974     return Op;
3975
3976   if (ShouldXformToMOVHLPS(SVOp) ||
3977       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
3978     return CommuteVectorShuffle(SVOp, DAG);
3979
3980   if (isShift) {
3981     // No better options. Use a vshl / vsrl.
3982     MVT EVT = VT.getVectorElementType();
3983     ShAmt *= EVT.getSizeInBits();
3984     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3985   }
3986   
3987   bool Commuted = false;
3988   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3989   // 1,1,1,1 -> v8i16 though.
3990   V1IsSplat = isSplatVector(V1.getNode());
3991   V2IsSplat = isSplatVector(V2.getNode());
3992
3993   // Canonicalize the splat or undef, if present, to be on the RHS.
3994   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3995     Op = CommuteVectorShuffle(SVOp, DAG);
3996     SVOp = cast<ShuffleVectorSDNode>(Op);
3997     V1 = SVOp->getOperand(0);
3998     V2 = SVOp->getOperand(1);
3999     std::swap(V1IsSplat, V2IsSplat);
4000     std::swap(V1IsUndef, V2IsUndef);
4001     Commuted = true;
4002   }
4003
4004   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4005     // Shuffling low element of v1 into undef, just return v1.
4006     if (V2IsUndef) 
4007       return V1;
4008     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4009     // the instruction selector will not match, so get a canonical MOVL with
4010     // swapped operands to undo the commute.
4011     return getMOVL(DAG, dl, VT, V2, V1);
4012   }
4013
4014   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4015       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4016       X86::isUNPCKLMask(SVOp) ||
4017       X86::isUNPCKHMask(SVOp))
4018     return Op;
4019
4020   if (V2IsSplat) {
4021     // Normalize mask so all entries that point to V2 points to its first
4022     // element then try to match unpck{h|l} again. If match, return a
4023     // new vector_shuffle with the corrected mask.
4024     SDValue NewMask = NormalizeMask(SVOp, DAG);
4025     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4026     if (NSVOp != SVOp) {
4027       if (X86::isUNPCKLMask(NSVOp, true)) {
4028         return NewMask;
4029       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4030         return NewMask;
4031       }
4032     }
4033   }
4034
4035   if (Commuted) {
4036     // Commute is back and try unpck* again.
4037     // FIXME: this seems wrong.
4038     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4039     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4040     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4041         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4042         X86::isUNPCKLMask(NewSVOp) ||
4043         X86::isUNPCKHMask(NewSVOp))
4044       return NewOp;
4045   }
4046
4047   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4048
4049   // Normalize the node to match x86 shuffle ops if needed
4050   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4051     return CommuteVectorShuffle(SVOp, DAG);
4052
4053   // Check for legal shuffle and return?
4054   SmallVector<int, 16> PermMask;
4055   SVOp->getMask(PermMask);
4056   if (isShuffleMaskLegal(PermMask, VT))
4057     return Op;
4058   
4059   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4060   if (VT == MVT::v8i16) {
4061     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4062     if (NewOp.getNode())
4063       return NewOp;
4064   }
4065
4066   if (VT == MVT::v16i8) {
4067     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4068     if (NewOp.getNode())
4069       return NewOp;
4070   }
4071   
4072   // Handle all 4 wide cases with a number of shuffles except for MMX.
4073   if (NumElems == 4 && !isMMX)
4074     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4075
4076   return SDValue();
4077 }
4078
4079 SDValue
4080 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4081                                                 SelectionDAG &DAG) {
4082   MVT VT = Op.getValueType();
4083   DebugLoc dl = Op.getDebugLoc();
4084   if (VT.getSizeInBits() == 8) {
4085     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4086                                     Op.getOperand(0), Op.getOperand(1));
4087     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4088                                     DAG.getValueType(VT));
4089     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4090   } else if (VT.getSizeInBits() == 16) {
4091     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4092     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4093     if (Idx == 0)
4094       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4095                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4096                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4097                                                  MVT::v4i32,
4098                                                  Op.getOperand(0)),
4099                                      Op.getOperand(1)));
4100     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4101                                     Op.getOperand(0), Op.getOperand(1));
4102     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4103                                     DAG.getValueType(VT));
4104     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4105   } else if (VT == MVT::f32) {
4106     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4107     // the result back to FR32 register. It's only worth matching if the
4108     // result has a single use which is a store or a bitcast to i32.  And in
4109     // the case of a store, it's not worth it if the index is a constant 0,
4110     // because a MOVSSmr can be used instead, which is smaller and faster.
4111     if (!Op.hasOneUse())
4112       return SDValue();
4113     SDNode *User = *Op.getNode()->use_begin();
4114     if ((User->getOpcode() != ISD::STORE ||
4115          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4116           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4117         (User->getOpcode() != ISD::BIT_CONVERT ||
4118          User->getValueType(0) != MVT::i32))
4119       return SDValue();
4120     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4121                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4122                                               Op.getOperand(0)),
4123                                               Op.getOperand(1));
4124     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4125   } else if (VT == MVT::i32) {
4126     // ExtractPS works with constant index.
4127     if (isa<ConstantSDNode>(Op.getOperand(1)))
4128       return Op;
4129   }
4130   return SDValue();
4131 }
4132
4133
4134 SDValue
4135 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4136   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4137     return SDValue();
4138
4139   if (Subtarget->hasSSE41()) {
4140     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4141     if (Res.getNode())
4142       return Res;
4143   }
4144
4145   MVT VT = Op.getValueType();
4146   DebugLoc dl = Op.getDebugLoc();
4147   // TODO: handle v16i8.
4148   if (VT.getSizeInBits() == 16) {
4149     SDValue Vec = Op.getOperand(0);
4150     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4151     if (Idx == 0)
4152       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4153                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4154                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4155                                                  MVT::v4i32, Vec),
4156                                      Op.getOperand(1)));
4157     // Transform it so it match pextrw which produces a 32-bit result.
4158     MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4159     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4160                                     Op.getOperand(0), Op.getOperand(1));
4161     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4162                                     DAG.getValueType(VT));
4163     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4164   } else if (VT.getSizeInBits() == 32) {
4165     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4166     if (Idx == 0)
4167       return Op;
4168     
4169     // SHUFPS the element to the lowest double word, then movss.
4170     int Mask[4] = { Idx, -1, -1, -1 };
4171     MVT VVT = Op.getOperand(0).getValueType();
4172     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 
4173                                        DAG.getUNDEF(VVT), Mask);
4174     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4175                        DAG.getIntPtrConstant(0));
4176   } else if (VT.getSizeInBits() == 64) {
4177     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4178     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4179     //        to match extract_elt for f64.
4180     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4181     if (Idx == 0)
4182       return Op;
4183
4184     // UNPCKHPD the element to the lowest double word, then movsd.
4185     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4186     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4187     int Mask[2] = { 1, -1 };
4188     MVT VVT = Op.getOperand(0).getValueType();
4189     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 
4190                                        DAG.getUNDEF(VVT), Mask);
4191     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4192                        DAG.getIntPtrConstant(0));
4193   }
4194
4195   return SDValue();
4196 }
4197
4198 SDValue
4199 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4200   MVT VT = Op.getValueType();
4201   MVT EVT = VT.getVectorElementType();
4202   DebugLoc dl = Op.getDebugLoc();
4203
4204   SDValue N0 = Op.getOperand(0);
4205   SDValue N1 = Op.getOperand(1);
4206   SDValue N2 = Op.getOperand(2);
4207
4208   if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4209       isa<ConstantSDNode>(N2)) {
4210     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4211                                               : X86ISD::PINSRW;
4212     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4213     // argument.
4214     if (N1.getValueType() != MVT::i32)
4215       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4216     if (N2.getValueType() != MVT::i32)
4217       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4218     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4219   } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4220     // Bits [7:6] of the constant are the source select.  This will always be
4221     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4222     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4223     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4224     // Bits [5:4] of the constant are the destination select.  This is the
4225     //  value of the incoming immediate.
4226     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4227     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4228     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4229     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4230   } else if (EVT == MVT::i32) {
4231     // InsertPS works with constant index.
4232     if (isa<ConstantSDNode>(N2))
4233       return Op;
4234   }
4235   return SDValue();
4236 }
4237
4238 SDValue
4239 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4240   MVT VT = Op.getValueType();
4241   MVT EVT = VT.getVectorElementType();
4242
4243   if (Subtarget->hasSSE41())
4244     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4245
4246   if (EVT == MVT::i8)
4247     return SDValue();
4248
4249   DebugLoc dl = Op.getDebugLoc();
4250   SDValue N0 = Op.getOperand(0);
4251   SDValue N1 = Op.getOperand(1);
4252   SDValue N2 = Op.getOperand(2);
4253
4254   if (EVT.getSizeInBits() == 16) {
4255     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4256     // as its second argument.
4257     if (N1.getValueType() != MVT::i32)
4258       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4259     if (N2.getValueType() != MVT::i32)
4260       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4261     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4262   }
4263   return SDValue();
4264 }
4265
4266 SDValue
4267 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4268   DebugLoc dl = Op.getDebugLoc();
4269   if (Op.getValueType() == MVT::v2f32)
4270     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4271                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4272                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4273                                                Op.getOperand(0))));
4274
4275   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4276   MVT VT = MVT::v2i32;
4277   switch (Op.getValueType().getSimpleVT()) {
4278   default: break;
4279   case MVT::v16i8:
4280   case MVT::v8i16:
4281     VT = MVT::v4i32;
4282     break;
4283   }
4284   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4285                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4286 }
4287
4288 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4289 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4290 // one of the above mentioned nodes. It has to be wrapped because otherwise
4291 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4292 // be used to form addressing mode. These wrapped nodes will be selected
4293 // into MOV32ri.
4294 SDValue
4295 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4296   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4297   // FIXME there isn't really any debug info here, should come from the parent
4298   DebugLoc dl = CP->getDebugLoc();
4299   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4300                                              CP->getAlignment());
4301   Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4302   // With PIC, the address is actually $g + Offset.
4303   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4304       !Subtarget->isPICStyleRIPRel()) {
4305     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4306                          DAG.getNode(X86ISD::GlobalBaseReg,
4307                                      DebugLoc::getUnknownLoc(),
4308                                      getPointerTy()),
4309                          Result);
4310   }
4311
4312   return Result;
4313 }
4314
4315 SDValue
4316 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4317                                       int64_t Offset,
4318                                       SelectionDAG &DAG) const {
4319   bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4320   bool ExtraLoadRequired =
4321     Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4322
4323   // Create the TargetGlobalAddress node, folding in the constant
4324   // offset if it is legal.
4325   SDValue Result;
4326   if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4327     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4328     Offset = 0;
4329   } else
4330     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4331   Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4332
4333   // With PIC, the address is actually $g + Offset.
4334   if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4335     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4336                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4337                          Result);
4338   }
4339
4340   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4341   // load the value at address GV, not the value of GV itself. This means that
4342   // the GlobalAddress must be in the base or index register of the address, not
4343   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4344   // The same applies for external symbols during PIC codegen
4345   if (ExtraLoadRequired)
4346     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4347                          PseudoSourceValue::getGOT(), 0);
4348
4349   // If there was a non-zero offset that we didn't fold, create an explicit
4350   // addition for it.
4351   if (Offset != 0)
4352     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4353                          DAG.getConstant(Offset, getPointerTy()));
4354
4355   return Result;
4356 }
4357
4358 SDValue
4359 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4360   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4361   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4362   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4363 }
4364
4365 static SDValue
4366 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4367            SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg) {
4368   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4369   DebugLoc dl = GA->getDebugLoc();
4370   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4371                                            GA->getValueType(0),
4372                                            GA->getOffset());
4373   if (InFlag) {
4374     SDValue Ops[] = { Chain,  TGA, *InFlag };
4375     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4376   } else {
4377     SDValue Ops[]  = { Chain, TGA };
4378     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4379   }
4380   SDValue Flag = Chain.getValue(1);
4381   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4382 }
4383
4384 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4385 static SDValue
4386 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4387                                 const MVT PtrVT) {
4388   SDValue InFlag;
4389   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
4390   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4391                                      DAG.getNode(X86ISD::GlobalBaseReg,
4392                                                  DebugLoc::getUnknownLoc(),
4393                                                  PtrVT), InFlag);
4394   InFlag = Chain.getValue(1);
4395
4396   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX);
4397 }
4398
4399 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4400 static SDValue
4401 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4402                                 const MVT PtrVT) {
4403   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX);
4404 }
4405
4406 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4407 // "local exec" model.
4408 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4409                                    const MVT PtrVT, TLSModel::Model model,
4410                                    bool is64Bit) {
4411   DebugLoc dl = GA->getDebugLoc();
4412   // Get the Thread Pointer
4413   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4414                              DebugLoc::getUnknownLoc(), PtrVT,
4415                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
4416                                              MVT::i32));
4417
4418   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4419                                       NULL, 0);
4420
4421   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4422   // exec)
4423   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4424                                              GA->getValueType(0),
4425                                              GA->getOffset());
4426   SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4427
4428   if (model == TLSModel::InitialExec)
4429     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4430                          PseudoSourceValue::getGOT(), 0);
4431
4432   // The address of the thread local variable is the add of the thread
4433   // pointer with the offset of the variable.
4434   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4435 }
4436
4437 SDValue
4438 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4439   // TODO: implement the "local dynamic" model
4440   // TODO: implement the "initial exec"model for pic executables
4441   assert(Subtarget->isTargetELF() &&
4442          "TLS not implemented for non-ELF targets");
4443   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4444   GlobalValue *GV = GA->getGlobal();
4445   TLSModel::Model model =
4446     getTLSModel (GV, getTargetMachine().getRelocationModel());
4447   if (Subtarget->is64Bit()) {
4448     switch (model) {
4449     case TLSModel::GeneralDynamic:
4450     case TLSModel::LocalDynamic: // not implemented
4451       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4452
4453     case TLSModel::InitialExec:
4454     case TLSModel::LocalExec:
4455       return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, true);
4456     }
4457   } else {
4458     switch (model) {
4459     case TLSModel::GeneralDynamic:
4460     case TLSModel::LocalDynamic: // not implemented
4461       return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4462
4463     case TLSModel::InitialExec:
4464     case TLSModel::LocalExec:
4465       return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, false);
4466     }
4467   }
4468   assert(0 && "Unreachable");
4469   return SDValue();
4470 }
4471
4472 SDValue
4473 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4474   // FIXME there isn't really any debug info here
4475   DebugLoc dl = Op.getDebugLoc();
4476   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4477   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4478   Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4479   // With PIC, the address is actually $g + Offset.
4480   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4481       !Subtarget->isPICStyleRIPRel()) {
4482     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4483                          DAG.getNode(X86ISD::GlobalBaseReg,
4484                                      DebugLoc::getUnknownLoc(),
4485                                      getPointerTy()),
4486                          Result);
4487   }
4488
4489   return Result;
4490 }
4491
4492 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4493   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4494   // FIXME there isn't really any debug into here
4495   DebugLoc dl = JT->getDebugLoc();
4496   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4497   Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4498   // With PIC, the address is actually $g + Offset.
4499   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4500       !Subtarget->isPICStyleRIPRel()) {
4501     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4502                          DAG.getNode(X86ISD::GlobalBaseReg,
4503                                      DebugLoc::getUnknownLoc(),
4504                                      getPointerTy()),
4505                          Result);
4506   }
4507
4508   return Result;
4509 }
4510
4511 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4512 /// take a 2 x i32 value to shift plus a shift amount.
4513 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4514   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4515   MVT VT = Op.getValueType();
4516   unsigned VTBits = VT.getSizeInBits();
4517   DebugLoc dl = Op.getDebugLoc();
4518   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4519   SDValue ShOpLo = Op.getOperand(0);
4520   SDValue ShOpHi = Op.getOperand(1);
4521   SDValue ShAmt  = Op.getOperand(2);
4522   SDValue Tmp1 = isSRA ?
4523     DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4524                 DAG.getConstant(VTBits - 1, MVT::i8)) :
4525     DAG.getConstant(0, VT);
4526
4527   SDValue Tmp2, Tmp3;
4528   if (Op.getOpcode() == ISD::SHL_PARTS) {
4529     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4530     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4531   } else {
4532     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4533     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4534   }
4535
4536   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4537                                   DAG.getConstant(VTBits, MVT::i8));
4538   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4539                                AndNode, DAG.getConstant(0, MVT::i8));
4540
4541   SDValue Hi, Lo;
4542   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4543   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4544   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4545
4546   if (Op.getOpcode() == ISD::SHL_PARTS) {
4547     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4548     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4549   } else {
4550     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4551     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4552   }
4553
4554   SDValue Ops[2] = { Lo, Hi };
4555   return DAG.getMergeValues(Ops, 2, dl);
4556 }
4557
4558 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4559   MVT SrcVT = Op.getOperand(0).getValueType();
4560   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4561          "Unknown SINT_TO_FP to lower!");
4562
4563   // These are really Legal; return the operand so the caller accepts it as
4564   // Legal.
4565   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4566     return Op;
4567   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4568       Subtarget->is64Bit()) {
4569     return Op;
4570   }
4571
4572   DebugLoc dl = Op.getDebugLoc();
4573   unsigned Size = SrcVT.getSizeInBits()/8;
4574   MachineFunction &MF = DAG.getMachineFunction();
4575   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4576   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4577   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4578                                StackSlot,
4579                                PseudoSourceValue::getFixedStack(SSFI), 0);
4580   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4581 }
4582
4583 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4584                                      SDValue StackSlot,
4585                                      SelectionDAG &DAG) {
4586   // Build the FILD
4587   DebugLoc dl = Op.getDebugLoc();
4588   SDVTList Tys;
4589   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4590   if (useSSE)
4591     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4592   else
4593     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4594   SmallVector<SDValue, 8> Ops;
4595   Ops.push_back(Chain);
4596   Ops.push_back(StackSlot);
4597   Ops.push_back(DAG.getValueType(SrcVT));
4598   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4599                                  Tys, &Ops[0], Ops.size());
4600
4601   if (useSSE) {
4602     Chain = Result.getValue(1);
4603     SDValue InFlag = Result.getValue(2);
4604
4605     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4606     // shouldn't be necessary except that RFP cannot be live across
4607     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4608     MachineFunction &MF = DAG.getMachineFunction();
4609     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4610     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4611     Tys = DAG.getVTList(MVT::Other);
4612     SmallVector<SDValue, 8> Ops;
4613     Ops.push_back(Chain);
4614     Ops.push_back(Result);
4615     Ops.push_back(StackSlot);
4616     Ops.push_back(DAG.getValueType(Op.getValueType()));
4617     Ops.push_back(InFlag);
4618     Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4619     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4620                          PseudoSourceValue::getFixedStack(SSFI), 0);
4621   }
4622
4623   return Result;
4624 }
4625
4626 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4627 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4628   // This algorithm is not obvious. Here it is in C code, more or less:
4629   /*
4630     double uint64_to_double( uint32_t hi, uint32_t lo ) {
4631       static const __m128i exp = { 0x4330000045300000ULL, 0 };
4632       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4633
4634       // Copy ints to xmm registers.
4635       __m128i xh = _mm_cvtsi32_si128( hi );
4636       __m128i xl = _mm_cvtsi32_si128( lo );
4637
4638       // Combine into low half of a single xmm register.
4639       __m128i x = _mm_unpacklo_epi32( xh, xl );
4640       __m128d d;
4641       double sd;
4642
4643       // Merge in appropriate exponents to give the integer bits the right
4644       // magnitude.
4645       x = _mm_unpacklo_epi32( x, exp );
4646
4647       // Subtract away the biases to deal with the IEEE-754 double precision
4648       // implicit 1.
4649       d = _mm_sub_pd( (__m128d) x, bias );
4650
4651       // All conversions up to here are exact. The correctly rounded result is
4652       // calculated using the current rounding mode using the following
4653       // horizontal add.
4654       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4655       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
4656                                 // store doesn't really need to be here (except
4657                                 // maybe to zero the other double)
4658       return sd;
4659     }
4660   */
4661
4662   DebugLoc dl = Op.getDebugLoc();
4663
4664   // Build some magic constants.
4665   std::vector<Constant*> CV0;
4666   CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4667   CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4668   CV0.push_back(ConstantInt::get(APInt(32, 0)));
4669   CV0.push_back(ConstantInt::get(APInt(32, 0)));
4670   Constant *C0 = ConstantVector::get(CV0);
4671   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4672
4673   std::vector<Constant*> CV1;
4674   CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4675   CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4676   Constant *C1 = ConstantVector::get(CV1);
4677   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4678
4679   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4680                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4681                                         Op.getOperand(0),
4682                                         DAG.getIntPtrConstant(1)));
4683   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4684                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4685                                         Op.getOperand(0),
4686                                         DAG.getIntPtrConstant(0)));
4687   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4688   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4689                               PseudoSourceValue::getConstantPool(), 0,
4690                               false, 16);
4691   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4692   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4693   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4694                               PseudoSourceValue::getConstantPool(), 0,
4695                               false, 16);
4696   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4697
4698   // Add the halves; easiest way is to swap them into another reg first.
4699   int ShufMask[2] = { 1, -1 };
4700   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4701                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
4702   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4703   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4704                      DAG.getIntPtrConstant(0));
4705 }
4706
4707 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4708 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4709   DebugLoc dl = Op.getDebugLoc();
4710   // FP constant to bias correct the final result.
4711   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4712                                    MVT::f64);
4713
4714   // Load the 32-bit value into an XMM register.
4715   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4716                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4717                                          Op.getOperand(0),
4718                                          DAG.getIntPtrConstant(0)));
4719
4720   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4721                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4722                      DAG.getIntPtrConstant(0));
4723
4724   // Or the load with the bias.
4725   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4726                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4727                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4728                                                    MVT::v2f64, Load)),
4729                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4730                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4731                                                    MVT::v2f64, Bias)));
4732   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4733                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4734                    DAG.getIntPtrConstant(0));
4735
4736   // Subtract the bias.
4737   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4738
4739   // Handle final rounding.
4740   MVT DestVT = Op.getValueType();
4741
4742   if (DestVT.bitsLT(MVT::f64)) {
4743     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4744                        DAG.getIntPtrConstant(0));
4745   } else if (DestVT.bitsGT(MVT::f64)) {
4746     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4747   }
4748
4749   // Handle final rounding.
4750   return Sub;
4751 }
4752
4753 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4754   SDValue N0 = Op.getOperand(0);
4755   DebugLoc dl = Op.getDebugLoc();
4756
4757   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4758   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4759   // the optimization here.
4760   if (DAG.SignBitIsZero(N0))
4761     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4762
4763   MVT SrcVT = N0.getValueType();
4764   if (SrcVT == MVT::i64) {
4765     // We only handle SSE2 f64 target here; caller can expand the rest.
4766     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4767       return SDValue();
4768
4769     return LowerUINT_TO_FP_i64(Op, DAG);
4770   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
4771     return LowerUINT_TO_FP_i32(Op, DAG);
4772   }
4773
4774   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
4775
4776   // Make a 64-bit buffer, and use it to build an FILD.
4777   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
4778   SDValue WordOff = DAG.getConstant(4, getPointerTy());
4779   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
4780                                    getPointerTy(), StackSlot, WordOff);
4781   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4782                                 StackSlot, NULL, 0);
4783   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
4784                                 OffsetSlot, NULL, 0);
4785   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
4786 }
4787
4788 std::pair<SDValue,SDValue> X86TargetLowering::
4789 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
4790   DebugLoc dl = Op.getDebugLoc();
4791
4792   MVT DstTy = Op.getValueType();
4793
4794   if (!IsSigned) {
4795     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
4796     DstTy = MVT::i64;
4797   }
4798
4799   assert(DstTy.getSimpleVT() <= MVT::i64 &&
4800          DstTy.getSimpleVT() >= MVT::i16 &&
4801          "Unknown FP_TO_SINT to lower!");
4802
4803   // These are really Legal.
4804   if (DstTy == MVT::i32 &&
4805       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4806     return std::make_pair(SDValue(), SDValue());
4807   if (Subtarget->is64Bit() &&
4808       DstTy == MVT::i64 &&
4809       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4810     return std::make_pair(SDValue(), SDValue());
4811
4812   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4813   // stack slot.
4814   MachineFunction &MF = DAG.getMachineFunction();
4815   unsigned MemSize = DstTy.getSizeInBits()/8;
4816   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4817   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4818   
4819   unsigned Opc;
4820   switch (DstTy.getSimpleVT()) {
4821   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4822   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4823   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4824   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4825   }
4826
4827   SDValue Chain = DAG.getEntryNode();
4828   SDValue Value = Op.getOperand(0);
4829   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4830     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4831     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
4832                          PseudoSourceValue::getFixedStack(SSFI), 0);
4833     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4834     SDValue Ops[] = {
4835       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4836     };
4837     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
4838     Chain = Value.getValue(1);
4839     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4840     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4841   }
4842
4843   // Build the FP_TO_INT*_IN_MEM
4844   SDValue Ops[] = { Chain, Value, StackSlot };
4845   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
4846
4847   return std::make_pair(FIST, StackSlot);
4848 }
4849
4850 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4851   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
4852   SDValue FIST = Vals.first, StackSlot = Vals.second;
4853   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
4854   if (FIST.getNode() == 0) return Op;
4855
4856   // Load the result.
4857   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4858                      FIST, StackSlot, NULL, 0);
4859 }
4860
4861 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
4862   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
4863   SDValue FIST = Vals.first, StackSlot = Vals.second;
4864   assert(FIST.getNode() && "Unexpected failure");
4865
4866   // Load the result.
4867   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4868                      FIST, StackSlot, NULL, 0);
4869 }
4870
4871 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4872   DebugLoc dl = Op.getDebugLoc();
4873   MVT VT = Op.getValueType();
4874   MVT EltVT = VT;
4875   if (VT.isVector())
4876     EltVT = VT.getVectorElementType();
4877   std::vector<Constant*> CV;
4878   if (EltVT == MVT::f64) {
4879     Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4880     CV.push_back(C);
4881     CV.push_back(C);
4882   } else {
4883     Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4884     CV.push_back(C);
4885     CV.push_back(C);
4886     CV.push_back(C);
4887     CV.push_back(C);
4888   }
4889   Constant *C = ConstantVector::get(CV);
4890   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4891   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4892                                PseudoSourceValue::getConstantPool(), 0,
4893                                false, 16);
4894   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
4895 }
4896
4897 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4898   DebugLoc dl = Op.getDebugLoc();
4899   MVT VT = Op.getValueType();
4900   MVT EltVT = VT;
4901   unsigned EltNum = 1;
4902   if (VT.isVector()) {
4903     EltVT = VT.getVectorElementType();
4904     EltNum = VT.getVectorNumElements();
4905   }
4906   std::vector<Constant*> CV;
4907   if (EltVT == MVT::f64) {
4908     Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4909     CV.push_back(C);
4910     CV.push_back(C);
4911   } else {
4912     Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4913     CV.push_back(C);
4914     CV.push_back(C);
4915     CV.push_back(C);
4916     CV.push_back(C);
4917   }
4918   Constant *C = ConstantVector::get(CV);
4919   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4920   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4921                                PseudoSourceValue::getConstantPool(), 0,
4922                                false, 16);
4923   if (VT.isVector()) {
4924     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4925                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
4926                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4927                                 Op.getOperand(0)),
4928                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
4929   } else {
4930     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
4931   }
4932 }
4933
4934 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4935   SDValue Op0 = Op.getOperand(0);
4936   SDValue Op1 = Op.getOperand(1);
4937   DebugLoc dl = Op.getDebugLoc();
4938   MVT VT = Op.getValueType();
4939   MVT SrcVT = Op1.getValueType();
4940
4941   // If second operand is smaller, extend it first.
4942   if (SrcVT.bitsLT(VT)) {
4943     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
4944     SrcVT = VT;
4945   }
4946   // And if it is bigger, shrink it first.
4947   if (SrcVT.bitsGT(VT)) {
4948     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
4949     SrcVT = VT;
4950   }
4951
4952   // At this point the operands and the result should have the same
4953   // type, and that won't be f80 since that is not custom lowered.
4954
4955   // First get the sign bit of second operand.
4956   std::vector<Constant*> CV;
4957   if (SrcVT == MVT::f64) {
4958     CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4959     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4960   } else {
4961     CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4962     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4963     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4964     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4965   }
4966   Constant *C = ConstantVector::get(CV);
4967   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4968   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
4969                                 PseudoSourceValue::getConstantPool(), 0,
4970                                 false, 16);
4971   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
4972
4973   // Shift sign bit right or left if the two operands have different types.
4974   if (SrcVT.bitsGT(VT)) {
4975     // Op0 is MVT::f32, Op1 is MVT::f64.
4976     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
4977     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
4978                           DAG.getConstant(32, MVT::i32));
4979     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
4980     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
4981                           DAG.getIntPtrConstant(0));
4982   }
4983
4984   // Clear first operand sign bit.
4985   CV.clear();
4986   if (VT == MVT::f64) {
4987     CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4988     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4989   } else {
4990     CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4991     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4992     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4993     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4994   }
4995   C = ConstantVector::get(CV);
4996   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4997   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4998                                 PseudoSourceValue::getConstantPool(), 0,
4999                                 false, 16);
5000   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5001
5002   // Or the value with the sign bit.
5003   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5004 }
5005
5006 /// Emit nodes that will be selected as "test Op0,Op0", or something
5007 /// equivalent.
5008 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5009                                     SelectionDAG &DAG) {
5010   DebugLoc dl = Op.getDebugLoc();
5011
5012   // CF and OF aren't always set the way we want. Determine which
5013   // of these we need.
5014   bool NeedCF = false;
5015   bool NeedOF = false;
5016   switch (X86CC) {
5017   case X86::COND_A: case X86::COND_AE:
5018   case X86::COND_B: case X86::COND_BE:
5019     NeedCF = true;
5020     break;
5021   case X86::COND_G: case X86::COND_GE:
5022   case X86::COND_L: case X86::COND_LE:
5023   case X86::COND_O: case X86::COND_NO:
5024     NeedOF = true;
5025     break;
5026   default: break;
5027   }
5028
5029   // See if we can use the EFLAGS value from the operand instead of
5030   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5031   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5032   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5033     unsigned Opcode = 0;
5034     unsigned NumOperands = 0;
5035     switch (Op.getNode()->getOpcode()) {
5036     case ISD::ADD:
5037       // Due to an isel shortcoming, be conservative if this add is likely to
5038       // be selected as part of a load-modify-store instruction. When the root
5039       // node in a match is a store, isel doesn't know how to remap non-chain
5040       // non-flag uses of other nodes in the match, such as the ADD in this
5041       // case. This leads to the ADD being left around and reselected, with
5042       // the result being two adds in the output.
5043       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5044            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5045         if (UI->getOpcode() == ISD::STORE)
5046           goto default_case;
5047       if (ConstantSDNode *C =
5048             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5049         // An add of one will be selected as an INC.
5050         if (C->getAPIntValue() == 1) {
5051           Opcode = X86ISD::INC;
5052           NumOperands = 1;
5053           break;
5054         }
5055         // An add of negative one (subtract of one) will be selected as a DEC.
5056         if (C->getAPIntValue().isAllOnesValue()) {
5057           Opcode = X86ISD::DEC;
5058           NumOperands = 1;
5059           break;
5060         }
5061       }
5062       // Otherwise use a regular EFLAGS-setting add.
5063       Opcode = X86ISD::ADD;
5064       NumOperands = 2;
5065       break;
5066     case ISD::SUB:
5067       // Due to the ISEL shortcoming noted above, be conservative if this sub is
5068       // likely to be selected as part of a load-modify-store instruction.
5069       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5070            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5071         if (UI->getOpcode() == ISD::STORE)
5072           goto default_case;
5073       // Otherwise use a regular EFLAGS-setting sub.
5074       Opcode = X86ISD::SUB;
5075       NumOperands = 2;
5076       break;
5077     case X86ISD::ADD:
5078     case X86ISD::SUB:
5079     case X86ISD::INC:
5080     case X86ISD::DEC:
5081       return SDValue(Op.getNode(), 1);
5082     default:
5083     default_case:
5084       break;
5085     }
5086     if (Opcode != 0) {
5087       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5088       SmallVector<SDValue, 4> Ops;
5089       for (unsigned i = 0; i != NumOperands; ++i)
5090         Ops.push_back(Op.getOperand(i));
5091       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5092       DAG.ReplaceAllUsesWith(Op, New);
5093       return SDValue(New.getNode(), 1);
5094     }
5095   }
5096
5097   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5098   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5099                      DAG.getConstant(0, Op.getValueType()));
5100 }
5101
5102 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5103 /// equivalent.
5104 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5105                                    SelectionDAG &DAG) {
5106   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5107     if (C->getAPIntValue() == 0)
5108       return EmitTest(Op0, X86CC, DAG);
5109
5110   DebugLoc dl = Op0.getDebugLoc();
5111   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5112 }
5113
5114 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5115   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5116   SDValue Op0 = Op.getOperand(0);
5117   SDValue Op1 = Op.getOperand(1);
5118   DebugLoc dl = Op.getDebugLoc();
5119   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5120
5121   // Lower (X & (1 << N)) == 0 to BT(X, N).
5122   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5123   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5124   if (Op0.getOpcode() == ISD::AND &&
5125       Op0.hasOneUse() &&
5126       Op1.getOpcode() == ISD::Constant &&
5127       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5128       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5129     SDValue LHS, RHS;
5130     if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5131       if (ConstantSDNode *Op010C =
5132             dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5133         if (Op010C->getZExtValue() == 1) {
5134           LHS = Op0.getOperand(0);
5135           RHS = Op0.getOperand(1).getOperand(1);
5136         }
5137     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5138       if (ConstantSDNode *Op000C =
5139             dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5140         if (Op000C->getZExtValue() == 1) {
5141           LHS = Op0.getOperand(1);
5142           RHS = Op0.getOperand(0).getOperand(1);
5143         }
5144     } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5145       ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5146       SDValue AndLHS = Op0.getOperand(0);
5147       if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5148         LHS = AndLHS.getOperand(0);
5149         RHS = AndLHS.getOperand(1);
5150       }
5151     }
5152
5153     if (LHS.getNode()) {
5154       // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5155       // instruction.  Since the shift amount is in-range-or-undefined, we know
5156       // that doing a bittest on the i16 value is ok.  We extend to i32 because
5157       // the encoding for the i16 version is larger than the i32 version.
5158       if (LHS.getValueType() == MVT::i8)
5159         LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5160
5161       // If the operand types disagree, extend the shift amount to match.  Since
5162       // BT ignores high bits (like shifts) we can use anyextend.
5163       if (LHS.getValueType() != RHS.getValueType())
5164         RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5165
5166       SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5167       unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5168       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5169                          DAG.getConstant(Cond, MVT::i8), BT);
5170     }
5171   }
5172
5173   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5174   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5175
5176   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5177   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5178                      DAG.getConstant(X86CC, MVT::i8), Cond);
5179 }
5180
5181 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5182   SDValue Cond;
5183   SDValue Op0 = Op.getOperand(0);
5184   SDValue Op1 = Op.getOperand(1);
5185   SDValue CC = Op.getOperand(2);
5186   MVT VT = Op.getValueType();
5187   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5188   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5189   DebugLoc dl = Op.getDebugLoc();
5190
5191   if (isFP) {
5192     unsigned SSECC = 8;
5193     MVT VT0 = Op0.getValueType();
5194     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5195     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5196     bool Swap = false;
5197
5198     switch (SetCCOpcode) {
5199     default: break;
5200     case ISD::SETOEQ:
5201     case ISD::SETEQ:  SSECC = 0; break;
5202     case ISD::SETOGT:
5203     case ISD::SETGT: Swap = true; // Fallthrough
5204     case ISD::SETLT:
5205     case ISD::SETOLT: SSECC = 1; break;
5206     case ISD::SETOGE:
5207     case ISD::SETGE: Swap = true; // Fallthrough
5208     case ISD::SETLE:
5209     case ISD::SETOLE: SSECC = 2; break;
5210     case ISD::SETUO:  SSECC = 3; break;
5211     case ISD::SETUNE:
5212     case ISD::SETNE:  SSECC = 4; break;
5213     case ISD::SETULE: Swap = true;
5214     case ISD::SETUGE: SSECC = 5; break;
5215     case ISD::SETULT: Swap = true;
5216     case ISD::SETUGT: SSECC = 6; break;
5217     case ISD::SETO:   SSECC = 7; break;
5218     }
5219     if (Swap)
5220       std::swap(Op0, Op1);
5221
5222     // In the two special cases we can't handle, emit two comparisons.
5223     if (SSECC == 8) {
5224       if (SetCCOpcode == ISD::SETUEQ) {
5225         SDValue UNORD, EQ;
5226         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5227         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5228         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5229       }
5230       else if (SetCCOpcode == ISD::SETONE) {
5231         SDValue ORD, NEQ;
5232         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5233         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5234         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5235       }
5236       assert(0 && "Illegal FP comparison");
5237     }
5238     // Handle all other FP comparisons here.
5239     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5240   }
5241
5242   // We are handling one of the integer comparisons here.  Since SSE only has
5243   // GT and EQ comparisons for integer, swapping operands and multiple
5244   // operations may be required for some comparisons.
5245   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5246   bool Swap = false, Invert = false, FlipSigns = false;
5247
5248   switch (VT.getSimpleVT()) {
5249   default: break;
5250   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5251   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5252   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5253   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5254   }
5255
5256   switch (SetCCOpcode) {
5257   default: break;
5258   case ISD::SETNE:  Invert = true;
5259   case ISD::SETEQ:  Opc = EQOpc; break;
5260   case ISD::SETLT:  Swap = true;
5261   case ISD::SETGT:  Opc = GTOpc; break;
5262   case ISD::SETGE:  Swap = true;
5263   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
5264   case ISD::SETULT: Swap = true;
5265   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5266   case ISD::SETUGE: Swap = true;
5267   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5268   }
5269   if (Swap)
5270     std::swap(Op0, Op1);
5271
5272   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
5273   // bits of the inputs before performing those operations.
5274   if (FlipSigns) {
5275     MVT EltVT = VT.getVectorElementType();
5276     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5277                                       EltVT);
5278     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5279     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5280                                     SignBits.size());
5281     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5282     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5283   }
5284
5285   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5286
5287   // If the logical-not of the result is required, perform that now.
5288   if (Invert)
5289     Result = DAG.getNOT(dl, Result, VT);
5290
5291   return Result;
5292 }
5293
5294 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5295 static bool isX86LogicalCmp(SDValue Op) {
5296   unsigned Opc = Op.getNode()->getOpcode();
5297   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5298     return true;
5299   if (Op.getResNo() == 1 &&
5300       (Opc == X86ISD::ADD ||
5301        Opc == X86ISD::SUB ||
5302        Opc == X86ISD::SMUL ||
5303        Opc == X86ISD::UMUL ||
5304        Opc == X86ISD::INC ||
5305        Opc == X86ISD::DEC))
5306     return true;
5307
5308   return false;
5309 }
5310
5311 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5312   bool addTest = true;
5313   SDValue Cond  = Op.getOperand(0);
5314   DebugLoc dl = Op.getDebugLoc();
5315   SDValue CC;
5316
5317   if (Cond.getOpcode() == ISD::SETCC)
5318     Cond = LowerSETCC(Cond, DAG);
5319
5320   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5321   // setting operand in place of the X86ISD::SETCC.
5322   if (Cond.getOpcode() == X86ISD::SETCC) {
5323     CC = Cond.getOperand(0);
5324
5325     SDValue Cmp = Cond.getOperand(1);
5326     unsigned Opc = Cmp.getOpcode();
5327     MVT VT = Op.getValueType();
5328
5329     bool IllegalFPCMov = false;
5330     if (VT.isFloatingPoint() && !VT.isVector() &&
5331         !isScalarFPTypeInSSEReg(VT))  // FPStack?
5332       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5333
5334     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5335         Opc == X86ISD::BT) { // FIXME
5336       Cond = Cmp;
5337       addTest = false;
5338     }
5339   }
5340
5341   if (addTest) {
5342     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5343     Cond = EmitTest(Cond, X86::COND_NE, DAG);
5344   }
5345
5346   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5347   SmallVector<SDValue, 4> Ops;
5348   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5349   // condition is true.
5350   Ops.push_back(Op.getOperand(2));
5351   Ops.push_back(Op.getOperand(1));
5352   Ops.push_back(CC);
5353   Ops.push_back(Cond);
5354   return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5355 }
5356
5357 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5358 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5359 // from the AND / OR.
5360 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5361   Opc = Op.getOpcode();
5362   if (Opc != ISD::OR && Opc != ISD::AND)
5363     return false;
5364   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5365           Op.getOperand(0).hasOneUse() &&
5366           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5367           Op.getOperand(1).hasOneUse());
5368 }
5369
5370 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5371 // 1 and that the SETCC node has a single use.
5372 static bool isXor1OfSetCC(SDValue Op) {
5373   if (Op.getOpcode() != ISD::XOR)
5374     return false;
5375   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5376   if (N1C && N1C->getAPIntValue() == 1) {
5377     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5378       Op.getOperand(0).hasOneUse();
5379   }
5380   return false;
5381 }
5382
5383 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5384   bool addTest = true;
5385   SDValue Chain = Op.getOperand(0);
5386   SDValue Cond  = Op.getOperand(1);
5387   SDValue Dest  = Op.getOperand(2);
5388   DebugLoc dl = Op.getDebugLoc();
5389   SDValue CC;
5390
5391   if (Cond.getOpcode() == ISD::SETCC)
5392     Cond = LowerSETCC(Cond, DAG);
5393 #if 0
5394   // FIXME: LowerXALUO doesn't handle these!!
5395   else if (Cond.getOpcode() == X86ISD::ADD  ||
5396            Cond.getOpcode() == X86ISD::SUB  ||
5397            Cond.getOpcode() == X86ISD::SMUL ||
5398            Cond.getOpcode() == X86ISD::UMUL)
5399     Cond = LowerXALUO(Cond, DAG);
5400 #endif
5401
5402   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5403   // setting operand in place of the X86ISD::SETCC.
5404   if (Cond.getOpcode() == X86ISD::SETCC) {
5405     CC = Cond.getOperand(0);
5406
5407     SDValue Cmp = Cond.getOperand(1);
5408     unsigned Opc = Cmp.getOpcode();
5409     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5410     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5411       Cond = Cmp;
5412       addTest = false;
5413     } else {
5414       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5415       default: break;
5416       case X86::COND_O:
5417       case X86::COND_B:
5418         // These can only come from an arithmetic instruction with overflow,
5419         // e.g. SADDO, UADDO.
5420         Cond = Cond.getNode()->getOperand(1);
5421         addTest = false;
5422         break;
5423       }
5424     }
5425   } else {
5426     unsigned CondOpc;
5427     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5428       SDValue Cmp = Cond.getOperand(0).getOperand(1);
5429       if (CondOpc == ISD::OR) {
5430         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5431         // two branches instead of an explicit OR instruction with a
5432         // separate test.
5433         if (Cmp == Cond.getOperand(1).getOperand(1) &&
5434             isX86LogicalCmp(Cmp)) {
5435           CC = Cond.getOperand(0).getOperand(0);
5436           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5437                               Chain, Dest, CC, Cmp);
5438           CC = Cond.getOperand(1).getOperand(0);
5439           Cond = Cmp;
5440           addTest = false;
5441         }
5442       } else { // ISD::AND
5443         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5444         // two branches instead of an explicit AND instruction with a
5445         // separate test. However, we only do this if this block doesn't
5446         // have a fall-through edge, because this requires an explicit
5447         // jmp when the condition is false.
5448         if (Cmp == Cond.getOperand(1).getOperand(1) &&
5449             isX86LogicalCmp(Cmp) &&
5450             Op.getNode()->hasOneUse()) {
5451           X86::CondCode CCode =
5452             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5453           CCode = X86::GetOppositeBranchCondition(CCode);
5454           CC = DAG.getConstant(CCode, MVT::i8);
5455           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5456           // Look for an unconditional branch following this conditional branch.
5457           // We need this because we need to reverse the successors in order
5458           // to implement FCMP_OEQ.
5459           if (User.getOpcode() == ISD::BR) {
5460             SDValue FalseBB = User.getOperand(1);
5461             SDValue NewBR =
5462               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5463             assert(NewBR == User);
5464             Dest = FalseBB;
5465
5466             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5467                                 Chain, Dest, CC, Cmp);
5468             X86::CondCode CCode =
5469               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5470             CCode = X86::GetOppositeBranchCondition(CCode);
5471             CC = DAG.getConstant(CCode, MVT::i8);
5472             Cond = Cmp;
5473             addTest = false;
5474           }
5475         }
5476       }
5477     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5478       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5479       // It should be transformed during dag combiner except when the condition
5480       // is set by a arithmetics with overflow node.
5481       X86::CondCode CCode =
5482         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5483       CCode = X86::GetOppositeBranchCondition(CCode);
5484       CC = DAG.getConstant(CCode, MVT::i8);
5485       Cond = Cond.getOperand(0).getOperand(1);
5486       addTest = false;
5487     }
5488   }
5489
5490   if (addTest) {
5491     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5492     Cond = EmitTest(Cond, X86::COND_NE, DAG);
5493   }
5494   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5495                      Chain, Dest, CC, Cond);
5496 }
5497
5498
5499 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5500 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5501 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5502 // that the guard pages used by the OS virtual memory manager are allocated in
5503 // correct sequence.
5504 SDValue
5505 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5506                                            SelectionDAG &DAG) {
5507   assert(Subtarget->isTargetCygMing() &&
5508          "This should be used only on Cygwin/Mingw targets");
5509   DebugLoc dl = Op.getDebugLoc();
5510
5511   // Get the inputs.
5512   SDValue Chain = Op.getOperand(0);
5513   SDValue Size  = Op.getOperand(1);
5514   // FIXME: Ensure alignment here
5515
5516   SDValue Flag;
5517
5518   MVT IntPtr = getPointerTy();
5519   MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5520
5521   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5522
5523   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5524   Flag = Chain.getValue(1);
5525
5526   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5527   SDValue Ops[] = { Chain,
5528                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
5529                       DAG.getRegister(X86::EAX, IntPtr),
5530                       DAG.getRegister(X86StackPtr, SPTy),
5531                       Flag };
5532   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5533   Flag = Chain.getValue(1);
5534
5535   Chain = DAG.getCALLSEQ_END(Chain,
5536                              DAG.getIntPtrConstant(0, true),
5537                              DAG.getIntPtrConstant(0, true),
5538                              Flag);
5539
5540   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5541
5542   SDValue Ops1[2] = { Chain.getValue(0), Chain };
5543   return DAG.getMergeValues(Ops1, 2, dl);
5544 }
5545
5546 SDValue
5547 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5548                                            SDValue Chain,
5549                                            SDValue Dst, SDValue Src,
5550                                            SDValue Size, unsigned Align,
5551                                            const Value *DstSV,
5552                                            uint64_t DstSVOff) {
5553   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5554
5555   // If not DWORD aligned or size is more than the threshold, call the library.
5556   // The libc version is likely to be faster for these cases. It can use the
5557   // address value and run time information about the CPU.
5558   if ((Align & 3) != 0 ||
5559       !ConstantSize ||
5560       ConstantSize->getZExtValue() >
5561         getSubtarget()->getMaxInlineSizeThreshold()) {
5562     SDValue InFlag(0, 0);
5563
5564     // Check to see if there is a specialized entry-point for memory zeroing.
5565     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5566
5567     if (const char *bzeroEntry =  V &&
5568         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5569       MVT IntPtr = getPointerTy();
5570       const Type *IntPtrTy = TD->getIntPtrType();
5571       TargetLowering::ArgListTy Args;
5572       TargetLowering::ArgListEntry Entry;
5573       Entry.Node = Dst;
5574       Entry.Ty = IntPtrTy;
5575       Args.push_back(Entry);
5576       Entry.Node = Size;
5577       Args.push_back(Entry);
5578       std::pair<SDValue,SDValue> CallResult =
5579         LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5580                     CallingConv::C, false,
5581                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5582       return CallResult.second;
5583     }
5584
5585     // Otherwise have the target-independent code call memset.
5586     return SDValue();
5587   }
5588
5589   uint64_t SizeVal = ConstantSize->getZExtValue();
5590   SDValue InFlag(0, 0);
5591   MVT AVT;
5592   SDValue Count;
5593   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5594   unsigned BytesLeft = 0;
5595   bool TwoRepStos = false;
5596   if (ValC) {
5597     unsigned ValReg;
5598     uint64_t Val = ValC->getZExtValue() & 255;
5599
5600     // If the value is a constant, then we can potentially use larger sets.
5601     switch (Align & 3) {
5602     case 2:   // WORD aligned
5603       AVT = MVT::i16;
5604       ValReg = X86::AX;
5605       Val = (Val << 8) | Val;
5606       break;
5607     case 0:  // DWORD aligned
5608       AVT = MVT::i32;
5609       ValReg = X86::EAX;
5610       Val = (Val << 8)  | Val;
5611       Val = (Val << 16) | Val;
5612       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5613         AVT = MVT::i64;
5614         ValReg = X86::RAX;
5615         Val = (Val << 32) | Val;
5616       }
5617       break;
5618     default:  // Byte aligned
5619       AVT = MVT::i8;
5620       ValReg = X86::AL;
5621       Count = DAG.getIntPtrConstant(SizeVal);
5622       break;
5623     }
5624
5625     if (AVT.bitsGT(MVT::i8)) {
5626       unsigned UBytes = AVT.getSizeInBits() / 8;
5627       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5628       BytesLeft = SizeVal % UBytes;
5629     }
5630
5631     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5632                               InFlag);
5633     InFlag = Chain.getValue(1);
5634   } else {
5635     AVT = MVT::i8;
5636     Count  = DAG.getIntPtrConstant(SizeVal);
5637     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5638     InFlag = Chain.getValue(1);
5639   }
5640
5641   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5642                                                               X86::ECX,
5643                             Count, InFlag);
5644   InFlag = Chain.getValue(1);
5645   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5646                                                               X86::EDI,
5647                             Dst, InFlag);
5648   InFlag = Chain.getValue(1);
5649
5650   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5651   SmallVector<SDValue, 8> Ops;
5652   Ops.push_back(Chain);
5653   Ops.push_back(DAG.getValueType(AVT));
5654   Ops.push_back(InFlag);
5655   Chain  = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5656
5657   if (TwoRepStos) {
5658     InFlag = Chain.getValue(1);
5659     Count  = Size;
5660     MVT CVT = Count.getValueType();
5661     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5662                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5663     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5664                                                              X86::ECX,
5665                               Left, InFlag);
5666     InFlag = Chain.getValue(1);
5667     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5668     Ops.clear();
5669     Ops.push_back(Chain);
5670     Ops.push_back(DAG.getValueType(MVT::i8));
5671     Ops.push_back(InFlag);
5672     Chain  = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5673   } else if (BytesLeft) {
5674     // Handle the last 1 - 7 bytes.
5675     unsigned Offset = SizeVal - BytesLeft;
5676     MVT AddrVT = Dst.getValueType();
5677     MVT SizeVT = Size.getValueType();
5678
5679     Chain = DAG.getMemset(Chain, dl,
5680                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5681                                       DAG.getConstant(Offset, AddrVT)),
5682                           Src,
5683                           DAG.getConstant(BytesLeft, SizeVT),
5684                           Align, DstSV, DstSVOff + Offset);
5685   }
5686
5687   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5688   return Chain;
5689 }
5690
5691 SDValue
5692 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5693                                       SDValue Chain, SDValue Dst, SDValue Src,
5694                                       SDValue Size, unsigned Align,
5695                                       bool AlwaysInline,
5696                                       const Value *DstSV, uint64_t DstSVOff,
5697                                       const Value *SrcSV, uint64_t SrcSVOff) {
5698   // This requires the copy size to be a constant, preferrably
5699   // within a subtarget-specific limit.
5700   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5701   if (!ConstantSize)
5702     return SDValue();
5703   uint64_t SizeVal = ConstantSize->getZExtValue();
5704   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5705     return SDValue();
5706
5707   /// If not DWORD aligned, call the library.
5708   if ((Align & 3) != 0)
5709     return SDValue();
5710
5711   // DWORD aligned
5712   MVT AVT = MVT::i32;
5713   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
5714     AVT = MVT::i64;
5715
5716   unsigned UBytes = AVT.getSizeInBits() / 8;
5717   unsigned CountVal = SizeVal / UBytes;
5718   SDValue Count = DAG.getIntPtrConstant(CountVal);
5719   unsigned BytesLeft = SizeVal % UBytes;
5720
5721   SDValue InFlag(0, 0);
5722   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5723                                                               X86::ECX,
5724                             Count, InFlag);
5725   InFlag = Chain.getValue(1);
5726   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5727                                                              X86::EDI,
5728                             Dst, InFlag);
5729   InFlag = Chain.getValue(1);
5730   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5731                                                               X86::ESI,
5732                             Src, InFlag);
5733   InFlag = Chain.getValue(1);
5734
5735   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5736   SmallVector<SDValue, 8> Ops;
5737   Ops.push_back(Chain);
5738   Ops.push_back(DAG.getValueType(AVT));
5739   Ops.push_back(InFlag);
5740   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5741
5742   SmallVector<SDValue, 4> Results;
5743   Results.push_back(RepMovs);
5744   if (BytesLeft) {
5745     // Handle the last 1 - 7 bytes.
5746     unsigned Offset = SizeVal - BytesLeft;
5747     MVT DstVT = Dst.getValueType();
5748     MVT SrcVT = Src.getValueType();
5749     MVT SizeVT = Size.getValueType();
5750     Results.push_back(DAG.getMemcpy(Chain, dl,
5751                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5752                                                 DAG.getConstant(Offset, DstVT)),
5753                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5754                                                 DAG.getConstant(Offset, SrcVT)),
5755                                     DAG.getConstant(BytesLeft, SizeVT),
5756                                     Align, AlwaysInline,
5757                                     DstSV, DstSVOff + Offset,
5758                                     SrcSV, SrcSVOff + Offset));
5759   }
5760
5761   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5762                      &Results[0], Results.size());
5763 }
5764
5765 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5766   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5767   DebugLoc dl = Op.getDebugLoc();
5768
5769   if (!Subtarget->is64Bit()) {
5770     // vastart just stores the address of the VarArgsFrameIndex slot into the
5771     // memory location argument.
5772     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5773     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5774   }
5775
5776   // __va_list_tag:
5777   //   gp_offset         (0 - 6 * 8)
5778   //   fp_offset         (48 - 48 + 8 * 16)
5779   //   overflow_arg_area (point to parameters coming in memory).
5780   //   reg_save_area
5781   SmallVector<SDValue, 8> MemOps;
5782   SDValue FIN = Op.getOperand(1);
5783   // Store gp_offset
5784   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5785                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
5786                                  FIN, SV, 0);
5787   MemOps.push_back(Store);
5788
5789   // Store fp_offset
5790   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5791                     FIN, DAG.getIntPtrConstant(4));
5792   Store = DAG.getStore(Op.getOperand(0), dl,
5793                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
5794                        FIN, SV, 0);
5795   MemOps.push_back(Store);
5796
5797   // Store ptr to overflow_arg_area
5798   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5799                     FIN, DAG.getIntPtrConstant(4));
5800   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5801   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5802   MemOps.push_back(Store);
5803
5804   // Store ptr to reg_save_area.
5805   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5806                     FIN, DAG.getIntPtrConstant(8));
5807   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5808   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5809   MemOps.push_back(Store);
5810   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5811                      &MemOps[0], MemOps.size());
5812 }
5813
5814 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5815   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5816   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5817   SDValue Chain = Op.getOperand(0);
5818   SDValue SrcPtr = Op.getOperand(1);
5819   SDValue SrcSV = Op.getOperand(2);
5820
5821   assert(0 && "VAArgInst is not yet implemented for x86-64!");
5822   abort();
5823   return SDValue();
5824 }
5825
5826 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5827   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5828   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5829   SDValue Chain = Op.getOperand(0);
5830   SDValue DstPtr = Op.getOperand(1);
5831   SDValue SrcPtr = Op.getOperand(2);
5832   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5833   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5834   DebugLoc dl = Op.getDebugLoc();
5835
5836   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5837                        DAG.getIntPtrConstant(24), 8, false,
5838                        DstSV, 0, SrcSV, 0);
5839 }
5840
5841 SDValue
5842 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5843   DebugLoc dl = Op.getDebugLoc();
5844   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5845   switch (IntNo) {
5846   default: return SDValue();    // Don't custom lower most intrinsics.
5847   // Comparison intrinsics.
5848   case Intrinsic::x86_sse_comieq_ss:
5849   case Intrinsic::x86_sse_comilt_ss:
5850   case Intrinsic::x86_sse_comile_ss:
5851   case Intrinsic::x86_sse_comigt_ss:
5852   case Intrinsic::x86_sse_comige_ss:
5853   case Intrinsic::x86_sse_comineq_ss:
5854   case Intrinsic::x86_sse_ucomieq_ss:
5855   case Intrinsic::x86_sse_ucomilt_ss:
5856   case Intrinsic::x86_sse_ucomile_ss:
5857   case Intrinsic::x86_sse_ucomigt_ss:
5858   case Intrinsic::x86_sse_ucomige_ss:
5859   case Intrinsic::x86_sse_ucomineq_ss:
5860   case Intrinsic::x86_sse2_comieq_sd:
5861   case Intrinsic::x86_sse2_comilt_sd:
5862   case Intrinsic::x86_sse2_comile_sd:
5863   case Intrinsic::x86_sse2_comigt_sd:
5864   case Intrinsic::x86_sse2_comige_sd:
5865   case Intrinsic::x86_sse2_comineq_sd:
5866   case Intrinsic::x86_sse2_ucomieq_sd:
5867   case Intrinsic::x86_sse2_ucomilt_sd:
5868   case Intrinsic::x86_sse2_ucomile_sd:
5869   case Intrinsic::x86_sse2_ucomigt_sd:
5870   case Intrinsic::x86_sse2_ucomige_sd:
5871   case Intrinsic::x86_sse2_ucomineq_sd: {
5872     unsigned Opc = 0;
5873     ISD::CondCode CC = ISD::SETCC_INVALID;
5874     switch (IntNo) {
5875     default: break;
5876     case Intrinsic::x86_sse_comieq_ss:
5877     case Intrinsic::x86_sse2_comieq_sd:
5878       Opc = X86ISD::COMI;
5879       CC = ISD::SETEQ;
5880       break;
5881     case Intrinsic::x86_sse_comilt_ss:
5882     case Intrinsic::x86_sse2_comilt_sd:
5883       Opc = X86ISD::COMI;
5884       CC = ISD::SETLT;
5885       break;
5886     case Intrinsic::x86_sse_comile_ss:
5887     case Intrinsic::x86_sse2_comile_sd:
5888       Opc = X86ISD::COMI;
5889       CC = ISD::SETLE;
5890       break;
5891     case Intrinsic::x86_sse_comigt_ss:
5892     case Intrinsic::x86_sse2_comigt_sd:
5893       Opc = X86ISD::COMI;
5894       CC = ISD::SETGT;
5895       break;
5896     case Intrinsic::x86_sse_comige_ss:
5897     case Intrinsic::x86_sse2_comige_sd:
5898       Opc = X86ISD::COMI;
5899       CC = ISD::SETGE;
5900       break;
5901     case Intrinsic::x86_sse_comineq_ss:
5902     case Intrinsic::x86_sse2_comineq_sd:
5903       Opc = X86ISD::COMI;
5904       CC = ISD::SETNE;
5905       break;
5906     case Intrinsic::x86_sse_ucomieq_ss:
5907     case Intrinsic::x86_sse2_ucomieq_sd:
5908       Opc = X86ISD::UCOMI;
5909       CC = ISD::SETEQ;
5910       break;
5911     case Intrinsic::x86_sse_ucomilt_ss:
5912     case Intrinsic::x86_sse2_ucomilt_sd:
5913       Opc = X86ISD::UCOMI;
5914       CC = ISD::SETLT;
5915       break;
5916     case Intrinsic::x86_sse_ucomile_ss:
5917     case Intrinsic::x86_sse2_ucomile_sd:
5918       Opc = X86ISD::UCOMI;
5919       CC = ISD::SETLE;
5920       break;
5921     case Intrinsic::x86_sse_ucomigt_ss:
5922     case Intrinsic::x86_sse2_ucomigt_sd:
5923       Opc = X86ISD::UCOMI;
5924       CC = ISD::SETGT;
5925       break;
5926     case Intrinsic::x86_sse_ucomige_ss:
5927     case Intrinsic::x86_sse2_ucomige_sd:
5928       Opc = X86ISD::UCOMI;
5929       CC = ISD::SETGE;
5930       break;
5931     case Intrinsic::x86_sse_ucomineq_ss:
5932     case Intrinsic::x86_sse2_ucomineq_sd:
5933       Opc = X86ISD::UCOMI;
5934       CC = ISD::SETNE;
5935       break;
5936     }
5937
5938     SDValue LHS = Op.getOperand(1);
5939     SDValue RHS = Op.getOperand(2);
5940     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5941     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
5942     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5943                                 DAG.getConstant(X86CC, MVT::i8), Cond);
5944     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
5945   }
5946
5947   // Fix vector shift instructions where the last operand is a non-immediate
5948   // i32 value.
5949   case Intrinsic::x86_sse2_pslli_w:
5950   case Intrinsic::x86_sse2_pslli_d:
5951   case Intrinsic::x86_sse2_pslli_q:
5952   case Intrinsic::x86_sse2_psrli_w:
5953   case Intrinsic::x86_sse2_psrli_d:
5954   case Intrinsic::x86_sse2_psrli_q:
5955   case Intrinsic::x86_sse2_psrai_w:
5956   case Intrinsic::x86_sse2_psrai_d:
5957   case Intrinsic::x86_mmx_pslli_w:
5958   case Intrinsic::x86_mmx_pslli_d:
5959   case Intrinsic::x86_mmx_pslli_q:
5960   case Intrinsic::x86_mmx_psrli_w:
5961   case Intrinsic::x86_mmx_psrli_d:
5962   case Intrinsic::x86_mmx_psrli_q:
5963   case Intrinsic::x86_mmx_psrai_w:
5964   case Intrinsic::x86_mmx_psrai_d: {
5965     SDValue ShAmt = Op.getOperand(2);
5966     if (isa<ConstantSDNode>(ShAmt))
5967       return SDValue();
5968
5969     unsigned NewIntNo = 0;
5970     MVT ShAmtVT = MVT::v4i32;
5971     switch (IntNo) {
5972     case Intrinsic::x86_sse2_pslli_w:
5973       NewIntNo = Intrinsic::x86_sse2_psll_w;
5974       break;
5975     case Intrinsic::x86_sse2_pslli_d:
5976       NewIntNo = Intrinsic::x86_sse2_psll_d;
5977       break;
5978     case Intrinsic::x86_sse2_pslli_q:
5979       NewIntNo = Intrinsic::x86_sse2_psll_q;
5980       break;
5981     case Intrinsic::x86_sse2_psrli_w:
5982       NewIntNo = Intrinsic::x86_sse2_psrl_w;
5983       break;
5984     case Intrinsic::x86_sse2_psrli_d:
5985       NewIntNo = Intrinsic::x86_sse2_psrl_d;
5986       break;
5987     case Intrinsic::x86_sse2_psrli_q:
5988       NewIntNo = Intrinsic::x86_sse2_psrl_q;
5989       break;
5990     case Intrinsic::x86_sse2_psrai_w:
5991       NewIntNo = Intrinsic::x86_sse2_psra_w;
5992       break;
5993     case Intrinsic::x86_sse2_psrai_d:
5994       NewIntNo = Intrinsic::x86_sse2_psra_d;
5995       break;
5996     default: {
5997       ShAmtVT = MVT::v2i32;
5998       switch (IntNo) {
5999       case Intrinsic::x86_mmx_pslli_w:
6000         NewIntNo = Intrinsic::x86_mmx_psll_w;
6001         break;
6002       case Intrinsic::x86_mmx_pslli_d:
6003         NewIntNo = Intrinsic::x86_mmx_psll_d;
6004         break;
6005       case Intrinsic::x86_mmx_pslli_q:
6006         NewIntNo = Intrinsic::x86_mmx_psll_q;
6007         break;
6008       case Intrinsic::x86_mmx_psrli_w:
6009         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6010         break;
6011       case Intrinsic::x86_mmx_psrli_d:
6012         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6013         break;
6014       case Intrinsic::x86_mmx_psrli_q:
6015         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6016         break;
6017       case Intrinsic::x86_mmx_psrai_w:
6018         NewIntNo = Intrinsic::x86_mmx_psra_w;
6019         break;
6020       case Intrinsic::x86_mmx_psrai_d:
6021         NewIntNo = Intrinsic::x86_mmx_psra_d;
6022         break;
6023       default: abort();  // Can't reach here.
6024       }
6025       break;
6026     }
6027     }
6028     MVT VT = Op.getValueType();
6029     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6030                         DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6031     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6032                        DAG.getConstant(NewIntNo, MVT::i32),
6033                        Op.getOperand(1), ShAmt);
6034   }
6035   }
6036 }
6037
6038 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6039   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6040   DebugLoc dl = Op.getDebugLoc();
6041
6042   if (Depth > 0) {
6043     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6044     SDValue Offset =
6045       DAG.getConstant(TD->getPointerSize(),
6046                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6047     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6048                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6049                                    FrameAddr, Offset),
6050                        NULL, 0);
6051   }
6052
6053   // Just load the return address.
6054   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6055   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6056                      RetAddrFI, NULL, 0);
6057 }
6058
6059 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6060   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6061   MFI->setFrameAddressIsTaken(true);
6062   MVT VT = Op.getValueType();
6063   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6064   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6065   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6066   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6067   while (Depth--)
6068     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6069   return FrameAddr;
6070 }
6071
6072 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6073                                                      SelectionDAG &DAG) {
6074   return DAG.getIntPtrConstant(2*TD->getPointerSize());
6075 }
6076
6077 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6078 {
6079   MachineFunction &MF = DAG.getMachineFunction();
6080   SDValue Chain     = Op.getOperand(0);
6081   SDValue Offset    = Op.getOperand(1);
6082   SDValue Handler   = Op.getOperand(2);
6083   DebugLoc dl       = Op.getDebugLoc();
6084
6085   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6086                                   getPointerTy());
6087   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6088
6089   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6090                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
6091   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6092   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6093   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6094   MF.getRegInfo().addLiveOut(StoreAddrReg);
6095
6096   return DAG.getNode(X86ISD::EH_RETURN, dl,
6097                      MVT::Other,
6098                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6099 }
6100
6101 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6102                                              SelectionDAG &DAG) {
6103   SDValue Root = Op.getOperand(0);
6104   SDValue Trmp = Op.getOperand(1); // trampoline
6105   SDValue FPtr = Op.getOperand(2); // nested function
6106   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6107   DebugLoc dl  = Op.getDebugLoc();
6108
6109   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6110
6111   const X86InstrInfo *TII =
6112     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6113
6114   if (Subtarget->is64Bit()) {
6115     SDValue OutChains[6];
6116
6117     // Large code-model.
6118
6119     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
6120     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6121
6122     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6123     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6124
6125     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6126
6127     // Load the pointer to the nested function into R11.
6128     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6129     SDValue Addr = Trmp;
6130     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6131                                 Addr, TrmpAddr, 0);
6132
6133     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6134                        DAG.getConstant(2, MVT::i64));
6135     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6136
6137     // Load the 'nest' parameter value into R10.
6138     // R10 is specified in X86CallingConv.td
6139     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6140     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6141                        DAG.getConstant(10, MVT::i64));
6142     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6143                                 Addr, TrmpAddr, 10);
6144
6145     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6146                        DAG.getConstant(12, MVT::i64));
6147     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6148
6149     // Jump to the nested function.
6150     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6151     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6152                        DAG.getConstant(20, MVT::i64));
6153     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6154                                 Addr, TrmpAddr, 20);
6155
6156     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6157     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6158                        DAG.getConstant(22, MVT::i64));
6159     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6160                                 TrmpAddr, 22);
6161
6162     SDValue Ops[] =
6163       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6164     return DAG.getMergeValues(Ops, 2, dl);
6165   } else {
6166     const Function *Func =
6167       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6168     unsigned CC = Func->getCallingConv();
6169     unsigned NestReg;
6170
6171     switch (CC) {
6172     default:
6173       assert(0 && "Unsupported calling convention");
6174     case CallingConv::C:
6175     case CallingConv::X86_StdCall: {
6176       // Pass 'nest' parameter in ECX.
6177       // Must be kept in sync with X86CallingConv.td
6178       NestReg = X86::ECX;
6179
6180       // Check that ECX wasn't needed by an 'inreg' parameter.
6181       const FunctionType *FTy = Func->getFunctionType();
6182       const AttrListPtr &Attrs = Func->getAttributes();
6183
6184       if (!Attrs.isEmpty() && !Func->isVarArg()) {
6185         unsigned InRegCount = 0;
6186         unsigned Idx = 1;
6187
6188         for (FunctionType::param_iterator I = FTy->param_begin(),
6189              E = FTy->param_end(); I != E; ++I, ++Idx)
6190           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6191             // FIXME: should only count parameters that are lowered to integers.
6192             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6193
6194         if (InRegCount > 2) {
6195           cerr << "Nest register in use - reduce number of inreg parameters!\n";
6196           abort();
6197         }
6198       }
6199       break;
6200     }
6201     case CallingConv::X86_FastCall:
6202     case CallingConv::Fast:
6203       // Pass 'nest' parameter in EAX.
6204       // Must be kept in sync with X86CallingConv.td
6205       NestReg = X86::EAX;
6206       break;
6207     }
6208
6209     SDValue OutChains[4];
6210     SDValue Addr, Disp;
6211
6212     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6213                        DAG.getConstant(10, MVT::i32));
6214     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6215
6216     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6217     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6218     OutChains[0] = DAG.getStore(Root, dl,
6219                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6220                                 Trmp, TrmpAddr, 0);
6221
6222     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6223                        DAG.getConstant(1, MVT::i32));
6224     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6225
6226     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6227     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6228                        DAG.getConstant(5, MVT::i32));
6229     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6230                                 TrmpAddr, 5, false, 1);
6231
6232     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6233                        DAG.getConstant(6, MVT::i32));
6234     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6235
6236     SDValue Ops[] =
6237       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6238     return DAG.getMergeValues(Ops, 2, dl);
6239   }
6240 }
6241
6242 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6243   /*
6244    The rounding mode is in bits 11:10 of FPSR, and has the following
6245    settings:
6246      00 Round to nearest
6247      01 Round to -inf
6248      10 Round to +inf
6249      11 Round to 0
6250
6251   FLT_ROUNDS, on the other hand, expects the following:
6252     -1 Undefined
6253      0 Round to 0
6254      1 Round to nearest
6255      2 Round to +inf
6256      3 Round to -inf
6257
6258   To perform the conversion, we do:
6259     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6260   */
6261
6262   MachineFunction &MF = DAG.getMachineFunction();
6263   const TargetMachine &TM = MF.getTarget();
6264   const TargetFrameInfo &TFI = *TM.getFrameInfo();
6265   unsigned StackAlignment = TFI.getStackAlignment();
6266   MVT VT = Op.getValueType();
6267   DebugLoc dl = Op.getDebugLoc();
6268
6269   // Save FP Control Word to stack slot
6270   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6271   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6272
6273   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6274                               DAG.getEntryNode(), StackSlot);
6275
6276   // Load FP Control Word from stack slot
6277   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6278
6279   // Transform as necessary
6280   SDValue CWD1 =
6281     DAG.getNode(ISD::SRL, dl, MVT::i16,
6282                 DAG.getNode(ISD::AND, dl, MVT::i16,
6283                             CWD, DAG.getConstant(0x800, MVT::i16)),
6284                 DAG.getConstant(11, MVT::i8));
6285   SDValue CWD2 =
6286     DAG.getNode(ISD::SRL, dl, MVT::i16,
6287                 DAG.getNode(ISD::AND, dl, MVT::i16,
6288                             CWD, DAG.getConstant(0x400, MVT::i16)),
6289                 DAG.getConstant(9, MVT::i8));
6290
6291   SDValue RetVal =
6292     DAG.getNode(ISD::AND, dl, MVT::i16,
6293                 DAG.getNode(ISD::ADD, dl, MVT::i16,
6294                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6295                             DAG.getConstant(1, MVT::i16)),
6296                 DAG.getConstant(3, MVT::i16));
6297
6298
6299   return DAG.getNode((VT.getSizeInBits() < 16 ?
6300                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6301 }
6302
6303 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6304   MVT VT = Op.getValueType();
6305   MVT OpVT = VT;
6306   unsigned NumBits = VT.getSizeInBits();
6307   DebugLoc dl = Op.getDebugLoc();
6308
6309   Op = Op.getOperand(0);
6310   if (VT == MVT::i8) {
6311     // Zero extend to i32 since there is not an i8 bsr.
6312     OpVT = MVT::i32;
6313     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6314   }
6315
6316   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6317   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6318   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6319
6320   // If src is zero (i.e. bsr sets ZF), returns NumBits.
6321   SmallVector<SDValue, 4> Ops;
6322   Ops.push_back(Op);
6323   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6324   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6325   Ops.push_back(Op.getValue(1));
6326   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6327
6328   // Finally xor with NumBits-1.
6329   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6330
6331   if (VT == MVT::i8)
6332     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6333   return Op;
6334 }
6335
6336 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6337   MVT VT = Op.getValueType();
6338   MVT OpVT = VT;
6339   unsigned NumBits = VT.getSizeInBits();
6340   DebugLoc dl = Op.getDebugLoc();
6341
6342   Op = Op.getOperand(0);
6343   if (VT == MVT::i8) {
6344     OpVT = MVT::i32;
6345     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6346   }
6347
6348   // Issue a bsf (scan bits forward) which also sets EFLAGS.
6349   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6350   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6351
6352   // If src is zero (i.e. bsf sets ZF), returns NumBits.
6353   SmallVector<SDValue, 4> Ops;
6354   Ops.push_back(Op);
6355   Ops.push_back(DAG.getConstant(NumBits, OpVT));
6356   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6357   Ops.push_back(Op.getValue(1));
6358   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6359
6360   if (VT == MVT::i8)
6361     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6362   return Op;
6363 }
6364
6365 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6366   MVT VT = Op.getValueType();
6367   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6368   DebugLoc dl = Op.getDebugLoc();
6369
6370   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6371   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6372   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6373   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6374   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6375   //
6376   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6377   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6378   //  return AloBlo + AloBhi + AhiBlo;
6379
6380   SDValue A = Op.getOperand(0);
6381   SDValue B = Op.getOperand(1);
6382
6383   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6384                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6385                        A, DAG.getConstant(32, MVT::i32));
6386   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6387                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6388                        B, DAG.getConstant(32, MVT::i32));
6389   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6390                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6391                        A, B);
6392   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6393                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6394                        A, Bhi);
6395   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6396                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6397                        Ahi, B);
6398   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6399                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6400                        AloBhi, DAG.getConstant(32, MVT::i32));
6401   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6402                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6403                        AhiBlo, DAG.getConstant(32, MVT::i32));
6404   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6405   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6406   return Res;
6407 }
6408
6409
6410 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6411   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6412   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6413   // looks for this combo and may remove the "setcc" instruction if the "setcc"
6414   // has only one use.
6415   SDNode *N = Op.getNode();
6416   SDValue LHS = N->getOperand(0);
6417   SDValue RHS = N->getOperand(1);
6418   unsigned BaseOp = 0;
6419   unsigned Cond = 0;
6420   DebugLoc dl = Op.getDebugLoc();
6421
6422   switch (Op.getOpcode()) {
6423   default: assert(0 && "Unknown ovf instruction!");
6424   case ISD::SADDO:
6425     // A subtract of one will be selected as a INC. Note that INC doesn't
6426     // set CF, so we can't do this for UADDO.
6427     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6428       if (C->getAPIntValue() == 1) {
6429         BaseOp = X86ISD::INC;
6430         Cond = X86::COND_O;
6431         break;
6432       }
6433     BaseOp = X86ISD::ADD;
6434     Cond = X86::COND_O;
6435     break;
6436   case ISD::UADDO:
6437     BaseOp = X86ISD::ADD;
6438     Cond = X86::COND_B;
6439     break;
6440   case ISD::SSUBO:
6441     // A subtract of one will be selected as a DEC. Note that DEC doesn't
6442     // set CF, so we can't do this for USUBO.
6443     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6444       if (C->getAPIntValue() == 1) {
6445         BaseOp = X86ISD::DEC;
6446         Cond = X86::COND_O;
6447         break;
6448       }
6449     BaseOp = X86ISD::SUB;
6450     Cond = X86::COND_O;
6451     break;
6452   case ISD::USUBO:
6453     BaseOp = X86ISD::SUB;
6454     Cond = X86::COND_B;
6455     break;
6456   case ISD::SMULO:
6457     BaseOp = X86ISD::SMUL;
6458     Cond = X86::COND_O;
6459     break;
6460   case ISD::UMULO:
6461     BaseOp = X86ISD::UMUL;
6462     Cond = X86::COND_B;
6463     break;
6464   }
6465
6466   // Also sets EFLAGS.
6467   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6468   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6469
6470   SDValue SetCC =
6471     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6472                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6473
6474   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6475   return Sum;
6476 }
6477
6478 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6479   MVT T = Op.getValueType();
6480   DebugLoc dl = Op.getDebugLoc();
6481   unsigned Reg = 0;
6482   unsigned size = 0;
6483   switch(T.getSimpleVT()) {
6484   default:
6485     assert(false && "Invalid value type!");
6486   case MVT::i8:  Reg = X86::AL;  size = 1; break;
6487   case MVT::i16: Reg = X86::AX;  size = 2; break;
6488   case MVT::i32: Reg = X86::EAX; size = 4; break;
6489   case MVT::i64:
6490     assert(Subtarget->is64Bit() && "Node not type legal!");
6491     Reg = X86::RAX; size = 8;
6492     break;
6493   }
6494   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6495                                     Op.getOperand(2), SDValue());
6496   SDValue Ops[] = { cpIn.getValue(0),
6497                     Op.getOperand(1),
6498                     Op.getOperand(3),
6499                     DAG.getTargetConstant(size, MVT::i8),
6500                     cpIn.getValue(1) };
6501   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6502   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6503   SDValue cpOut =
6504     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6505   return cpOut;
6506 }
6507
6508 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6509                                                  SelectionDAG &DAG) {
6510   assert(Subtarget->is64Bit() && "Result not type legalized?");
6511   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6512   SDValue TheChain = Op.getOperand(0);
6513   DebugLoc dl = Op.getDebugLoc();
6514   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6515   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6516   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6517                                    rax.getValue(2));
6518   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6519                             DAG.getConstant(32, MVT::i8));
6520   SDValue Ops[] = {
6521     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6522     rdx.getValue(1)
6523   };
6524   return DAG.getMergeValues(Ops, 2, dl);
6525 }
6526
6527 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6528   SDNode *Node = Op.getNode();
6529   DebugLoc dl = Node->getDebugLoc();
6530   MVT T = Node->getValueType(0);
6531   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6532                               DAG.getConstant(0, T), Node->getOperand(2));
6533   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6534                        cast<AtomicSDNode>(Node)->getMemoryVT(),
6535                        Node->getOperand(0),
6536                        Node->getOperand(1), negOp,
6537                        cast<AtomicSDNode>(Node)->getSrcValue(),
6538                        cast<AtomicSDNode>(Node)->getAlignment());
6539 }
6540
6541 /// LowerOperation - Provide custom lowering hooks for some operations.
6542 ///
6543 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6544   switch (Op.getOpcode()) {
6545   default: assert(0 && "Should not custom lower this!");
6546   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
6547   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
6548   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6549   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6550   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6551   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
6552   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6553   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6554   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6555   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6556   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
6557   case ISD::SHL_PARTS:
6558   case ISD::SRA_PARTS:
6559   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
6560   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
6561   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
6562   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
6563   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
6564   case ISD::FABS:               return LowerFABS(Op, DAG);
6565   case ISD::FNEG:               return LowerFNEG(Op, DAG);
6566   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
6567   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6568   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
6569   case ISD::SELECT:             return LowerSELECT(Op, DAG);
6570   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
6571   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6572   case ISD::CALL:               return LowerCALL(Op, DAG);
6573   case ISD::RET:                return LowerRET(Op, DAG);
6574   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
6575   case ISD::VASTART:            return LowerVASTART(Op, DAG);
6576   case ISD::VAARG:              return LowerVAARG(Op, DAG);
6577   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
6578   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6579   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6580   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6581   case ISD::FRAME_TO_ARGS_OFFSET:
6582                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6583   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6584   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
6585   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
6586   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6587   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
6588   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
6589   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
6590   case ISD::SADDO:
6591   case ISD::UADDO:
6592   case ISD::SSUBO:
6593   case ISD::USUBO:
6594   case ISD::SMULO:
6595   case ISD::UMULO:              return LowerXALUO(Op, DAG);
6596   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
6597   }
6598 }
6599
6600 void X86TargetLowering::
6601 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6602                         SelectionDAG &DAG, unsigned NewOp) {
6603   MVT T = Node->getValueType(0);
6604   DebugLoc dl = Node->getDebugLoc();
6605   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6606
6607   SDValue Chain = Node->getOperand(0);
6608   SDValue In1 = Node->getOperand(1);
6609   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6610                              Node->getOperand(2), DAG.getIntPtrConstant(0));
6611   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6612                              Node->getOperand(2), DAG.getIntPtrConstant(1));
6613   // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6614   // have a MemOperand.  Pass the info through as a normal operand.
6615   SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6616   SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6617   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6618   SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6619   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6620   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6621   Results.push_back(Result.getValue(2));
6622 }
6623
6624 /// ReplaceNodeResults - Replace a node with an illegal result type
6625 /// with a new node built out of custom code.
6626 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6627                                            SmallVectorImpl<SDValue>&Results,
6628                                            SelectionDAG &DAG) {
6629   DebugLoc dl = N->getDebugLoc();
6630   switch (N->getOpcode()) {
6631   default:
6632     assert(false && "Do not know how to custom type legalize this operation!");
6633     return;
6634   case ISD::FP_TO_SINT: {
6635     std::pair<SDValue,SDValue> Vals =
6636         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6637     SDValue FIST = Vals.first, StackSlot = Vals.second;
6638     if (FIST.getNode() != 0) {
6639       MVT VT = N->getValueType(0);
6640       // Return a load from the stack slot.
6641       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6642     }
6643     return;
6644   }
6645   case ISD::READCYCLECOUNTER: {
6646     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6647     SDValue TheChain = N->getOperand(0);
6648     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6649     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6650                                      rd.getValue(1));
6651     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6652                                      eax.getValue(2));
6653     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6654     SDValue Ops[] = { eax, edx };
6655     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6656     Results.push_back(edx.getValue(1));
6657     return;
6658   }
6659   case ISD::ATOMIC_CMP_SWAP: {
6660     MVT T = N->getValueType(0);
6661     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6662     SDValue cpInL, cpInH;
6663     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6664                         DAG.getConstant(0, MVT::i32));
6665     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6666                         DAG.getConstant(1, MVT::i32));
6667     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6668     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6669                              cpInL.getValue(1));
6670     SDValue swapInL, swapInH;
6671     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6672                           DAG.getConstant(0, MVT::i32));
6673     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6674                           DAG.getConstant(1, MVT::i32));
6675     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6676                                cpInH.getValue(1));
6677     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6678                                swapInL.getValue(1));
6679     SDValue Ops[] = { swapInH.getValue(0),
6680                       N->getOperand(1),
6681                       swapInH.getValue(1) };
6682     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6683     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6684     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6685                                         MVT::i32, Result.getValue(1));
6686     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6687                                         MVT::i32, cpOutL.getValue(2));
6688     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6689     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6690     Results.push_back(cpOutH.getValue(1));
6691     return;
6692   }
6693   case ISD::ATOMIC_LOAD_ADD:
6694     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6695     return;
6696   case ISD::ATOMIC_LOAD_AND:
6697     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6698     return;
6699   case ISD::ATOMIC_LOAD_NAND:
6700     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6701     return;
6702   case ISD::ATOMIC_LOAD_OR:
6703     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6704     return;
6705   case ISD::ATOMIC_LOAD_SUB:
6706     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6707     return;
6708   case ISD::ATOMIC_LOAD_XOR:
6709     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6710     return;
6711   case ISD::ATOMIC_SWAP:
6712     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6713     return;
6714   }
6715 }
6716
6717 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6718   switch (Opcode) {
6719   default: return NULL;
6720   case X86ISD::BSF:                return "X86ISD::BSF";
6721   case X86ISD::BSR:                return "X86ISD::BSR";
6722   case X86ISD::SHLD:               return "X86ISD::SHLD";
6723   case X86ISD::SHRD:               return "X86ISD::SHRD";
6724   case X86ISD::FAND:               return "X86ISD::FAND";
6725   case X86ISD::FOR:                return "X86ISD::FOR";
6726   case X86ISD::FXOR:               return "X86ISD::FXOR";
6727   case X86ISD::FSRL:               return "X86ISD::FSRL";
6728   case X86ISD::FILD:               return "X86ISD::FILD";
6729   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
6730   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6731   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6732   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6733   case X86ISD::FLD:                return "X86ISD::FLD";
6734   case X86ISD::FST:                return "X86ISD::FST";
6735   case X86ISD::CALL:               return "X86ISD::CALL";
6736   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
6737   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
6738   case X86ISD::BT:                 return "X86ISD::BT";
6739   case X86ISD::CMP:                return "X86ISD::CMP";
6740   case X86ISD::COMI:               return "X86ISD::COMI";
6741   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
6742   case X86ISD::SETCC:              return "X86ISD::SETCC";
6743   case X86ISD::CMOV:               return "X86ISD::CMOV";
6744   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
6745   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
6746   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
6747   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
6748   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
6749   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
6750   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
6751   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
6752   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
6753   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
6754   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
6755   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
6756   case X86ISD::FMAX:               return "X86ISD::FMAX";
6757   case X86ISD::FMIN:               return "X86ISD::FMIN";
6758   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
6759   case X86ISD::FRCP:               return "X86ISD::FRCP";
6760   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
6761   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6762   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
6763   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
6764   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
6765   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
6766   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
6767   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
6768   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
6769   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
6770   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
6771   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
6772   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
6773   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
6774   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
6775   case X86ISD::VSHL:               return "X86ISD::VSHL";
6776   case X86ISD::VSRL:               return "X86ISD::VSRL";
6777   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
6778   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
6779   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
6780   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
6781   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
6782   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
6783   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
6784   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
6785   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
6786   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
6787   case X86ISD::ADD:                return "X86ISD::ADD";
6788   case X86ISD::SUB:                return "X86ISD::SUB";
6789   case X86ISD::SMUL:               return "X86ISD::SMUL";
6790   case X86ISD::UMUL:               return "X86ISD::UMUL";
6791   case X86ISD::INC:                return "X86ISD::INC";
6792   case X86ISD::DEC:                return "X86ISD::DEC";
6793   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
6794   }
6795 }
6796
6797 // isLegalAddressingMode - Return true if the addressing mode represented
6798 // by AM is legal for this target, for a load/store of the specified type.
6799 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6800                                               const Type *Ty) const {
6801   // X86 supports extremely general addressing modes.
6802
6803   // X86 allows a sign-extended 32-bit immediate field as a displacement.
6804   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6805     return false;
6806
6807   if (AM.BaseGV) {
6808     // We can only fold this if we don't need an extra load.
6809     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6810       return false;
6811     // If BaseGV requires a register, we cannot also have a BaseReg.
6812     if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6813         AM.HasBaseReg)
6814       return false;
6815
6816     // X86-64 only supports addr of globals in small code model.
6817     if (Subtarget->is64Bit()) {
6818       if (getTargetMachine().getCodeModel() != CodeModel::Small)
6819         return false;
6820       // If lower 4G is not available, then we must use rip-relative addressing.
6821       if (AM.BaseOffs || AM.Scale > 1)
6822         return false;
6823     }
6824   }
6825
6826   switch (AM.Scale) {
6827   case 0:
6828   case 1:
6829   case 2:
6830   case 4:
6831   case 8:
6832     // These scales always work.
6833     break;
6834   case 3:
6835   case 5:
6836   case 9:
6837     // These scales are formed with basereg+scalereg.  Only accept if there is
6838     // no basereg yet.
6839     if (AM.HasBaseReg)
6840       return false;
6841     break;
6842   default:  // Other stuff never works.
6843     return false;
6844   }
6845
6846   return true;
6847 }
6848
6849
6850 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6851   if (!Ty1->isInteger() || !Ty2->isInteger())
6852     return false;
6853   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6854   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6855   if (NumBits1 <= NumBits2)
6856     return false;
6857   return Subtarget->is64Bit() || NumBits1 < 64;
6858 }
6859
6860 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6861   if (!VT1.isInteger() || !VT2.isInteger())
6862     return false;
6863   unsigned NumBits1 = VT1.getSizeInBits();
6864   unsigned NumBits2 = VT2.getSizeInBits();
6865   if (NumBits1 <= NumBits2)
6866     return false;
6867   return Subtarget->is64Bit() || NumBits1 < 64;
6868 }
6869
6870 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
6871   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6872   return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
6873 }
6874
6875 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
6876   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6877   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
6878 }
6879
6880 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6881 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6882 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6883 /// are assumed to be legal.
6884 bool
6885 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 
6886                                       MVT VT) const {
6887   // Only do shuffles on 128-bit vector types for now.
6888   if (VT.getSizeInBits() == 64)
6889     return false;
6890
6891   // FIXME: pshufb, blends, palignr, shifts.
6892   return (VT.getVectorNumElements() == 2 ||
6893           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6894           isMOVLMask(M, VT) ||
6895           isSHUFPMask(M, VT) ||
6896           isPSHUFDMask(M, VT) ||
6897           isPSHUFHWMask(M, VT) ||
6898           isPSHUFLWMask(M, VT) ||
6899           isUNPCKLMask(M, VT) ||
6900           isUNPCKHMask(M, VT) ||
6901           isUNPCKL_v_undef_Mask(M, VT) ||
6902           isUNPCKH_v_undef_Mask(M, VT));
6903 }
6904
6905 bool
6906 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
6907                                           MVT VT) const {
6908   unsigned NumElts = VT.getVectorNumElements();
6909   // FIXME: This collection of masks seems suspect.
6910   if (NumElts == 2)
6911     return true;
6912   if (NumElts == 4 && VT.getSizeInBits() == 128) {
6913     return (isMOVLMask(Mask, VT)  ||
6914             isCommutedMOVLMask(Mask, VT, true) ||
6915             isSHUFPMask(Mask, VT) ||
6916             isCommutedSHUFPMask(Mask, VT));
6917   }
6918   return false;
6919 }
6920
6921 //===----------------------------------------------------------------------===//
6922 //                           X86 Scheduler Hooks
6923 //===----------------------------------------------------------------------===//
6924
6925 // private utility function
6926 MachineBasicBlock *
6927 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6928                                                        MachineBasicBlock *MBB,
6929                                                        unsigned regOpc,
6930                                                        unsigned immOpc,
6931                                                        unsigned LoadOpc,
6932                                                        unsigned CXchgOpc,
6933                                                        unsigned copyOpc,
6934                                                        unsigned notOpc,
6935                                                        unsigned EAXreg,
6936                                                        TargetRegisterClass *RC,
6937                                                        bool invSrc) const {
6938   // For the atomic bitwise operator, we generate
6939   //   thisMBB:
6940   //   newMBB:
6941   //     ld  t1 = [bitinstr.addr]
6942   //     op  t2 = t1, [bitinstr.val]
6943   //     mov EAX = t1
6944   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6945   //     bz  newMBB
6946   //     fallthrough -->nextMBB
6947   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6948   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6949   MachineFunction::iterator MBBIter = MBB;
6950   ++MBBIter;
6951
6952   /// First build the CFG
6953   MachineFunction *F = MBB->getParent();
6954   MachineBasicBlock *thisMBB = MBB;
6955   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6956   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6957   F->insert(MBBIter, newMBB);
6958   F->insert(MBBIter, nextMBB);
6959
6960   // Move all successors to thisMBB to nextMBB
6961   nextMBB->transferSuccessors(thisMBB);
6962
6963   // Update thisMBB to fall through to newMBB
6964   thisMBB->addSuccessor(newMBB);
6965
6966   // newMBB jumps to itself and fall through to nextMBB
6967   newMBB->addSuccessor(nextMBB);
6968   newMBB->addSuccessor(newMBB);
6969
6970   // Insert instructions into newMBB based on incoming instruction
6971   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
6972          "unexpected number of operands");
6973   DebugLoc dl = bInstr->getDebugLoc();
6974   MachineOperand& destOper = bInstr->getOperand(0);
6975   MachineOperand* argOpers[2 + X86AddrNumOperands];
6976   int numArgs = bInstr->getNumOperands() - 1;
6977   for (int i=0; i < numArgs; ++i)
6978     argOpers[i] = &bInstr->getOperand(i+1);
6979
6980   // x86 address has 4 operands: base, index, scale, and displacement
6981   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
6982   int valArgIndx = lastAddrIndx + 1;
6983
6984   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6985   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
6986   for (int i=0; i <= lastAddrIndx; ++i)
6987     (*MIB).addOperand(*argOpers[i]);
6988
6989   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6990   if (invSrc) {
6991     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
6992   }
6993   else
6994     tt = t1;
6995
6996   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6997   assert((argOpers[valArgIndx]->isReg() ||
6998           argOpers[valArgIndx]->isImm()) &&
6999          "invalid operand");
7000   if (argOpers[valArgIndx]->isReg())
7001     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7002   else
7003     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7004   MIB.addReg(tt);
7005   (*MIB).addOperand(*argOpers[valArgIndx]);
7006
7007   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7008   MIB.addReg(t1);
7009
7010   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7011   for (int i=0; i <= lastAddrIndx; ++i)
7012     (*MIB).addOperand(*argOpers[i]);
7013   MIB.addReg(t2);
7014   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7015   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7016
7017   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7018   MIB.addReg(EAXreg);
7019
7020   // insert branch
7021   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7022
7023   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7024   return nextMBB;
7025 }
7026
7027 // private utility function:  64 bit atomics on 32 bit host.
7028 MachineBasicBlock *
7029 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7030                                                        MachineBasicBlock *MBB,
7031                                                        unsigned regOpcL,
7032                                                        unsigned regOpcH,
7033                                                        unsigned immOpcL,
7034                                                        unsigned immOpcH,
7035                                                        bool invSrc) const {
7036   // For the atomic bitwise operator, we generate
7037   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7038   //     ld t1,t2 = [bitinstr.addr]
7039   //   newMBB:
7040   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7041   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7042   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7043   //     mov ECX, EBX <- t5, t6
7044   //     mov EAX, EDX <- t1, t2
7045   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7046   //     mov t3, t4 <- EAX, EDX
7047   //     bz  newMBB
7048   //     result in out1, out2
7049   //     fallthrough -->nextMBB
7050
7051   const TargetRegisterClass *RC = X86::GR32RegisterClass;
7052   const unsigned LoadOpc = X86::MOV32rm;
7053   const unsigned copyOpc = X86::MOV32rr;
7054   const unsigned NotOpc = X86::NOT32r;
7055   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7056   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7057   MachineFunction::iterator MBBIter = MBB;
7058   ++MBBIter;
7059
7060   /// First build the CFG
7061   MachineFunction *F = MBB->getParent();
7062   MachineBasicBlock *thisMBB = MBB;
7063   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7064   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7065   F->insert(MBBIter, newMBB);
7066   F->insert(MBBIter, nextMBB);
7067
7068   // Move all successors to thisMBB to nextMBB
7069   nextMBB->transferSuccessors(thisMBB);
7070
7071   // Update thisMBB to fall through to newMBB
7072   thisMBB->addSuccessor(newMBB);
7073
7074   // newMBB jumps to itself and fall through to nextMBB
7075   newMBB->addSuccessor(nextMBB);
7076   newMBB->addSuccessor(newMBB);
7077
7078   DebugLoc dl = bInstr->getDebugLoc();
7079   // Insert instructions into newMBB based on incoming instruction
7080   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7081   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7082          "unexpected number of operands");
7083   MachineOperand& dest1Oper = bInstr->getOperand(0);
7084   MachineOperand& dest2Oper = bInstr->getOperand(1);
7085   MachineOperand* argOpers[2 + X86AddrNumOperands];
7086   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7087     argOpers[i] = &bInstr->getOperand(i+2);
7088
7089   // x86 address has 4 operands: base, index, scale, and displacement
7090   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7091
7092   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7093   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7094   for (int i=0; i <= lastAddrIndx; ++i)
7095     (*MIB).addOperand(*argOpers[i]);
7096   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7097   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7098   // add 4 to displacement.
7099   for (int i=0; i <= lastAddrIndx-2; ++i)
7100     (*MIB).addOperand(*argOpers[i]);
7101   MachineOperand newOp3 = *(argOpers[3]);
7102   if (newOp3.isImm())
7103     newOp3.setImm(newOp3.getImm()+4);
7104   else
7105     newOp3.setOffset(newOp3.getOffset()+4);
7106   (*MIB).addOperand(newOp3);
7107   (*MIB).addOperand(*argOpers[lastAddrIndx]);
7108
7109   // t3/4 are defined later, at the bottom of the loop
7110   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7111   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7112   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7113     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7114   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7115     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7116
7117   unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7118   unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7119   if (invSrc) {
7120     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7121     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7122   } else {
7123     tt1 = t1;
7124     tt2 = t2;
7125   }
7126
7127   int valArgIndx = lastAddrIndx + 1;
7128   assert((argOpers[valArgIndx]->isReg() ||
7129           argOpers[valArgIndx]->isImm()) &&
7130          "invalid operand");
7131   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7132   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7133   if (argOpers[valArgIndx]->isReg())
7134     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7135   else
7136     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7137   if (regOpcL != X86::MOV32rr)
7138     MIB.addReg(tt1);
7139   (*MIB).addOperand(*argOpers[valArgIndx]);
7140   assert(argOpers[valArgIndx + 1]->isReg() ==
7141          argOpers[valArgIndx]->isReg());
7142   assert(argOpers[valArgIndx + 1]->isImm() ==
7143          argOpers[valArgIndx]->isImm());
7144   if (argOpers[valArgIndx + 1]->isReg())
7145     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7146   else
7147     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7148   if (regOpcH != X86::MOV32rr)
7149     MIB.addReg(tt2);
7150   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7151
7152   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7153   MIB.addReg(t1);
7154   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7155   MIB.addReg(t2);
7156
7157   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7158   MIB.addReg(t5);
7159   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7160   MIB.addReg(t6);
7161
7162   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7163   for (int i=0; i <= lastAddrIndx; ++i)
7164     (*MIB).addOperand(*argOpers[i]);
7165
7166   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7167   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7168
7169   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7170   MIB.addReg(X86::EAX);
7171   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7172   MIB.addReg(X86::EDX);
7173
7174   // insert branch
7175   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7176
7177   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7178   return nextMBB;
7179 }
7180
7181 // private utility function
7182 MachineBasicBlock *
7183 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7184                                                       MachineBasicBlock *MBB,
7185                                                       unsigned cmovOpc) const {
7186   // For the atomic min/max operator, we generate
7187   //   thisMBB:
7188   //   newMBB:
7189   //     ld t1 = [min/max.addr]
7190   //     mov t2 = [min/max.val]
7191   //     cmp  t1, t2
7192   //     cmov[cond] t2 = t1
7193   //     mov EAX = t1
7194   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7195   //     bz   newMBB
7196   //     fallthrough -->nextMBB
7197   //
7198   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7199   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7200   MachineFunction::iterator MBBIter = MBB;
7201   ++MBBIter;
7202
7203   /// First build the CFG
7204   MachineFunction *F = MBB->getParent();
7205   MachineBasicBlock *thisMBB = MBB;
7206   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7207   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7208   F->insert(MBBIter, newMBB);
7209   F->insert(MBBIter, nextMBB);
7210
7211   // Move all successors to thisMBB to nextMBB
7212   nextMBB->transferSuccessors(thisMBB);
7213
7214   // Update thisMBB to fall through to newMBB
7215   thisMBB->addSuccessor(newMBB);
7216
7217   // newMBB jumps to newMBB and fall through to nextMBB
7218   newMBB->addSuccessor(nextMBB);
7219   newMBB->addSuccessor(newMBB);
7220
7221   DebugLoc dl = mInstr->getDebugLoc();
7222   // Insert instructions into newMBB based on incoming instruction
7223   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7224          "unexpected number of operands");
7225   MachineOperand& destOper = mInstr->getOperand(0);
7226   MachineOperand* argOpers[2 + X86AddrNumOperands];
7227   int numArgs = mInstr->getNumOperands() - 1;
7228   for (int i=0; i < numArgs; ++i)
7229     argOpers[i] = &mInstr->getOperand(i+1);
7230
7231   // x86 address has 4 operands: base, index, scale, and displacement
7232   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7233   int valArgIndx = lastAddrIndx + 1;
7234
7235   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7236   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7237   for (int i=0; i <= lastAddrIndx; ++i)
7238     (*MIB).addOperand(*argOpers[i]);
7239
7240   // We only support register and immediate values
7241   assert((argOpers[valArgIndx]->isReg() ||
7242           argOpers[valArgIndx]->isImm()) &&
7243          "invalid operand");
7244
7245   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7246   if (argOpers[valArgIndx]->isReg())
7247     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7248   else
7249     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7250   (*MIB).addOperand(*argOpers[valArgIndx]);
7251
7252   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7253   MIB.addReg(t1);
7254
7255   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7256   MIB.addReg(t1);
7257   MIB.addReg(t2);
7258
7259   // Generate movc
7260   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7261   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7262   MIB.addReg(t2);
7263   MIB.addReg(t1);
7264
7265   // Cmp and exchange if none has modified the memory location
7266   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7267   for (int i=0; i <= lastAddrIndx; ++i)
7268     (*MIB).addOperand(*argOpers[i]);
7269   MIB.addReg(t3);
7270   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7271   (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7272
7273   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7274   MIB.addReg(X86::EAX);
7275
7276   // insert branch
7277   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7278
7279   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
7280   return nextMBB;
7281 }
7282
7283
7284 MachineBasicBlock *
7285 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7286                                                MachineBasicBlock *BB) const {
7287   DebugLoc dl = MI->getDebugLoc();
7288   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7289   switch (MI->getOpcode()) {
7290   default: assert(false && "Unexpected instr type to insert");
7291   case X86::CMOV_V1I64:
7292   case X86::CMOV_FR32:
7293   case X86::CMOV_FR64:
7294   case X86::CMOV_V4F32:
7295   case X86::CMOV_V2F64:
7296   case X86::CMOV_V2I64: {
7297     // To "insert" a SELECT_CC instruction, we actually have to insert the
7298     // diamond control-flow pattern.  The incoming instruction knows the
7299     // destination vreg to set, the condition code register to branch on, the
7300     // true/false values to select between, and a branch opcode to use.
7301     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7302     MachineFunction::iterator It = BB;
7303     ++It;
7304
7305     //  thisMBB:
7306     //  ...
7307     //   TrueVal = ...
7308     //   cmpTY ccX, r1, r2
7309     //   bCC copy1MBB
7310     //   fallthrough --> copy0MBB
7311     MachineBasicBlock *thisMBB = BB;
7312     MachineFunction *F = BB->getParent();
7313     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7314     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7315     unsigned Opc =
7316       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7317     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7318     F->insert(It, copy0MBB);
7319     F->insert(It, sinkMBB);
7320     // Update machine-CFG edges by transferring all successors of the current
7321     // block to the new block which will contain the Phi node for the select.
7322     sinkMBB->transferSuccessors(BB);
7323
7324     // Add the true and fallthrough blocks as its successors.
7325     BB->addSuccessor(copy0MBB);
7326     BB->addSuccessor(sinkMBB);
7327
7328     //  copy0MBB:
7329     //   %FalseValue = ...
7330     //   # fallthrough to sinkMBB
7331     BB = copy0MBB;
7332
7333     // Update machine-CFG edges
7334     BB->addSuccessor(sinkMBB);
7335
7336     //  sinkMBB:
7337     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7338     //  ...
7339     BB = sinkMBB;
7340     BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7341       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7342       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7343
7344     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7345     return BB;
7346   }
7347
7348   case X86::FP32_TO_INT16_IN_MEM:
7349   case X86::FP32_TO_INT32_IN_MEM:
7350   case X86::FP32_TO_INT64_IN_MEM:
7351   case X86::FP64_TO_INT16_IN_MEM:
7352   case X86::FP64_TO_INT32_IN_MEM:
7353   case X86::FP64_TO_INT64_IN_MEM:
7354   case X86::FP80_TO_INT16_IN_MEM:
7355   case X86::FP80_TO_INT32_IN_MEM:
7356   case X86::FP80_TO_INT64_IN_MEM: {
7357     // Change the floating point control register to use "round towards zero"
7358     // mode when truncating to an integer value.
7359     MachineFunction *F = BB->getParent();
7360     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7361     addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7362
7363     // Load the old value of the high byte of the control word...
7364     unsigned OldCW =
7365       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7366     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7367                       CWFrameIdx);
7368
7369     // Set the high part to be round to zero...
7370     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7371       .addImm(0xC7F);
7372
7373     // Reload the modified control word now...
7374     addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7375
7376     // Restore the memory image of control word to original value
7377     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7378       .addReg(OldCW);
7379
7380     // Get the X86 opcode to use.
7381     unsigned Opc;
7382     switch (MI->getOpcode()) {
7383     default: assert(0 && "illegal opcode!");
7384     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7385     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7386     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7387     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7388     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7389     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7390     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7391     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7392     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7393     }
7394
7395     X86AddressMode AM;
7396     MachineOperand &Op = MI->getOperand(0);
7397     if (Op.isReg()) {
7398       AM.BaseType = X86AddressMode::RegBase;
7399       AM.Base.Reg = Op.getReg();
7400     } else {
7401       AM.BaseType = X86AddressMode::FrameIndexBase;
7402       AM.Base.FrameIndex = Op.getIndex();
7403     }
7404     Op = MI->getOperand(1);
7405     if (Op.isImm())
7406       AM.Scale = Op.getImm();
7407     Op = MI->getOperand(2);
7408     if (Op.isImm())
7409       AM.IndexReg = Op.getImm();
7410     Op = MI->getOperand(3);
7411     if (Op.isGlobal()) {
7412       AM.GV = Op.getGlobal();
7413     } else {
7414       AM.Disp = Op.getImm();
7415     }
7416     addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7417                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7418
7419     // Reload the original control word now.
7420     addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7421
7422     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7423     return BB;
7424   }
7425   case X86::ATOMAND32:
7426     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7427                                                X86::AND32ri, X86::MOV32rm,
7428                                                X86::LCMPXCHG32, X86::MOV32rr,
7429                                                X86::NOT32r, X86::EAX,
7430                                                X86::GR32RegisterClass);
7431   case X86::ATOMOR32:
7432     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7433                                                X86::OR32ri, X86::MOV32rm,
7434                                                X86::LCMPXCHG32, X86::MOV32rr,
7435                                                X86::NOT32r, X86::EAX,
7436                                                X86::GR32RegisterClass);
7437   case X86::ATOMXOR32:
7438     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7439                                                X86::XOR32ri, X86::MOV32rm,
7440                                                X86::LCMPXCHG32, X86::MOV32rr,
7441                                                X86::NOT32r, X86::EAX,
7442                                                X86::GR32RegisterClass);
7443   case X86::ATOMNAND32:
7444     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7445                                                X86::AND32ri, X86::MOV32rm,
7446                                                X86::LCMPXCHG32, X86::MOV32rr,
7447                                                X86::NOT32r, X86::EAX,
7448                                                X86::GR32RegisterClass, true);
7449   case X86::ATOMMIN32:
7450     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7451   case X86::ATOMMAX32:
7452     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7453   case X86::ATOMUMIN32:
7454     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7455   case X86::ATOMUMAX32:
7456     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7457
7458   case X86::ATOMAND16:
7459     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7460                                                X86::AND16ri, X86::MOV16rm,
7461                                                X86::LCMPXCHG16, X86::MOV16rr,
7462                                                X86::NOT16r, X86::AX,
7463                                                X86::GR16RegisterClass);
7464   case X86::ATOMOR16:
7465     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7466                                                X86::OR16ri, X86::MOV16rm,
7467                                                X86::LCMPXCHG16, X86::MOV16rr,
7468                                                X86::NOT16r, X86::AX,
7469                                                X86::GR16RegisterClass);
7470   case X86::ATOMXOR16:
7471     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7472                                                X86::XOR16ri, X86::MOV16rm,
7473                                                X86::LCMPXCHG16, X86::MOV16rr,
7474                                                X86::NOT16r, X86::AX,
7475                                                X86::GR16RegisterClass);
7476   case X86::ATOMNAND16:
7477     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7478                                                X86::AND16ri, X86::MOV16rm,
7479                                                X86::LCMPXCHG16, X86::MOV16rr,
7480                                                X86::NOT16r, X86::AX,
7481                                                X86::GR16RegisterClass, true);
7482   case X86::ATOMMIN16:
7483     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7484   case X86::ATOMMAX16:
7485     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7486   case X86::ATOMUMIN16:
7487     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7488   case X86::ATOMUMAX16:
7489     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7490
7491   case X86::ATOMAND8:
7492     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7493                                                X86::AND8ri, X86::MOV8rm,
7494                                                X86::LCMPXCHG8, X86::MOV8rr,
7495                                                X86::NOT8r, X86::AL,
7496                                                X86::GR8RegisterClass);
7497   case X86::ATOMOR8:
7498     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7499                                                X86::OR8ri, X86::MOV8rm,
7500                                                X86::LCMPXCHG8, X86::MOV8rr,
7501                                                X86::NOT8r, X86::AL,
7502                                                X86::GR8RegisterClass);
7503   case X86::ATOMXOR8:
7504     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7505                                                X86::XOR8ri, X86::MOV8rm,
7506                                                X86::LCMPXCHG8, X86::MOV8rr,
7507                                                X86::NOT8r, X86::AL,
7508                                                X86::GR8RegisterClass);
7509   case X86::ATOMNAND8:
7510     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7511                                                X86::AND8ri, X86::MOV8rm,
7512                                                X86::LCMPXCHG8, X86::MOV8rr,
7513                                                X86::NOT8r, X86::AL,
7514                                                X86::GR8RegisterClass, true);
7515   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7516   // This group is for 64-bit host.
7517   case X86::ATOMAND64:
7518     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7519                                                X86::AND64ri32, X86::MOV64rm,
7520                                                X86::LCMPXCHG64, X86::MOV64rr,
7521                                                X86::NOT64r, X86::RAX,
7522                                                X86::GR64RegisterClass);
7523   case X86::ATOMOR64:
7524     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7525                                                X86::OR64ri32, X86::MOV64rm,
7526                                                X86::LCMPXCHG64, X86::MOV64rr,
7527                                                X86::NOT64r, X86::RAX,
7528                                                X86::GR64RegisterClass);
7529   case X86::ATOMXOR64:
7530     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7531                                                X86::XOR64ri32, X86::MOV64rm,
7532                                                X86::LCMPXCHG64, X86::MOV64rr,
7533                                                X86::NOT64r, X86::RAX,
7534                                                X86::GR64RegisterClass);
7535   case X86::ATOMNAND64:
7536     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7537                                                X86::AND64ri32, X86::MOV64rm,
7538                                                X86::LCMPXCHG64, X86::MOV64rr,
7539                                                X86::NOT64r, X86::RAX,
7540                                                X86::GR64RegisterClass, true);
7541   case X86::ATOMMIN64:
7542     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7543   case X86::ATOMMAX64:
7544     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7545   case X86::ATOMUMIN64:
7546     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7547   case X86::ATOMUMAX64:
7548     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7549
7550   // This group does 64-bit operations on a 32-bit host.
7551   case X86::ATOMAND6432:
7552     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7553                                                X86::AND32rr, X86::AND32rr,
7554                                                X86::AND32ri, X86::AND32ri,
7555                                                false);
7556   case X86::ATOMOR6432:
7557     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7558                                                X86::OR32rr, X86::OR32rr,
7559                                                X86::OR32ri, X86::OR32ri,
7560                                                false);
7561   case X86::ATOMXOR6432:
7562     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7563                                                X86::XOR32rr, X86::XOR32rr,
7564                                                X86::XOR32ri, X86::XOR32ri,
7565                                                false);
7566   case X86::ATOMNAND6432:
7567     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7568                                                X86::AND32rr, X86::AND32rr,
7569                                                X86::AND32ri, X86::AND32ri,
7570                                                true);
7571   case X86::ATOMADD6432:
7572     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7573                                                X86::ADD32rr, X86::ADC32rr,
7574                                                X86::ADD32ri, X86::ADC32ri,
7575                                                false);
7576   case X86::ATOMSUB6432:
7577     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7578                                                X86::SUB32rr, X86::SBB32rr,
7579                                                X86::SUB32ri, X86::SBB32ri,
7580                                                false);
7581   case X86::ATOMSWAP6432:
7582     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7583                                                X86::MOV32rr, X86::MOV32rr,
7584                                                X86::MOV32ri, X86::MOV32ri,
7585                                                false);
7586   }
7587 }
7588
7589 //===----------------------------------------------------------------------===//
7590 //                           X86 Optimization Hooks
7591 //===----------------------------------------------------------------------===//
7592
7593 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7594                                                        const APInt &Mask,
7595                                                        APInt &KnownZero,
7596                                                        APInt &KnownOne,
7597                                                        const SelectionDAG &DAG,
7598                                                        unsigned Depth) const {
7599   unsigned Opc = Op.getOpcode();
7600   assert((Opc >= ISD::BUILTIN_OP_END ||
7601           Opc == ISD::INTRINSIC_WO_CHAIN ||
7602           Opc == ISD::INTRINSIC_W_CHAIN ||
7603           Opc == ISD::INTRINSIC_VOID) &&
7604          "Should use MaskedValueIsZero if you don't know whether Op"
7605          " is a target node!");
7606
7607   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
7608   switch (Opc) {
7609   default: break;
7610   case X86ISD::ADD:
7611   case X86ISD::SUB:
7612   case X86ISD::SMUL:
7613   case X86ISD::UMUL:
7614   case X86ISD::INC:
7615   case X86ISD::DEC:
7616     // These nodes' second result is a boolean.
7617     if (Op.getResNo() == 0)
7618       break;
7619     // Fallthrough
7620   case X86ISD::SETCC:
7621     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7622                                        Mask.getBitWidth() - 1);
7623     break;
7624   }
7625 }
7626
7627 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7628 /// node is a GlobalAddress + offset.
7629 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7630                                        GlobalValue* &GA, int64_t &Offset) const{
7631   if (N->getOpcode() == X86ISD::Wrapper) {
7632     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7633       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7634       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7635       return true;
7636     }
7637   }
7638   return TargetLowering::isGAPlusOffset(N, GA, Offset);
7639 }
7640
7641 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7642                                const TargetLowering &TLI) {
7643   GlobalValue *GV;
7644   int64_t Offset = 0;
7645   if (TLI.isGAPlusOffset(Base, GV, Offset))
7646     return (GV->getAlignment() >= N && (Offset % N) == 0);
7647   // DAG combine handles the stack object case.
7648   return false;
7649 }
7650
7651 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7652                                      MVT EVT, SDNode *&Base,
7653                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
7654                                      const TargetLowering &TLI) {
7655   Base = NULL;
7656   for (unsigned i = 0; i < NumElems; ++i) {
7657     if (N->getMaskElt(i) < 0) {
7658       if (!Base)
7659         return false;
7660       continue;
7661     }
7662
7663     SDValue Elt = DAG.getShuffleScalarElt(N, i);
7664     if (!Elt.getNode() ||
7665         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7666       return false;
7667     if (!Base) {
7668       Base = Elt.getNode();
7669       if (Base->getOpcode() == ISD::UNDEF)
7670         return false;
7671       continue;
7672     }
7673     if (Elt.getOpcode() == ISD::UNDEF)
7674       continue;
7675
7676     if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7677                                EVT.getSizeInBits()/8, i, MFI))
7678       return false;
7679   }
7680   return true;
7681 }
7682
7683 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7684 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7685 /// if the load addresses are consecutive, non-overlapping, and in the right
7686 /// order.  In the case of v2i64, it will see if it can rewrite the
7687 /// shuffle to be an appropriate build vector so it can take advantage of
7688 // performBuildVectorCombine.
7689 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7690                                      const TargetLowering &TLI) {
7691   DebugLoc dl = N->getDebugLoc();
7692   MVT VT = N->getValueType(0);
7693   MVT EVT = VT.getVectorElementType();
7694   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7695   unsigned NumElems = VT.getVectorNumElements();
7696
7697   // For x86-32 machines, if we see an insert and then a shuffle in a v2i64
7698   // where the upper half is 0, it is advantageous to rewrite it as a build
7699   // vector of (0, val) so it can use movq.
7700   if (VT == MVT::v2i64) {
7701     SDValue In[2];
7702     In[0] = N->getOperand(0);
7703     In[1] = N->getOperand(1);
7704     int Idx0 = SVN->getMaskElt(0);
7705     int Idx1 = SVN->getMaskElt(1);
7706     // FIXME: can we take advantage of undef index?
7707     if (Idx0 >= 0 && Idx1 >= 0 &&
7708         In[Idx0/2].getOpcode() == ISD::INSERT_VECTOR_ELT &&
7709         In[Idx1/2].getOpcode() == ISD::BUILD_VECTOR) {
7710       ConstantSDNode* InsertVecIdx =
7711                              dyn_cast<ConstantSDNode>(In[Idx0/2].getOperand(2));
7712       if (InsertVecIdx &&
7713           InsertVecIdx->getZExtValue() == (unsigned)(Idx0 % 2) &&
7714           isZeroNode(In[Idx1/2].getOperand(Idx1 % 2))) {
7715         return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7716                            In[Idx0/2].getOperand(1),
7717                            In[Idx1/2].getOperand(Idx1 % 2));
7718       }
7719     }
7720   }
7721
7722   // Try to combine a vector_shuffle into a 128-bit load.
7723   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7724   SDNode *Base = NULL;
7725   if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, Base, DAG, MFI, TLI))
7726     return SDValue();
7727
7728   LoadSDNode *LD = cast<LoadSDNode>(Base);
7729   if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7730     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7731                        LD->getSrcValue(), LD->getSrcValueOffset(),
7732                        LD->isVolatile());
7733   return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7734                      LD->getSrcValue(), LD->getSrcValueOffset(),
7735                      LD->isVolatile(), LD->getAlignment());
7736 }
7737
7738 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7739 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7740                                          TargetLowering::DAGCombinerInfo &DCI,
7741                                          const X86Subtarget *Subtarget,
7742                                          const TargetLowering &TLI) {
7743   unsigned NumOps = N->getNumOperands();
7744   DebugLoc dl = N->getDebugLoc();
7745
7746   // Ignore single operand BUILD_VECTOR.
7747   if (NumOps == 1)
7748     return SDValue();
7749
7750   MVT VT = N->getValueType(0);
7751   MVT EVT = VT.getVectorElementType();
7752   if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7753     // We are looking for load i64 and zero extend. We want to transform
7754     // it before legalizer has a chance to expand it. Also look for i64
7755     // BUILD_PAIR bit casted to f64.
7756     return SDValue();
7757   // This must be an insertion into a zero vector.
7758   SDValue HighElt = N->getOperand(1);
7759   if (!isZeroNode(HighElt))
7760     return SDValue();
7761
7762   // Value must be a load.
7763   SDNode *Base = N->getOperand(0).getNode();
7764   if (!isa<LoadSDNode>(Base)) {
7765     if (Base->getOpcode() != ISD::BIT_CONVERT)
7766       return SDValue();
7767     Base = Base->getOperand(0).getNode();
7768     if (!isa<LoadSDNode>(Base))
7769       return SDValue();
7770   }
7771
7772   // Transform it into VZEXT_LOAD addr.
7773   LoadSDNode *LD = cast<LoadSDNode>(Base);
7774
7775   // Load must not be an extload.
7776   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7777     return SDValue();
7778
7779   // Load type should legal type so we don't have to legalize it.
7780   if (!TLI.isTypeLegal(VT))
7781     return SDValue();
7782
7783   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7784   SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7785   SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7786   TargetLowering::TargetLoweringOpt TLO(DAG);
7787   TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7788   DCI.CommitTargetLoweringOpt(TLO);
7789   return ResNode;
7790 }
7791
7792 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7793 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7794                                     const X86Subtarget *Subtarget) {
7795   DebugLoc DL = N->getDebugLoc();
7796   SDValue Cond = N->getOperand(0);
7797   // Get the LHS/RHS of the select.
7798   SDValue LHS = N->getOperand(1);
7799   SDValue RHS = N->getOperand(2);
7800   
7801   // If we have SSE[12] support, try to form min/max nodes.
7802   if (Subtarget->hasSSE2() &&
7803       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7804       Cond.getOpcode() == ISD::SETCC) {
7805     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7806
7807     unsigned Opcode = 0;
7808     if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7809       switch (CC) {
7810       default: break;
7811       case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7812       case ISD::SETULE:
7813       case ISD::SETLE:
7814         if (!UnsafeFPMath) break;
7815         // FALL THROUGH.
7816       case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
7817       case ISD::SETLT:
7818         Opcode = X86ISD::FMIN;
7819         break;
7820
7821       case ISD::SETOGT: // (X > Y) ? X : Y -> max
7822       case ISD::SETUGT:
7823       case ISD::SETGT:
7824         if (!UnsafeFPMath) break;
7825         // FALL THROUGH.
7826       case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
7827       case ISD::SETGE:
7828         Opcode = X86ISD::FMAX;
7829         break;
7830       }
7831     } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7832       switch (CC) {
7833       default: break;
7834       case ISD::SETOGT: // (X > Y) ? Y : X -> min
7835       case ISD::SETUGT:
7836       case ISD::SETGT:
7837         if (!UnsafeFPMath) break;
7838         // FALL THROUGH.
7839       case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
7840       case ISD::SETGE:
7841         Opcode = X86ISD::FMIN;
7842         break;
7843
7844       case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
7845       case ISD::SETULE:
7846       case ISD::SETLE:
7847         if (!UnsafeFPMath) break;
7848         // FALL THROUGH.
7849       case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
7850       case ISD::SETLT:
7851         Opcode = X86ISD::FMAX;
7852         break;
7853       }
7854     }
7855
7856     if (Opcode)
7857       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
7858   }
7859   
7860   // If this is a select between two integer constants, try to do some
7861   // optimizations.
7862   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
7863     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
7864       // Don't do this for crazy integer types.
7865       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
7866         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
7867         // so that TrueC (the true value) is larger than FalseC.
7868         bool NeedsCondInvert = false;
7869         
7870         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
7871             // Efficiently invertible.
7872             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
7873              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
7874               isa<ConstantSDNode>(Cond.getOperand(1))))) {
7875           NeedsCondInvert = true;
7876           std::swap(TrueC, FalseC);
7877         }
7878    
7879         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
7880         if (FalseC->getAPIntValue() == 0 &&
7881             TrueC->getAPIntValue().isPowerOf2()) {
7882           if (NeedsCondInvert) // Invert the condition if needed.
7883             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7884                                DAG.getConstant(1, Cond.getValueType()));
7885           
7886           // Zero extend the condition if needed.
7887           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
7888           
7889           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7890           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
7891                              DAG.getConstant(ShAmt, MVT::i8));
7892         }
7893         
7894         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
7895         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7896           if (NeedsCondInvert) // Invert the condition if needed.
7897             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7898                                DAG.getConstant(1, Cond.getValueType()));
7899           
7900           // Zero extend the condition if needed.
7901           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7902                              FalseC->getValueType(0), Cond);
7903           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7904                              SDValue(FalseC, 0));
7905         }
7906         
7907         // Optimize cases that will turn into an LEA instruction.  This requires
7908         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7909         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7910           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7911           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7912           
7913           bool isFastMultiplier = false;
7914           if (Diff < 10) {
7915             switch ((unsigned char)Diff) {
7916               default: break;
7917               case 1:  // result = add base, cond
7918               case 2:  // result = lea base(    , cond*2)
7919               case 3:  // result = lea base(cond, cond*2)
7920               case 4:  // result = lea base(    , cond*4)
7921               case 5:  // result = lea base(cond, cond*4)
7922               case 8:  // result = lea base(    , cond*8)
7923               case 9:  // result = lea base(cond, cond*8)
7924                 isFastMultiplier = true;
7925                 break;
7926             }
7927           }
7928           
7929           if (isFastMultiplier) {
7930             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
7931             if (NeedsCondInvert) // Invert the condition if needed.
7932               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7933                                  DAG.getConstant(1, Cond.getValueType()));
7934             
7935             // Zero extend the condition if needed.
7936             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
7937                                Cond);
7938             // Scale the condition by the difference.
7939             if (Diff != 1)
7940               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
7941                                  DAG.getConstant(Diff, Cond.getValueType()));
7942             
7943             // Add the base if non-zero.
7944             if (FalseC->getAPIntValue() != 0)
7945               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7946                                  SDValue(FalseC, 0));
7947             return Cond;
7948           }
7949         }      
7950       }
7951   }
7952       
7953   return SDValue();
7954 }
7955
7956 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
7957 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
7958                                   TargetLowering::DAGCombinerInfo &DCI) {
7959   DebugLoc DL = N->getDebugLoc();
7960   
7961   // If the flag operand isn't dead, don't touch this CMOV.
7962   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
7963     return SDValue();
7964   
7965   // If this is a select between two integer constants, try to do some
7966   // optimizations.  Note that the operands are ordered the opposite of SELECT
7967   // operands.
7968   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7969     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7970       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
7971       // larger than FalseC (the false value).
7972       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
7973         
7974       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
7975         CC = X86::GetOppositeBranchCondition(CC);
7976         std::swap(TrueC, FalseC);
7977       }
7978         
7979       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
7980       // This is efficient for any integer data type (including i8/i16) and
7981       // shift amount.
7982       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
7983         SDValue Cond = N->getOperand(3);
7984         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7985                            DAG.getConstant(CC, MVT::i8), Cond);
7986       
7987         // Zero extend the condition if needed.
7988         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
7989         
7990         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7991         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
7992                            DAG.getConstant(ShAmt, MVT::i8));
7993         if (N->getNumValues() == 2)  // Dead flag value?
7994           return DCI.CombineTo(N, Cond, SDValue());
7995         return Cond;
7996       }
7997       
7998       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
7999       // for any integer data type, including i8/i16.
8000       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8001         SDValue Cond = N->getOperand(3);
8002         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8003                            DAG.getConstant(CC, MVT::i8), Cond);
8004         
8005         // Zero extend the condition if needed.
8006         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8007                            FalseC->getValueType(0), Cond);
8008         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8009                            SDValue(FalseC, 0));
8010         
8011         if (N->getNumValues() == 2)  // Dead flag value?
8012           return DCI.CombineTo(N, Cond, SDValue());
8013         return Cond;
8014       }
8015       
8016       // Optimize cases that will turn into an LEA instruction.  This requires
8017       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8018       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8019         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8020         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8021        
8022         bool isFastMultiplier = false;
8023         if (Diff < 10) {
8024           switch ((unsigned char)Diff) {
8025           default: break;
8026           case 1:  // result = add base, cond
8027           case 2:  // result = lea base(    , cond*2)
8028           case 3:  // result = lea base(cond, cond*2)
8029           case 4:  // result = lea base(    , cond*4)
8030           case 5:  // result = lea base(cond, cond*4)
8031           case 8:  // result = lea base(    , cond*8)
8032           case 9:  // result = lea base(cond, cond*8)
8033             isFastMultiplier = true;
8034             break;
8035           }
8036         }
8037         
8038         if (isFastMultiplier) {
8039           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8040           SDValue Cond = N->getOperand(3);
8041           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8042                              DAG.getConstant(CC, MVT::i8), Cond);
8043           // Zero extend the condition if needed.
8044           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8045                              Cond);
8046           // Scale the condition by the difference.
8047           if (Diff != 1)
8048             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8049                                DAG.getConstant(Diff, Cond.getValueType()));
8050
8051           // Add the base if non-zero.
8052           if (FalseC->getAPIntValue() != 0)
8053             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8054                                SDValue(FalseC, 0));
8055           if (N->getNumValues() == 2)  // Dead flag value?
8056             return DCI.CombineTo(N, Cond, SDValue());
8057           return Cond;
8058         }
8059       }      
8060     }
8061   }
8062   return SDValue();
8063 }
8064
8065
8066 /// PerformMulCombine - Optimize a single multiply with constant into two
8067 /// in order to implement it with two cheaper instructions, e.g.
8068 /// LEA + SHL, LEA + LEA.
8069 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8070                                  TargetLowering::DAGCombinerInfo &DCI) {
8071   if (DAG.getMachineFunction().
8072       getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8073     return SDValue();
8074
8075   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8076     return SDValue();
8077
8078   MVT VT = N->getValueType(0);
8079   if (VT != MVT::i64)
8080     return SDValue();
8081
8082   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8083   if (!C)
8084     return SDValue();
8085   uint64_t MulAmt = C->getZExtValue();
8086   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8087     return SDValue();
8088
8089   uint64_t MulAmt1 = 0;
8090   uint64_t MulAmt2 = 0;
8091   if ((MulAmt % 9) == 0) {
8092     MulAmt1 = 9;
8093     MulAmt2 = MulAmt / 9;
8094   } else if ((MulAmt % 5) == 0) {
8095     MulAmt1 = 5;
8096     MulAmt2 = MulAmt / 5;
8097   } else if ((MulAmt % 3) == 0) {
8098     MulAmt1 = 3;
8099     MulAmt2 = MulAmt / 3;
8100   }
8101   if (MulAmt2 &&
8102       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8103     DebugLoc DL = N->getDebugLoc();
8104
8105     if (isPowerOf2_64(MulAmt2) &&
8106         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8107       // If second multiplifer is pow2, issue it first. We want the multiply by
8108       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8109       // is an add.
8110       std::swap(MulAmt1, MulAmt2);
8111
8112     SDValue NewMul;
8113     if (isPowerOf2_64(MulAmt1)) 
8114       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8115                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8116     else
8117       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8118                            DAG.getConstant(MulAmt1, VT));
8119
8120     if (isPowerOf2_64(MulAmt2)) 
8121       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8122                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8123     else 
8124       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8125                            DAG.getConstant(MulAmt2, VT));
8126
8127     // Do not add new nodes to DAG combiner worklist.
8128     DCI.CombineTo(N, NewMul, false);
8129   }
8130   return SDValue();
8131 }
8132
8133
8134 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8135 ///                       when possible.
8136 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8137                                    const X86Subtarget *Subtarget) {
8138   // On X86 with SSE2 support, we can transform this to a vector shift if
8139   // all elements are shifted by the same amount.  We can't do this in legalize
8140   // because the a constant vector is typically transformed to a constant pool
8141   // so we have no knowledge of the shift amount.
8142   if (!Subtarget->hasSSE2())
8143     return SDValue();
8144
8145   MVT VT = N->getValueType(0);
8146   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8147     return SDValue();
8148
8149   SDValue ShAmtOp = N->getOperand(1);
8150   MVT EltVT = VT.getVectorElementType();
8151   DebugLoc DL = N->getDebugLoc();
8152   SDValue BaseShAmt;
8153   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8154     unsigned NumElts = VT.getVectorNumElements();
8155     unsigned i = 0;
8156     for (; i != NumElts; ++i) {
8157       SDValue Arg = ShAmtOp.getOperand(i);
8158       if (Arg.getOpcode() == ISD::UNDEF) continue;
8159       BaseShAmt = Arg;
8160       break;
8161     }
8162     for (; i != NumElts; ++i) {
8163       SDValue Arg = ShAmtOp.getOperand(i);
8164       if (Arg.getOpcode() == ISD::UNDEF) continue;
8165       if (Arg != BaseShAmt) {
8166         return SDValue();
8167       }
8168     }
8169   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8170              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8171     BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8172                             DAG.getIntPtrConstant(0));
8173   } else
8174     return SDValue();
8175
8176   if (EltVT.bitsGT(MVT::i32))
8177     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8178   else if (EltVT.bitsLT(MVT::i32))
8179     BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8180
8181   // The shift amount is identical so we can do a vector shift.
8182   SDValue  ValOp = N->getOperand(0);
8183   switch (N->getOpcode()) {
8184   default:
8185     assert(0 && "Unknown shift opcode!");
8186     break;
8187   case ISD::SHL:
8188     if (VT == MVT::v2i64)
8189       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8190                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8191                          ValOp, BaseShAmt);
8192     if (VT == MVT::v4i32)
8193       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8194                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8195                          ValOp, BaseShAmt);
8196     if (VT == MVT::v8i16)
8197       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8198                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8199                          ValOp, BaseShAmt);
8200     break;
8201   case ISD::SRA:
8202     if (VT == MVT::v4i32)
8203       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8204                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8205                          ValOp, BaseShAmt);
8206     if (VT == MVT::v8i16)
8207       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8208                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8209                          ValOp, BaseShAmt);
8210     break;
8211   case ISD::SRL:
8212     if (VT == MVT::v2i64)
8213       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8214                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8215                          ValOp, BaseShAmt);
8216     if (VT == MVT::v4i32)
8217       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8218                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8219                          ValOp, BaseShAmt);
8220     if (VT ==  MVT::v8i16)
8221       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8222                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8223                          ValOp, BaseShAmt);
8224     break;
8225   }
8226   return SDValue();
8227 }
8228
8229 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8230 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8231                                    const X86Subtarget *Subtarget) {
8232   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
8233   // the FP state in cases where an emms may be missing.
8234   // A preferable solution to the general problem is to figure out the right
8235   // places to insert EMMS.  This qualifies as a quick hack.
8236
8237   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8238   StoreSDNode *St = cast<StoreSDNode>(N);
8239   MVT VT = St->getValue().getValueType();
8240   if (VT.getSizeInBits() != 64)
8241     return SDValue();
8242
8243   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE2();
8244   if ((VT.isVector() ||
8245        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8246       isa<LoadSDNode>(St->getValue()) &&
8247       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8248       St->getChain().hasOneUse() && !St->isVolatile()) {
8249     SDNode* LdVal = St->getValue().getNode();
8250     LoadSDNode *Ld = 0;
8251     int TokenFactorIndex = -1;
8252     SmallVector<SDValue, 8> Ops;
8253     SDNode* ChainVal = St->getChain().getNode();
8254     // Must be a store of a load.  We currently handle two cases:  the load
8255     // is a direct child, and it's under an intervening TokenFactor.  It is
8256     // possible to dig deeper under nested TokenFactors.
8257     if (ChainVal == LdVal)
8258       Ld = cast<LoadSDNode>(St->getChain());
8259     else if (St->getValue().hasOneUse() &&
8260              ChainVal->getOpcode() == ISD::TokenFactor) {
8261       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8262         if (ChainVal->getOperand(i).getNode() == LdVal) {
8263           TokenFactorIndex = i;
8264           Ld = cast<LoadSDNode>(St->getValue());
8265         } else
8266           Ops.push_back(ChainVal->getOperand(i));
8267       }
8268     }
8269
8270     if (!Ld || !ISD::isNormalLoad(Ld))
8271       return SDValue();
8272
8273     // If this is not the MMX case, i.e. we are just turning i64 load/store
8274     // into f64 load/store, avoid the transformation if there are multiple
8275     // uses of the loaded value.
8276     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8277       return SDValue();
8278
8279     DebugLoc LdDL = Ld->getDebugLoc();
8280     DebugLoc StDL = N->getDebugLoc();
8281     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8282     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8283     // pair instead.
8284     if (Subtarget->is64Bit() || F64IsLegal) {
8285       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8286       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8287                                   Ld->getBasePtr(), Ld->getSrcValue(),
8288                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
8289                                   Ld->getAlignment());
8290       SDValue NewChain = NewLd.getValue(1);
8291       if (TokenFactorIndex != -1) {
8292         Ops.push_back(NewChain);
8293         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8294                                Ops.size());
8295       }
8296       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8297                           St->getSrcValue(), St->getSrcValueOffset(),
8298                           St->isVolatile(), St->getAlignment());
8299     }
8300
8301     // Otherwise, lower to two pairs of 32-bit loads / stores.
8302     SDValue LoAddr = Ld->getBasePtr();
8303     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8304                                  DAG.getConstant(4, MVT::i32));
8305
8306     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8307                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
8308                                Ld->isVolatile(), Ld->getAlignment());
8309     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8310                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8311                                Ld->isVolatile(),
8312                                MinAlign(Ld->getAlignment(), 4));
8313
8314     SDValue NewChain = LoLd.getValue(1);
8315     if (TokenFactorIndex != -1) {
8316       Ops.push_back(LoLd);
8317       Ops.push_back(HiLd);
8318       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8319                              Ops.size());
8320     }
8321
8322     LoAddr = St->getBasePtr();
8323     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8324                          DAG.getConstant(4, MVT::i32));
8325
8326     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8327                                 St->getSrcValue(), St->getSrcValueOffset(),
8328                                 St->isVolatile(), St->getAlignment());
8329     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8330                                 St->getSrcValue(),
8331                                 St->getSrcValueOffset() + 4,
8332                                 St->isVolatile(),
8333                                 MinAlign(St->getAlignment(), 4));
8334     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8335   }
8336   return SDValue();
8337 }
8338
8339 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8340 /// X86ISD::FXOR nodes.
8341 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8342   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8343   // F[X]OR(0.0, x) -> x
8344   // F[X]OR(x, 0.0) -> x
8345   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8346     if (C->getValueAPF().isPosZero())
8347       return N->getOperand(1);
8348   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8349     if (C->getValueAPF().isPosZero())
8350       return N->getOperand(0);
8351   return SDValue();
8352 }
8353
8354 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8355 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8356   // FAND(0.0, x) -> 0.0
8357   // FAND(x, 0.0) -> 0.0
8358   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8359     if (C->getValueAPF().isPosZero())
8360       return N->getOperand(0);
8361   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8362     if (C->getValueAPF().isPosZero())
8363       return N->getOperand(1);
8364   return SDValue();
8365 }
8366
8367 static SDValue PerformBTCombine(SDNode *N,
8368                                 SelectionDAG &DAG,
8369                                 TargetLowering::DAGCombinerInfo &DCI) {
8370   // BT ignores high bits in the bit index operand.
8371   SDValue Op1 = N->getOperand(1);
8372   if (Op1.hasOneUse()) {
8373     unsigned BitWidth = Op1.getValueSizeInBits();
8374     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8375     APInt KnownZero, KnownOne;
8376     TargetLowering::TargetLoweringOpt TLO(DAG);
8377     TargetLowering &TLI = DAG.getTargetLoweringInfo();
8378     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8379         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8380       DCI.CommitTargetLoweringOpt(TLO);
8381   }
8382   return SDValue();
8383 }
8384
8385 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8386                                              DAGCombinerInfo &DCI) const {
8387   SelectionDAG &DAG = DCI.DAG;
8388   switch (N->getOpcode()) {
8389   default: break;
8390   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8391   case ISD::BUILD_VECTOR:
8392     return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8393   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
8394   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
8395   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
8396   case ISD::SHL:
8397   case ISD::SRA:
8398   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
8399   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
8400   case X86ISD::FXOR:
8401   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
8402   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
8403   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
8404   }
8405
8406   return SDValue();
8407 }
8408
8409 //===----------------------------------------------------------------------===//
8410 //                           X86 Inline Assembly Support
8411 //===----------------------------------------------------------------------===//
8412
8413 /// getConstraintType - Given a constraint letter, return the type of
8414 /// constraint it is for this target.
8415 X86TargetLowering::ConstraintType
8416 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8417   if (Constraint.size() == 1) {
8418     switch (Constraint[0]) {
8419     case 'A':
8420       return C_Register;
8421     case 'f':
8422     case 'r':
8423     case 'R':
8424     case 'l':
8425     case 'q':
8426     case 'Q':
8427     case 'x':
8428     case 'y':
8429     case 'Y':
8430       return C_RegisterClass;
8431     case 'e':
8432     case 'Z':
8433       return C_Other;
8434     default:
8435       break;
8436     }
8437   }
8438   return TargetLowering::getConstraintType(Constraint);
8439 }
8440
8441 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8442 /// with another that has more specific requirements based on the type of the
8443 /// corresponding operand.
8444 const char *X86TargetLowering::
8445 LowerXConstraint(MVT ConstraintVT) const {
8446   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8447   // 'f' like normal targets.
8448   if (ConstraintVT.isFloatingPoint()) {
8449     if (Subtarget->hasSSE2())
8450       return "Y";
8451     if (Subtarget->hasSSE1())
8452       return "x";
8453   }
8454
8455   return TargetLowering::LowerXConstraint(ConstraintVT);
8456 }
8457
8458 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8459 /// vector.  If it is invalid, don't add anything to Ops.
8460 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8461                                                      char Constraint,
8462                                                      bool hasMemory,
8463                                                      std::vector<SDValue>&Ops,
8464                                                      SelectionDAG &DAG) const {
8465   SDValue Result(0, 0);
8466
8467   switch (Constraint) {
8468   default: break;
8469   case 'I':
8470     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8471       if (C->getZExtValue() <= 31) {
8472         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8473         break;
8474       }
8475     }
8476     return;
8477   case 'J':
8478     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8479       if (C->getZExtValue() <= 63) {
8480         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8481         break;
8482       }
8483     }
8484     return;
8485   case 'N':
8486     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8487       if (C->getZExtValue() <= 255) {
8488         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8489         break;
8490       }
8491     }
8492     return;
8493   case 'e': {
8494     // 32-bit signed value
8495     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8496       const ConstantInt *CI = C->getConstantIntValue();
8497       if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8498         // Widen to 64 bits here to get it sign extended.
8499         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8500         break;
8501       }
8502     // FIXME gcc accepts some relocatable values here too, but only in certain
8503     // memory models; it's complicated.
8504     }
8505     return;
8506   }
8507   case 'Z': {
8508     // 32-bit unsigned value
8509     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8510       const ConstantInt *CI = C->getConstantIntValue();
8511       if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8512         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8513         break;
8514       }
8515     }
8516     // FIXME gcc accepts some relocatable values here too, but only in certain
8517     // memory models; it's complicated.
8518     return;
8519   }
8520   case 'i': {
8521     // Literal immediates are always ok.
8522     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8523       // Widen to 64 bits here to get it sign extended.
8524       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8525       break;
8526     }
8527
8528     // If we are in non-pic codegen mode, we allow the address of a global (with
8529     // an optional displacement) to be used with 'i'.
8530     GlobalAddressSDNode *GA = 0;
8531     int64_t Offset = 0;
8532
8533     // Match either (GA), (GA+C), (GA+C1+C2), etc.
8534     while (1) {
8535       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8536         Offset += GA->getOffset();
8537         break;
8538       } else if (Op.getOpcode() == ISD::ADD) {
8539         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8540           Offset += C->getZExtValue();
8541           Op = Op.getOperand(0);
8542           continue;
8543         }
8544       } else if (Op.getOpcode() == ISD::SUB) {
8545         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8546           Offset += -C->getZExtValue();
8547           Op = Op.getOperand(0);
8548           continue;
8549         }
8550       }
8551       
8552       // Otherwise, this isn't something we can handle, reject it.
8553       return;
8554     }
8555
8556     if (hasMemory)
8557       Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8558     else
8559       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8560                                       Offset);
8561     Result = Op;
8562     break;
8563   }
8564   }
8565
8566   if (Result.getNode()) {
8567     Ops.push_back(Result);
8568     return;
8569   }
8570   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8571                                                       Ops, DAG);
8572 }
8573
8574 std::vector<unsigned> X86TargetLowering::
8575 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8576                                   MVT VT) const {
8577   if (Constraint.size() == 1) {
8578     // FIXME: not handling fp-stack yet!
8579     switch (Constraint[0]) {      // GCC X86 Constraint Letters
8580     default: break;  // Unknown constraint letter
8581     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
8582     case 'Q':   // Q_REGS
8583       if (VT == MVT::i32)
8584         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8585       else if (VT == MVT::i16)
8586         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8587       else if (VT == MVT::i8)
8588         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8589       else if (VT == MVT::i64)
8590         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8591       break;
8592     }
8593   }
8594
8595   return std::vector<unsigned>();
8596 }
8597
8598 std::pair<unsigned, const TargetRegisterClass*>
8599 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8600                                                 MVT VT) const {
8601   // First, see if this is a constraint that directly corresponds to an LLVM
8602   // register class.
8603   if (Constraint.size() == 1) {
8604     // GCC Constraint Letters
8605     switch (Constraint[0]) {
8606     default: break;
8607     case 'r':   // GENERAL_REGS
8608     case 'R':   // LEGACY_REGS
8609     case 'l':   // INDEX_REGS
8610       if (VT == MVT::i8)
8611         return std::make_pair(0U, X86::GR8RegisterClass);
8612       if (VT == MVT::i16)
8613         return std::make_pair(0U, X86::GR16RegisterClass);
8614       if (VT == MVT::i32 || !Subtarget->is64Bit())
8615         return std::make_pair(0U, X86::GR32RegisterClass);
8616       return std::make_pair(0U, X86::GR64RegisterClass);
8617     case 'f':  // FP Stack registers.
8618       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8619       // value to the correct fpstack register class.
8620       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8621         return std::make_pair(0U, X86::RFP32RegisterClass);
8622       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8623         return std::make_pair(0U, X86::RFP64RegisterClass);
8624       return std::make_pair(0U, X86::RFP80RegisterClass);
8625     case 'y':   // MMX_REGS if MMX allowed.
8626       if (!Subtarget->hasMMX()) break;
8627       return std::make_pair(0U, X86::VR64RegisterClass);
8628     case 'Y':   // SSE_REGS if SSE2 allowed
8629       if (!Subtarget->hasSSE2()) break;
8630       // FALL THROUGH.
8631     case 'x':   // SSE_REGS if SSE1 allowed
8632       if (!Subtarget->hasSSE1()) break;
8633
8634       switch (VT.getSimpleVT()) {
8635       default: break;
8636       // Scalar SSE types.
8637       case MVT::f32:
8638       case MVT::i32:
8639         return std::make_pair(0U, X86::FR32RegisterClass);
8640       case MVT::f64:
8641       case MVT::i64:
8642         return std::make_pair(0U, X86::FR64RegisterClass);
8643       // Vector types.
8644       case MVT::v16i8:
8645       case MVT::v8i16:
8646       case MVT::v4i32:
8647       case MVT::v2i64:
8648       case MVT::v4f32:
8649       case MVT::v2f64:
8650         return std::make_pair(0U, X86::VR128RegisterClass);
8651       }
8652       break;
8653     }
8654   }
8655
8656   // Use the default implementation in TargetLowering to convert the register
8657   // constraint into a member of a register class.
8658   std::pair<unsigned, const TargetRegisterClass*> Res;
8659   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8660
8661   // Not found as a standard register?
8662   if (Res.second == 0) {
8663     // GCC calls "st(0)" just plain "st".
8664     if (StringsEqualNoCase("{st}", Constraint)) {
8665       Res.first = X86::ST0;
8666       Res.second = X86::RFP80RegisterClass;
8667     }
8668     // 'A' means EAX + EDX.
8669     if (Constraint == "A") {
8670       Res.first = X86::EAX;
8671       Res.second = X86::GRADRegisterClass;
8672     }
8673     return Res;
8674   }
8675
8676   // Otherwise, check to see if this is a register class of the wrong value
8677   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8678   // turn into {ax},{dx}.
8679   if (Res.second->hasType(VT))
8680     return Res;   // Correct type already, nothing to do.
8681
8682   // All of the single-register GCC register classes map their values onto
8683   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
8684   // really want an 8-bit or 32-bit register, map to the appropriate register
8685   // class and return the appropriate register.
8686   if (Res.second == X86::GR16RegisterClass) {
8687     if (VT == MVT::i8) {
8688       unsigned DestReg = 0;
8689       switch (Res.first) {
8690       default: break;
8691       case X86::AX: DestReg = X86::AL; break;
8692       case X86::DX: DestReg = X86::DL; break;
8693       case X86::CX: DestReg = X86::CL; break;
8694       case X86::BX: DestReg = X86::BL; break;
8695       }
8696       if (DestReg) {
8697         Res.first = DestReg;
8698         Res.second = X86::GR8RegisterClass;
8699       }
8700     } else if (VT == MVT::i32) {
8701       unsigned DestReg = 0;
8702       switch (Res.first) {
8703       default: break;
8704       case X86::AX: DestReg = X86::EAX; break;
8705       case X86::DX: DestReg = X86::EDX; break;
8706       case X86::CX: DestReg = X86::ECX; break;
8707       case X86::BX: DestReg = X86::EBX; break;
8708       case X86::SI: DestReg = X86::ESI; break;
8709       case X86::DI: DestReg = X86::EDI; break;
8710       case X86::BP: DestReg = X86::EBP; break;
8711       case X86::SP: DestReg = X86::ESP; break;
8712       }
8713       if (DestReg) {
8714         Res.first = DestReg;
8715         Res.second = X86::GR32RegisterClass;
8716       }
8717     } else if (VT == MVT::i64) {
8718       unsigned DestReg = 0;
8719       switch (Res.first) {
8720       default: break;
8721       case X86::AX: DestReg = X86::RAX; break;
8722       case X86::DX: DestReg = X86::RDX; break;
8723       case X86::CX: DestReg = X86::RCX; break;
8724       case X86::BX: DestReg = X86::RBX; break;
8725       case X86::SI: DestReg = X86::RSI; break;
8726       case X86::DI: DestReg = X86::RDI; break;
8727       case X86::BP: DestReg = X86::RBP; break;
8728       case X86::SP: DestReg = X86::RSP; break;
8729       }
8730       if (DestReg) {
8731         Res.first = DestReg;
8732         Res.second = X86::GR64RegisterClass;
8733       }
8734     }
8735   } else if (Res.second == X86::FR32RegisterClass ||
8736              Res.second == X86::FR64RegisterClass ||
8737              Res.second == X86::VR128RegisterClass) {
8738     // Handle references to XMM physical registers that got mapped into the
8739     // wrong class.  This can happen with constraints like {xmm0} where the
8740     // target independent register mapper will just pick the first match it can
8741     // find, ignoring the required type.
8742     if (VT == MVT::f32)
8743       Res.second = X86::FR32RegisterClass;
8744     else if (VT == MVT::f64)
8745       Res.second = X86::FR64RegisterClass;
8746     else if (X86::VR128RegisterClass->hasType(VT))
8747       Res.second = X86::VR128RegisterClass;
8748   }
8749
8750   return Res;
8751 }
8752
8753 //===----------------------------------------------------------------------===//
8754 //                           X86 Widen vector type
8755 //===----------------------------------------------------------------------===//
8756
8757 /// getWidenVectorType: given a vector type, returns the type to widen
8758 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8759 /// If there is no vector type that we want to widen to, returns MVT::Other
8760 /// When and where to widen is target dependent based on the cost of
8761 /// scalarizing vs using the wider vector type.
8762
8763 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8764   assert(VT.isVector());
8765   if (isTypeLegal(VT))
8766     return VT;
8767
8768   // TODO: In computeRegisterProperty, we can compute the list of legal vector
8769   //       type based on element type.  This would speed up our search (though
8770   //       it may not be worth it since the size of the list is relatively
8771   //       small).
8772   MVT EltVT = VT.getVectorElementType();
8773   unsigned NElts = VT.getVectorNumElements();
8774
8775   // On X86, it make sense to widen any vector wider than 1
8776   if (NElts <= 1)
8777     return MVT::Other;
8778
8779   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8780        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8781     MVT SVT = (MVT::SimpleValueType)nVT;
8782
8783     if (isTypeLegal(SVT) &&
8784         SVT.getVectorElementType() == EltVT &&
8785         SVT.getVectorNumElements() > NElts)
8786       return SVT;
8787   }
8788   return MVT::Other;
8789 }