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