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