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