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