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