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