reverting 116056: win64_params.ll may need to be conditionalized?
[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 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 using namespace llvm;
54 using namespace dwarf;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 static cl::opt<bool>
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60
61 // Forward declarations.
62 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63                        SDValue V2);
64
65 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
66   
67   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
68   
69   if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
70     if (is64Bit) return new X8664_MachoTargetObjectFile();
71     return new TargetLoweringObjectFileMachO();
72   } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
73     if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
74     return new X8632_ELFTargetObjectFile(TM);
75   } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
76     return new TargetLoweringObjectFileCOFF();
77   }  
78   llvm_unreachable("unknown subtarget type");
79 }
80
81 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
82   : TargetLowering(TM, createTLOF(TM)) {
83   Subtarget = &TM.getSubtarget<X86Subtarget>();
84   X86ScalarSSEf64 = Subtarget->hasSSE2();
85   X86ScalarSSEf32 = Subtarget->hasSSE1();
86   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
87
88   RegInfo = TM.getRegisterInfo();
89   TD = getTargetData();
90
91   // Set up the TargetLowering object.
92
93   // X86 is weird, it always uses i8 for shift amounts and setcc results.
94   setShiftAmountType(MVT::i8);
95   setBooleanContents(ZeroOrOneBooleanContent);
96   setSchedulingPreference(Sched::RegPressure);
97   setStackPointerRegisterToSaveRestore(X86StackPtr);
98
99   if (Subtarget->isTargetDarwin()) {
100     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
101     setUseUnderscoreSetJmp(false);
102     setUseUnderscoreLongJmp(false);
103   } else if (Subtarget->isTargetMingw()) {
104     // MS runtime is weird: it exports _setjmp, but longjmp!
105     setUseUnderscoreSetJmp(true);
106     setUseUnderscoreLongJmp(false);
107   } else {
108     setUseUnderscoreSetJmp(true);
109     setUseUnderscoreLongJmp(true);
110   }
111
112   // Set up the register classes.
113   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
114   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
115   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
116   if (Subtarget->is64Bit())
117     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
118
119   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
120
121   // We don't accept any truncstore of integer registers.
122   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
123   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
124   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
125   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
126   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
127   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
128
129   // SETOEQ and SETUNE require checking two conditions.
130   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
131   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
132   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
133   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
134   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
135   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
136
137   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
138   // operation.
139   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
140   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
141   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
142
143   if (Subtarget->is64Bit()) {
144     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
145     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
146   } else if (!UseSoftFloat) {
147     // We have an algorithm for SSE2->double, and we turn this into a
148     // 64-bit FILD followed by conditional FADD for other targets.
149     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
150     // We have an algorithm for SSE2, and we turn this into a 64-bit
151     // FILD for other targets.
152     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
153   }
154
155   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
156   // this operation.
157   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
158   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
159
160   if (!UseSoftFloat) {
161     // SSE has no i16 to fp conversion, only i32
162     if (X86ScalarSSEf32) {
163       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
164       // f32 and f64 cases are Legal, f80 case is not
165       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
166     } else {
167       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
168       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
169     }
170   } else {
171     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
172     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
173   }
174
175   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
176   // are Legal, f80 is custom lowered.
177   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
178   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
179
180   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
181   // this operation.
182   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
183   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
184
185   if (X86ScalarSSEf32) {
186     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
187     // f32 and f64 cases are Legal, f80 case is not
188     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
189   } else {
190     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
191     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
192   }
193
194   // Handle FP_TO_UINT by promoting the destination to a larger signed
195   // conversion.
196   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
197   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
198   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
199
200   if (Subtarget->is64Bit()) {
201     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
202     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
203   } else if (!UseSoftFloat) {
204     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
205       // Expand FP_TO_UINT into a select.
206       // FIXME: We would like to use a Custom expander here eventually to do
207       // the optimal thing for SSE vs. the default expansion in the legalizer.
208       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
209     else
210       // With SSE3 we can use fisttpll to convert to a signed i64; without
211       // SSE, we're stuck with a fistpll.
212       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
213   }
214
215   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
216   if (!X86ScalarSSEf64) { 
217     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
218     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
219     if (Subtarget->is64Bit()) {
220       setOperationAction(ISD::BIT_CONVERT    , MVT::f64  , Expand);
221       // Without SSE, i64->f64 goes through memory.
222       setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Expand);
223     }
224   }
225
226   // Scalar integer divide and remainder are lowered to use operations that
227   // produce two results, to match the available instructions. This exposes
228   // the two-result form to trivial CSE, which is able to combine x/y and x%y
229   // into a single instruction.
230   //
231   // Scalar integer multiply-high is also lowered to use two-result
232   // operations, to match the available instructions. However, plain multiply
233   // (low) operations are left as Legal, as there are single-result
234   // instructions for this in x86. Using the two-result multiply instructions
235   // when both high and low results are needed must be arranged by dagcombine.
236   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
237   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
238   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
239   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
240   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
241   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
242   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
243   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
244   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
245   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
246   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
247   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
248   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
249   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
250   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
251   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
252   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
253   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
254   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
255   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
256   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
257   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
258   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
259   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
260
261   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
262   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
263   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
264   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
265   if (Subtarget->is64Bit())
266     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
267   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
268   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
269   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
270   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
271   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
272   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
273   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
274   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
275
276   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
277   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
278   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
279   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
280   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
281   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
282   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
283   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
284   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
285   if (Subtarget->is64Bit()) {
286     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
287     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
288     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
289   }
290
291   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
292   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
293
294   // These should be promoted to a larger select which is supported.
295   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
296   // X86 wants to expand cmov itself.
297   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
298   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
299   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
300   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
301   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
302   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
303   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
304   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
305   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
306   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
307   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
308   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
309   if (Subtarget->is64Bit()) {
310     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
311     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
312   }
313   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
314
315   // Darwin ABI issue.
316   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
317   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
318   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
319   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
320   if (Subtarget->is64Bit())
321     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
322   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
323   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
324   if (Subtarget->is64Bit()) {
325     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
326     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
327     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
328     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
329     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
330   }
331   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
332   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
333   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
334   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
335   if (Subtarget->is64Bit()) {
336     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
337     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
338     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
339   }
340
341   if (Subtarget->hasSSE1())
342     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
343
344   // We may not have a libcall for MEMBARRIER so we should lower this.
345   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
346   
347   // On X86 and X86-64, atomic operations are lowered to locked instructions.
348   // Locked instructions, in turn, have implicit fence semantics (all memory
349   // operations are flushed before issuing the locked instruction, and they
350   // are not buffered), so we can fold away the common pattern of
351   // fence-atomic-fence.
352   setShouldFoldAtomicFences(true);
353
354   // Expand certain atomics
355   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
356   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
358   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
359
360   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
361   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
362   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
363   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
364
365   if (!Subtarget->is64Bit()) {
366     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
367     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
368     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
369     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
370     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
371     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
372     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
373   }
374
375   // FIXME - use subtarget debug flags
376   if (!Subtarget->isTargetDarwin() &&
377       !Subtarget->isTargetELF() &&
378       !Subtarget->isTargetCygMing()) {
379     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
380   }
381
382   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
383   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
384   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
385   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
386   if (Subtarget->is64Bit()) {
387     setExceptionPointerRegister(X86::RAX);
388     setExceptionSelectorRegister(X86::RDX);
389   } else {
390     setExceptionPointerRegister(X86::EAX);
391     setExceptionSelectorRegister(X86::EDX);
392   }
393   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
394   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
395
396   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
397
398   setOperationAction(ISD::TRAP, MVT::Other, Legal);
399
400   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
401   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
402   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
403   if (Subtarget->is64Bit()) {
404     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
405     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
406   } else {
407     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
408     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
409   }
410
411   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
412   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
413   if (Subtarget->is64Bit())
414     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
415   if (Subtarget->isTargetCygMing())
416     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
417   else
418     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
419
420   if (!UseSoftFloat && X86ScalarSSEf64) {
421     // f32 and f64 use SSE.
422     // Set up the FP register classes.
423     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
424     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
425
426     // Use ANDPD to simulate FABS.
427     setOperationAction(ISD::FABS , MVT::f64, Custom);
428     setOperationAction(ISD::FABS , MVT::f32, Custom);
429
430     // Use XORP to simulate FNEG.
431     setOperationAction(ISD::FNEG , MVT::f64, Custom);
432     setOperationAction(ISD::FNEG , MVT::f32, Custom);
433
434     // Use ANDPD and ORPD to simulate FCOPYSIGN.
435     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
436     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
437
438     // We don't support sin/cos/fmod
439     setOperationAction(ISD::FSIN , MVT::f64, Expand);
440     setOperationAction(ISD::FCOS , MVT::f64, Expand);
441     setOperationAction(ISD::FSIN , MVT::f32, Expand);
442     setOperationAction(ISD::FCOS , MVT::f32, Expand);
443
444     // Expand FP immediates into loads from the stack, except for the special
445     // cases we handle.
446     addLegalFPImmediate(APFloat(+0.0)); // xorpd
447     addLegalFPImmediate(APFloat(+0.0f)); // xorps
448   } else if (!UseSoftFloat && X86ScalarSSEf32) {
449     // Use SSE for f32, x87 for f64.
450     // Set up the FP register classes.
451     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
452     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
453
454     // Use ANDPS to simulate FABS.
455     setOperationAction(ISD::FABS , MVT::f32, Custom);
456
457     // Use XORP to simulate FNEG.
458     setOperationAction(ISD::FNEG , MVT::f32, Custom);
459
460     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
461
462     // Use ANDPS and ORPS to simulate FCOPYSIGN.
463     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
464     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
465
466     // We don't support sin/cos/fmod
467     setOperationAction(ISD::FSIN , MVT::f32, Expand);
468     setOperationAction(ISD::FCOS , MVT::f32, Expand);
469
470     // Special cases we handle for FP constants.
471     addLegalFPImmediate(APFloat(+0.0f)); // xorps
472     addLegalFPImmediate(APFloat(+0.0)); // FLD0
473     addLegalFPImmediate(APFloat(+1.0)); // FLD1
474     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
475     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
476
477     if (!UnsafeFPMath) {
478       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
479       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
480     }
481   } else if (!UseSoftFloat) {
482     // f32 and f64 in x87.
483     // Set up the FP register classes.
484     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
485     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
486
487     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
488     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
489     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
490     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
491
492     if (!UnsafeFPMath) {
493       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
494       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
495     }
496     addLegalFPImmediate(APFloat(+0.0)); // FLD0
497     addLegalFPImmediate(APFloat(+1.0)); // FLD1
498     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
499     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
500     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
501     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
502     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
503     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
504   }
505
506   // Long double always uses X87.
507   if (!UseSoftFloat) {
508     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
509     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
510     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
511     {
512       bool ignored;
513       APFloat TmpFlt(+0.0);
514       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
515                      &ignored);
516       addLegalFPImmediate(TmpFlt);  // FLD0
517       TmpFlt.changeSign();
518       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
519       APFloat TmpFlt2(+1.0);
520       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
521                       &ignored);
522       addLegalFPImmediate(TmpFlt2);  // FLD1
523       TmpFlt2.changeSign();
524       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
525     }
526
527     if (!UnsafeFPMath) {
528       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
529       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
530     }
531   }
532
533   // Always use a library call for pow.
534   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
535   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
536   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
537
538   setOperationAction(ISD::FLOG, MVT::f80, Expand);
539   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
540   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
541   setOperationAction(ISD::FEXP, MVT::f80, Expand);
542   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
543
544   // First set operation action for all vector types to either promote
545   // (for widening) or expand (for scalarization). Then we will selectively
546   // turn on ones that can be effectively codegen'd.
547   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
548        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
549     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
564     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
565     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
598     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
602     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
603          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
604       setTruncStoreAction((MVT::SimpleValueType)VT,
605                           (MVT::SimpleValueType)InnerVT, Expand);
606     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
607     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
608     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
609   }
610
611   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
612   // with -msoft-float, disable use of MMX as well.
613   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
614     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass, false);
615     // No operations on x86mmx supported, everything uses intrinsics.
616   }
617
618   // MMX-sized vectors (other than x86mmx) are expected to be expanded
619   // into smaller operations.
620   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
621   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
622   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
623   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
624   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
625   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
626   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
627   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
628   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
629   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
630   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
631   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
632   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
633   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
634   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
635   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
636   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
637   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
638   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
639   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
640   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
641   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
642   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
643   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
644   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
645   setOperationAction(ISD::BIT_CONVERT,        MVT::v8i8,  Expand);
646   setOperationAction(ISD::BIT_CONVERT,        MVT::v4i16, Expand);
647   setOperationAction(ISD::BIT_CONVERT,        MVT::v2i32, Expand);
648   setOperationAction(ISD::BIT_CONVERT,        MVT::v1i64, Expand);
649
650   if (!UseSoftFloat && Subtarget->hasSSE1()) {
651     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
652
653     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
654     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
655     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
656     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
657     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
658     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
659     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
660     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
661     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
662     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
663     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
664     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
665   }
666
667   if (!UseSoftFloat && Subtarget->hasSSE2()) {
668     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
669
670     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
671     // registers cannot be used even for integer operations.
672     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
673     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
674     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
675     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
676
677     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
678     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
679     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
680     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
681     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
682     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
683     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
684     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
685     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
686     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
687     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
688     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
689     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
690     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
691     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
692     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
693
694     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
695     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
696     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
697     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
698
699     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
700     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
701     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
702     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
703     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
704
705     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
706     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
707     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
708     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
709     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
710
711     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
712     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
713       EVT VT = (MVT::SimpleValueType)i;
714       // Do not attempt to custom lower non-power-of-2 vectors
715       if (!isPowerOf2_32(VT.getVectorNumElements()))
716         continue;
717       // Do not attempt to custom lower non-128-bit vectors
718       if (!VT.is128BitVector())
719         continue;
720       setOperationAction(ISD::BUILD_VECTOR,
721                          VT.getSimpleVT().SimpleTy, Custom);
722       setOperationAction(ISD::VECTOR_SHUFFLE,
723                          VT.getSimpleVT().SimpleTy, Custom);
724       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
725                          VT.getSimpleVT().SimpleTy, Custom);
726     }
727
728     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
729     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
730     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
731     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
732     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
733     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
734
735     if (Subtarget->is64Bit()) {
736       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
737       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
738     }
739
740     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
741     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
742       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
743       EVT VT = SVT;
744
745       // Do not attempt to promote non-128-bit vectors
746       if (!VT.is128BitVector())
747         continue;
748       
749       setOperationAction(ISD::AND,    SVT, Promote);
750       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
751       setOperationAction(ISD::OR,     SVT, Promote);
752       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
753       setOperationAction(ISD::XOR,    SVT, Promote);
754       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
755       setOperationAction(ISD::LOAD,   SVT, Promote);
756       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
757       setOperationAction(ISD::SELECT, SVT, Promote);
758       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
759     }
760
761     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
762
763     // Custom lower v2i64 and v2f64 selects.
764     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
765     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
766     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
767     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
768
769     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
770     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
771   }
772
773   if (Subtarget->hasSSE41()) {
774     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
775     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
776     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
777     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
778     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
779     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
780     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
781     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
782     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
783     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
784
785     // FIXME: Do we need to handle scalar-to-vector here?
786     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
787
788     // Can turn SHL into an integer multiply.
789     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
790     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
791
792     // i8 and i16 vectors are custom , because the source register and source
793     // source memory operand types are not the same width.  f32 vectors are
794     // custom since the immediate controlling the insert encodes additional
795     // information.
796     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
797     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
798     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
799     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
800
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
802     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
803     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
804     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
805
806     if (Subtarget->is64Bit()) {
807       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
808       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
809     }
810   }
811
812   if (Subtarget->hasSSE42()) {
813     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
814   }
815
816   if (!UseSoftFloat && Subtarget->hasAVX()) {
817     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
818     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
819     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
820     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
821     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
822
823     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
824     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
825     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
826     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
827     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
828     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
829     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
830     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
831     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
832     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
833     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
834     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
835     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
836     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
837     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
838
839     // Operations to consider commented out -v16i16 v32i8
840     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
841     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
842     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
843     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
844     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
845     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
846     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
847     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
848     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
849     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
850     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
851     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
852     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
853     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
854
855     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
856     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
857     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
858     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
859
860     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
861     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
862     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
863     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
864     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
865
866     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
868     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
871     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
872
873 #if 0
874     // Not sure we want to do this since there are no 256-bit integer
875     // operations in AVX
876
877     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878     // This includes 256-bit vectors
879     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
880       EVT VT = (MVT::SimpleValueType)i;
881
882       // Do not attempt to custom lower non-power-of-2 vectors
883       if (!isPowerOf2_32(VT.getVectorNumElements()))
884         continue;
885
886       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
887       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
888       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
889     }
890
891     if (Subtarget->is64Bit()) {
892       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
893       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
894     }
895 #endif
896
897 #if 0
898     // Not sure we want to do this since there are no 256-bit integer
899     // operations in AVX
900
901     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
902     // Including 256-bit vectors
903     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
904       EVT VT = (MVT::SimpleValueType)i;
905
906       if (!VT.is256BitVector()) {
907         continue;
908       }
909       setOperationAction(ISD::AND,    VT, Promote);
910       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
911       setOperationAction(ISD::OR,     VT, Promote);
912       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
913       setOperationAction(ISD::XOR,    VT, Promote);
914       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
915       setOperationAction(ISD::LOAD,   VT, Promote);
916       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
917       setOperationAction(ISD::SELECT, VT, Promote);
918       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
919     }
920
921     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
922 #endif
923   }
924
925   // We want to custom lower some of our intrinsics.
926   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
927
928   // Add/Sub/Mul with overflow operations are custom lowered.
929   setOperationAction(ISD::SADDO, MVT::i32, Custom);
930   setOperationAction(ISD::UADDO, MVT::i32, Custom);
931   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
932   setOperationAction(ISD::USUBO, MVT::i32, Custom);
933   setOperationAction(ISD::SMULO, MVT::i32, Custom);
934
935   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
936   // handle type legalization for these operations here.
937   //
938   // FIXME: We really should do custom legalization for addition and
939   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
940   // than generic legalization for 64-bit multiplication-with-overflow, though.
941   if (Subtarget->is64Bit()) {
942     setOperationAction(ISD::SADDO, MVT::i64, Custom);
943     setOperationAction(ISD::UADDO, MVT::i64, Custom);
944     setOperationAction(ISD::SSUBO, MVT::i64, Custom);
945     setOperationAction(ISD::USUBO, MVT::i64, Custom);
946     setOperationAction(ISD::SMULO, MVT::i64, Custom);
947   }
948
949   if (!Subtarget->is64Bit()) {
950     // These libcalls are not available in 32-bit.
951     setLibcallName(RTLIB::SHL_I128, 0);
952     setLibcallName(RTLIB::SRL_I128, 0);
953     setLibcallName(RTLIB::SRA_I128, 0);
954   }
955
956   // We have target-specific dag combine patterns for the following nodes:
957   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
958   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
959   setTargetDAGCombine(ISD::BUILD_VECTOR);
960   setTargetDAGCombine(ISD::SELECT);
961   setTargetDAGCombine(ISD::SHL);
962   setTargetDAGCombine(ISD::SRA);
963   setTargetDAGCombine(ISD::SRL);
964   setTargetDAGCombine(ISD::OR);
965   setTargetDAGCombine(ISD::STORE);
966   setTargetDAGCombine(ISD::ZERO_EXTEND);
967   if (Subtarget->is64Bit())
968     setTargetDAGCombine(ISD::MUL);
969
970   computeRegisterProperties();
971
972   // FIXME: These should be based on subtarget info. Plus, the values should
973   // be smaller when we are in optimizing for size mode.
974   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
975   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
976   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
977   setPrefLoopAlignment(16);
978   benefitFromCodePlacementOpt = true;
979 }
980
981
982 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
983   return MVT::i8;
984 }
985
986
987 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
988 /// the desired ByVal argument alignment.
989 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
990   if (MaxAlign == 16)
991     return;
992   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
993     if (VTy->getBitWidth() == 128)
994       MaxAlign = 16;
995   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
996     unsigned EltAlign = 0;
997     getMaxByValAlign(ATy->getElementType(), EltAlign);
998     if (EltAlign > MaxAlign)
999       MaxAlign = EltAlign;
1000   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1001     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1002       unsigned EltAlign = 0;
1003       getMaxByValAlign(STy->getElementType(i), EltAlign);
1004       if (EltAlign > MaxAlign)
1005         MaxAlign = EltAlign;
1006       if (MaxAlign == 16)
1007         break;
1008     }
1009   }
1010   return;
1011 }
1012
1013 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1014 /// function arguments in the caller parameter area. For X86, aggregates
1015 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1016 /// are at 4-byte boundaries.
1017 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1018   if (Subtarget->is64Bit()) {
1019     // Max of 8 and alignment of type.
1020     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1021     if (TyAlign > 8)
1022       return TyAlign;
1023     return 8;
1024   }
1025
1026   unsigned Align = 4;
1027   if (Subtarget->hasSSE1())
1028     getMaxByValAlign(Ty, Align);
1029   return Align;
1030 }
1031
1032 /// getOptimalMemOpType - Returns the target specific optimal type for load
1033 /// and store operations as a result of memset, memcpy, and memmove
1034 /// lowering. If DstAlign is zero that means it's safe to destination
1035 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1036 /// means there isn't a need to check it against alignment requirement,
1037 /// probably because the source does not need to be loaded. If
1038 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1039 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1040 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1041 /// constant so it does not need to be loaded.
1042 /// It returns EVT::Other if the type should be determined using generic
1043 /// target-independent logic.
1044 EVT
1045 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1046                                        unsigned DstAlign, unsigned SrcAlign,
1047                                        bool NonScalarIntSafe,
1048                                        bool MemcpyStrSrc,
1049                                        MachineFunction &MF) const {
1050   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1051   // linux.  This is because the stack realignment code can't handle certain
1052   // cases like PR2962.  This should be removed when PR2962 is fixed.
1053   const Function *F = MF.getFunction();
1054   if (NonScalarIntSafe &&
1055       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1056     if (Size >= 16 &&
1057         (Subtarget->isUnalignedMemAccessFast() ||
1058          ((DstAlign == 0 || DstAlign >= 16) &&
1059           (SrcAlign == 0 || SrcAlign >= 16))) &&
1060         Subtarget->getStackAlignment() >= 16) {
1061       if (Subtarget->hasSSE2())
1062         return MVT::v4i32;
1063       if (Subtarget->hasSSE1())
1064         return MVT::v4f32;
1065     } else if (!MemcpyStrSrc && Size >= 8 &&
1066                !Subtarget->is64Bit() &&
1067                Subtarget->getStackAlignment() >= 8 &&
1068                Subtarget->hasSSE2()) {
1069       // Do not use f64 to lower memcpy if source is string constant. It's
1070       // better to use i32 to avoid the loads.
1071       return MVT::f64;
1072     }
1073   }
1074   if (Subtarget->is64Bit() && Size >= 8)
1075     return MVT::i64;
1076   return MVT::i32;
1077 }
1078
1079 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1080 /// current function.  The returned value is a member of the
1081 /// MachineJumpTableInfo::JTEntryKind enum.
1082 unsigned X86TargetLowering::getJumpTableEncoding() const {
1083   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1084   // symbol.
1085   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1086       Subtarget->isPICStyleGOT())
1087     return MachineJumpTableInfo::EK_Custom32;
1088   
1089   // Otherwise, use the normal jump table encoding heuristics.
1090   return TargetLowering::getJumpTableEncoding();
1091 }
1092
1093 /// getPICBaseSymbol - Return the X86-32 PIC base.
1094 MCSymbol *
1095 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1096                                     MCContext &Ctx) const {
1097   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1098   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1099                                Twine(MF->getFunctionNumber())+"$pb");
1100 }
1101
1102
1103 const MCExpr *
1104 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1105                                              const MachineBasicBlock *MBB,
1106                                              unsigned uid,MCContext &Ctx) const{
1107   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1108          Subtarget->isPICStyleGOT());
1109   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1110   // entries.
1111   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1112                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1113 }
1114
1115 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1116 /// jumptable.
1117 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1118                                                     SelectionDAG &DAG) const {
1119   if (!Subtarget->is64Bit())
1120     // This doesn't have DebugLoc associated with it, but is not really the
1121     // same as a Register.
1122     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1123   return Table;
1124 }
1125
1126 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1127 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1128 /// MCExpr.
1129 const MCExpr *X86TargetLowering::
1130 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1131                              MCContext &Ctx) const {
1132   // X86-64 uses RIP relative addressing based on the jump table label.
1133   if (Subtarget->isPICStyleRIPRel())
1134     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1135
1136   // Otherwise, the reference is relative to the PIC base.
1137   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1138 }
1139
1140 /// getFunctionAlignment - Return the Log2 alignment of this function.
1141 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1142   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1143 }
1144
1145 std::pair<const TargetRegisterClass*, uint8_t>
1146 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1147   const TargetRegisterClass *RRC = 0;
1148   uint8_t Cost = 1;
1149   switch (VT.getSimpleVT().SimpleTy) {
1150   default:
1151     return TargetLowering::findRepresentativeClass(VT);
1152   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1153     RRC = (Subtarget->is64Bit()
1154            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1155     break;
1156   case MVT::x86mmx:
1157     RRC = X86::VR64RegisterClass;
1158     break;
1159   case MVT::f32: case MVT::f64:
1160   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1161   case MVT::v4f32: case MVT::v2f64:
1162   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1163   case MVT::v4f64:
1164     RRC = X86::VR128RegisterClass;
1165     break;
1166   }
1167   return std::make_pair(RRC, Cost);
1168 }
1169
1170 unsigned
1171 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1172                                        MachineFunction &MF) const {
1173   unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1174   switch (RC->getID()) {
1175   default:
1176     return 0;
1177   case X86::GR32RegClassID:
1178     return 4 - FPDiff;
1179   case X86::GR64RegClassID:
1180     return 8 - FPDiff;
1181   case X86::VR128RegClassID:
1182     return Subtarget->is64Bit() ? 10 : 4;
1183   case X86::VR64RegClassID:
1184     return 4;
1185   }
1186 }
1187
1188 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1189                                                unsigned &Offset) const {
1190   if (!Subtarget->isTargetLinux())
1191     return false;
1192
1193   if (Subtarget->is64Bit()) {
1194     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1195     Offset = 0x28;
1196     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1197       AddressSpace = 256;
1198     else
1199       AddressSpace = 257;
1200   } else {
1201     // %gs:0x14 on i386
1202     Offset = 0x14;
1203     AddressSpace = 256;
1204   }
1205   return true;
1206 }
1207
1208
1209 //===----------------------------------------------------------------------===//
1210 //               Return Value Calling Convention Implementation
1211 //===----------------------------------------------------------------------===//
1212
1213 #include "X86GenCallingConv.inc"
1214
1215 bool 
1216 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1217                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1218                         LLVMContext &Context) const {
1219   SmallVector<CCValAssign, 16> RVLocs;
1220   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1221                  RVLocs, Context);
1222   return CCInfo.CheckReturn(Outs, RetCC_X86);
1223 }
1224
1225 SDValue
1226 X86TargetLowering::LowerReturn(SDValue Chain,
1227                                CallingConv::ID CallConv, bool isVarArg,
1228                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1229                                const SmallVectorImpl<SDValue> &OutVals,
1230                                DebugLoc dl, SelectionDAG &DAG) const {
1231   MachineFunction &MF = DAG.getMachineFunction();
1232   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1233
1234   SmallVector<CCValAssign, 16> RVLocs;
1235   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1236                  RVLocs, *DAG.getContext());
1237   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1238
1239   // Add the regs to the liveout set for the function.
1240   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1241   for (unsigned i = 0; i != RVLocs.size(); ++i)
1242     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1243       MRI.addLiveOut(RVLocs[i].getLocReg());
1244
1245   SDValue Flag;
1246
1247   SmallVector<SDValue, 6> RetOps;
1248   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1249   // Operand #1 = Bytes To Pop
1250   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1251                    MVT::i16));
1252
1253   // Copy the result values into the output registers.
1254   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1255     CCValAssign &VA = RVLocs[i];
1256     assert(VA.isRegLoc() && "Can only return in registers!");
1257     SDValue ValToCopy = OutVals[i];
1258     EVT ValVT = ValToCopy.getValueType();
1259
1260     // If this is x86-64, and we disabled SSE, we can't return FP values,
1261     // or SSE or MMX vectors.
1262     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1263          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1264           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1265       report_fatal_error("SSE register return with SSE disabled");
1266     }
1267     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1268     // llvm-gcc has never done it right and no one has noticed, so this
1269     // should be OK for now.
1270     if (ValVT == MVT::f64 &&
1271         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1272       report_fatal_error("SSE2 register return with SSE2 disabled");
1273
1274     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1275     // the RET instruction and handled by the FP Stackifier.
1276     if (VA.getLocReg() == X86::ST0 ||
1277         VA.getLocReg() == X86::ST1) {
1278       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1279       // change the value to the FP stack register class.
1280       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1281         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1282       RetOps.push_back(ValToCopy);
1283       // Don't emit a copytoreg.
1284       continue;
1285     }
1286
1287     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1288     // which is returned in RAX / RDX.
1289     if (Subtarget->is64Bit()) {
1290       if (ValVT == MVT::x86mmx) {
1291         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1292           ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1293           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1294                                   ValToCopy);
1295           // If we don't have SSE2 available, convert to v4f32 so the generated
1296           // register is legal.
1297           if (!Subtarget->hasSSE2())
1298             ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32,ValToCopy);
1299         }
1300       }
1301     }
1302     
1303     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1304     Flag = Chain.getValue(1);
1305   }
1306
1307   // The x86-64 ABI for returning structs by value requires that we copy
1308   // the sret argument into %rax for the return. We saved the argument into
1309   // a virtual register in the entry block, so now we copy the value out
1310   // and into %rax.
1311   if (Subtarget->is64Bit() &&
1312       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1313     MachineFunction &MF = DAG.getMachineFunction();
1314     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1315     unsigned Reg = FuncInfo->getSRetReturnReg();
1316     assert(Reg && 
1317            "SRetReturnReg should have been set in LowerFormalArguments().");
1318     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1319
1320     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1321     Flag = Chain.getValue(1);
1322
1323     // RAX now acts like a return value.
1324     MRI.addLiveOut(X86::RAX);
1325   }
1326
1327   RetOps[0] = Chain;  // Update chain.
1328
1329   // Add the flag if we have it.
1330   if (Flag.getNode())
1331     RetOps.push_back(Flag);
1332
1333   return DAG.getNode(X86ISD::RET_FLAG, dl,
1334                      MVT::Other, &RetOps[0], RetOps.size());
1335 }
1336
1337 /// LowerCallResult - Lower the result values of a call into the
1338 /// appropriate copies out of appropriate physical registers.
1339 ///
1340 SDValue
1341 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1342                                    CallingConv::ID CallConv, bool isVarArg,
1343                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1344                                    DebugLoc dl, SelectionDAG &DAG,
1345                                    SmallVectorImpl<SDValue> &InVals) const {
1346
1347   // Assign locations to each value returned by this call.
1348   SmallVector<CCValAssign, 16> RVLocs;
1349   bool Is64Bit = Subtarget->is64Bit();
1350   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1351                  RVLocs, *DAG.getContext());
1352   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1353
1354   // Copy all of the result registers out of their specified physreg.
1355   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356     CCValAssign &VA = RVLocs[i];
1357     EVT CopyVT = VA.getValVT();
1358
1359     // If this is x86-64, and we disabled SSE, we can't return FP values
1360     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1361         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1362       report_fatal_error("SSE register return with SSE disabled");
1363     }
1364
1365     SDValue Val;
1366
1367     // If this is a call to a function that returns an fp value on the floating
1368     // point stack, we must guarantee the the value is popped from the stack, so
1369     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1370     // if the return value is not used. We use the FpGET_ST0 instructions
1371     // instead.
1372     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1373       // If we prefer to use the value in xmm registers, copy it out as f80 and
1374       // use a truncate to move it from fp stack reg to xmm reg.
1375       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1376       bool isST0 = VA.getLocReg() == X86::ST0;
1377       unsigned Opc = 0;
1378       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1379       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1380       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1381       SDValue Ops[] = { Chain, InFlag };
1382       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1383                                          Ops, 2), 1);
1384       Val = Chain.getValue(0);
1385
1386       // Round the f80 to the right size, which also moves it to the appropriate
1387       // xmm register.
1388       if (CopyVT != VA.getValVT())
1389         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1390                           // This truncation won't change the value.
1391                           DAG.getIntPtrConstant(1));
1392     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1393       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1394       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1395         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1396                                    MVT::v2i64, InFlag).getValue(1);
1397         Val = Chain.getValue(0);
1398         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1399                           Val, DAG.getConstant(0, MVT::i64));
1400       } else {
1401         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1402                                    MVT::i64, InFlag).getValue(1);
1403         Val = Chain.getValue(0);
1404       }
1405       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1406     } else {
1407       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1408                                  CopyVT, InFlag).getValue(1);
1409       Val = Chain.getValue(0);
1410     }
1411     InFlag = Chain.getValue(2);
1412     InVals.push_back(Val);
1413   }
1414
1415   return Chain;
1416 }
1417
1418
1419 //===----------------------------------------------------------------------===//
1420 //                C & StdCall & Fast Calling Convention implementation
1421 //===----------------------------------------------------------------------===//
1422 //  StdCall calling convention seems to be standard for many Windows' API
1423 //  routines and around. It differs from C calling convention just a little:
1424 //  callee should clean up the stack, not caller. Symbols should be also
1425 //  decorated in some fancy way :) It doesn't support any vector arguments.
1426 //  For info on fast calling convention see Fast Calling Convention (tail call)
1427 //  implementation LowerX86_32FastCCCallTo.
1428
1429 /// CallIsStructReturn - Determines whether a call uses struct return
1430 /// semantics.
1431 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1432   if (Outs.empty())
1433     return false;
1434
1435   return Outs[0].Flags.isSRet();
1436 }
1437
1438 /// ArgsAreStructReturn - Determines whether a function uses struct
1439 /// return semantics.
1440 static bool
1441 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1442   if (Ins.empty())
1443     return false;
1444
1445   return Ins[0].Flags.isSRet();
1446 }
1447
1448 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1449 /// given CallingConvention value.
1450 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1451   if (Subtarget->is64Bit()) {
1452     if (CC == CallingConv::GHC)
1453       return CC_X86_64_GHC;
1454     else if (Subtarget->isTargetWin64())
1455       return CC_X86_Win64_C;
1456     else
1457       return CC_X86_64_C;
1458   }
1459
1460   if (CC == CallingConv::X86_FastCall)
1461     return CC_X86_32_FastCall;
1462   else if (CC == CallingConv::X86_ThisCall)
1463     return CC_X86_32_ThisCall;
1464   else if (CC == CallingConv::Fast)
1465     return CC_X86_32_FastCC;
1466   else if (CC == CallingConv::GHC)
1467     return CC_X86_32_GHC;
1468   else
1469     return CC_X86_32_C;
1470 }
1471
1472 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1473 /// by "Src" to address "Dst" with size and alignment information specified by
1474 /// the specific parameter attribute. The copy will be passed as a byval
1475 /// function parameter.
1476 static SDValue
1477 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1478                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1479                           DebugLoc dl) {
1480   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1481   
1482   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1483                        /*isVolatile*/false, /*AlwaysInline=*/true,
1484                        MachinePointerInfo(), MachinePointerInfo());
1485 }
1486
1487 /// IsTailCallConvention - Return true if the calling convention is one that
1488 /// supports tail call optimization.
1489 static bool IsTailCallConvention(CallingConv::ID CC) {
1490   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1491 }
1492
1493 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1494 /// a tailcall target by changing its ABI.
1495 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1496   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1497 }
1498
1499 SDValue
1500 X86TargetLowering::LowerMemArgument(SDValue Chain,
1501                                     CallingConv::ID CallConv,
1502                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1503                                     DebugLoc dl, SelectionDAG &DAG,
1504                                     const CCValAssign &VA,
1505                                     MachineFrameInfo *MFI,
1506                                     unsigned i) const {
1507   // Create the nodes corresponding to a load from this parameter slot.
1508   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1509   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1510   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1511   EVT ValVT;
1512
1513   // If value is passed by pointer we have address passed instead of the value
1514   // itself.
1515   if (VA.getLocInfo() == CCValAssign::Indirect)
1516     ValVT = VA.getLocVT();
1517   else
1518     ValVT = VA.getValVT();
1519
1520   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1521   // changed with more analysis.
1522   // In case of tail call optimization mark all arguments mutable. Since they
1523   // could be overwritten by lowering of arguments in case of a tail call.
1524   if (Flags.isByVal()) {
1525     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1526                                     VA.getLocMemOffset(), isImmutable);
1527     return DAG.getFrameIndex(FI, getPointerTy());
1528   } else {
1529     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1530                                     VA.getLocMemOffset(), isImmutable);
1531     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1532     return DAG.getLoad(ValVT, dl, Chain, FIN,
1533                        MachinePointerInfo::getFixedStack(FI),
1534                        false, false, 0);
1535   }
1536 }
1537
1538 SDValue
1539 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1540                                         CallingConv::ID CallConv,
1541                                         bool isVarArg,
1542                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1543                                         DebugLoc dl,
1544                                         SelectionDAG &DAG,
1545                                         SmallVectorImpl<SDValue> &InVals)
1546                                           const {
1547   MachineFunction &MF = DAG.getMachineFunction();
1548   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1549
1550   const Function* Fn = MF.getFunction();
1551   if (Fn->hasExternalLinkage() &&
1552       Subtarget->isTargetCygMing() &&
1553       Fn->getName() == "main")
1554     FuncInfo->setForceFramePointer(true);
1555
1556   MachineFrameInfo *MFI = MF.getFrameInfo();
1557   bool Is64Bit = Subtarget->is64Bit();
1558   bool IsWin64 = Subtarget->isTargetWin64();
1559
1560   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1561          "Var args not supported with calling convention fastcc or ghc");
1562
1563   // Assign locations to all of the incoming arguments.
1564   SmallVector<CCValAssign, 16> ArgLocs;
1565   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1566                  ArgLocs, *DAG.getContext());
1567   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1568
1569   unsigned LastVal = ~0U;
1570   SDValue ArgValue;
1571   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1572     CCValAssign &VA = ArgLocs[i];
1573     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1574     // places.
1575     assert(VA.getValNo() != LastVal &&
1576            "Don't support value assigned to multiple locs yet");
1577     LastVal = VA.getValNo();
1578
1579     if (VA.isRegLoc()) {
1580       EVT RegVT = VA.getLocVT();
1581       TargetRegisterClass *RC = NULL;
1582       if (RegVT == MVT::i32)
1583         RC = X86::GR32RegisterClass;
1584       else if (Is64Bit && RegVT == MVT::i64)
1585         RC = X86::GR64RegisterClass;
1586       else if (RegVT == MVT::f32)
1587         RC = X86::FR32RegisterClass;
1588       else if (RegVT == MVT::f64)
1589         RC = X86::FR64RegisterClass;
1590       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1591         RC = X86::VR256RegisterClass;
1592       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1593         RC = X86::VR128RegisterClass;
1594       else if (RegVT == MVT::x86mmx)
1595         RC = X86::VR64RegisterClass;
1596       else
1597         llvm_unreachable("Unknown argument type!");
1598
1599       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1600       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1601
1602       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1603       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1604       // right size.
1605       if (VA.getLocInfo() == CCValAssign::SExt)
1606         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1607                                DAG.getValueType(VA.getValVT()));
1608       else if (VA.getLocInfo() == CCValAssign::ZExt)
1609         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1610                                DAG.getValueType(VA.getValVT()));
1611       else if (VA.getLocInfo() == CCValAssign::BCvt)
1612         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1613
1614       if (VA.isExtInLoc()) {
1615         // Handle MMX values passed in XMM regs.
1616         if (RegVT.isVector()) {
1617           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1618                                  ArgValue);
1619         } else
1620           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1621       }
1622     } else {
1623       assert(VA.isMemLoc());
1624       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1625     }
1626
1627     // If value is passed via pointer - do a load.
1628     if (VA.getLocInfo() == CCValAssign::Indirect)
1629       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1630                              MachinePointerInfo(), false, false, 0);
1631
1632     InVals.push_back(ArgValue);
1633   }
1634
1635   // The x86-64 ABI for returning structs by value requires that we copy
1636   // the sret argument into %rax for the return. Save the argument into
1637   // a virtual register so that we can access it from the return points.
1638   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1639     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1640     unsigned Reg = FuncInfo->getSRetReturnReg();
1641     if (!Reg) {
1642       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1643       FuncInfo->setSRetReturnReg(Reg);
1644     }
1645     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1646     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1647   }
1648
1649   unsigned StackSize = CCInfo.getNextStackOffset();
1650   // Align stack specially for tail calls.
1651   if (FuncIsMadeTailCallSafe(CallConv))
1652     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1653
1654   // If the function takes variable number of arguments, make a frame index for
1655   // the start of the first vararg value... for expansion of llvm.va_start.
1656   if (isVarArg) {
1657     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1658                     CallConv != CallingConv::X86_ThisCall))) {
1659       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1660     }
1661     if (Is64Bit) {
1662       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1663
1664       // FIXME: We should really autogenerate these arrays
1665       static const unsigned GPR64ArgRegsWin64[] = {
1666         X86::RCX, X86::RDX, X86::R8,  X86::R9
1667       };
1668       static const unsigned GPR64ArgRegs64Bit[] = {
1669         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1670       };
1671       static const unsigned XMMArgRegs64Bit[] = {
1672         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1673         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1674       };
1675       const unsigned *GPR64ArgRegs;
1676       unsigned NumXMMRegs = 0;
1677
1678       if (IsWin64) {
1679         // The XMM registers which might contain var arg parameters are shadowed
1680         // in their paired GPR.  So we only need to save the GPR to their home
1681         // slots.
1682         TotalNumIntRegs = 4;
1683         GPR64ArgRegs = GPR64ArgRegsWin64;
1684       } else {
1685         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1686         GPR64ArgRegs = GPR64ArgRegs64Bit;
1687
1688         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1689       }
1690       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1691                                                        TotalNumIntRegs);
1692
1693       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1694       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1695              "SSE register cannot be used when SSE is disabled!");
1696       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1697              "SSE register cannot be used when SSE is disabled!");
1698       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1699         // Kernel mode asks for SSE to be disabled, so don't push them
1700         // on the stack.
1701         TotalNumXMMRegs = 0;
1702
1703       if (IsWin64) {
1704         FuncInfo->setRegSaveFrameIndex(
1705           MFI->CreateFixedObject(1, NumIntRegs * 8, false));
1706         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1707       } else {
1708         // For X86-64, if there are vararg parameters that are passed via
1709         // registers, then we must store them to their spots on the stack so they
1710         // may be loaded by deferencing the result of va_next.
1711         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1712         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1713         FuncInfo->setRegSaveFrameIndex(
1714           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1715                                false));
1716       }
1717
1718       // Store the integer parameter registers.
1719       SmallVector<SDValue, 8> MemOps;
1720       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1721                                         getPointerTy());
1722       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1723       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1724         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1725                                   DAG.getIntPtrConstant(Offset));
1726         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1727                                      X86::GR64RegisterClass);
1728         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1729         SDValue Store =
1730           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1731                        MachinePointerInfo::getFixedStack(
1732                          FuncInfo->getRegSaveFrameIndex(), Offset),
1733                        false, false, 0);
1734         MemOps.push_back(Store);
1735         Offset += 8;
1736       }
1737
1738       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1739         // Now store the XMM (fp + vector) parameter registers.
1740         SmallVector<SDValue, 11> SaveXMMOps;
1741         SaveXMMOps.push_back(Chain);
1742
1743         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1744         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1745         SaveXMMOps.push_back(ALVal);
1746
1747         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1748                                FuncInfo->getRegSaveFrameIndex()));
1749         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1750                                FuncInfo->getVarArgsFPOffset()));
1751
1752         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1753           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1754                                        X86::VR128RegisterClass);
1755           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1756           SaveXMMOps.push_back(Val);
1757         }
1758         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1759                                      MVT::Other,
1760                                      &SaveXMMOps[0], SaveXMMOps.size()));
1761       }
1762
1763       if (!MemOps.empty())
1764         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1765                             &MemOps[0], MemOps.size());
1766     }
1767   }
1768
1769   // Some CCs need callee pop.
1770   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1771     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1772   } else {
1773     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1774     // If this is an sret function, the return should pop the hidden pointer.
1775     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1776       FuncInfo->setBytesToPopOnReturn(4);
1777   }
1778
1779   if (!Is64Bit) {
1780     // RegSaveFrameIndex is X86-64 only.
1781     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1782     if (CallConv == CallingConv::X86_FastCall ||
1783         CallConv == CallingConv::X86_ThisCall)
1784       // fastcc functions can't have varargs.
1785       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1786   }
1787
1788   return Chain;
1789 }
1790
1791 SDValue
1792 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1793                                     SDValue StackPtr, SDValue Arg,
1794                                     DebugLoc dl, SelectionDAG &DAG,
1795                                     const CCValAssign &VA,
1796                                     ISD::ArgFlagsTy Flags) const {
1797   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1798   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1799   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1800   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1801   if (Flags.isByVal())
1802     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1803
1804   return DAG.getStore(Chain, dl, Arg, PtrOff,
1805                       MachinePointerInfo::getStack(LocMemOffset),
1806                       false, false, 0);
1807 }
1808
1809 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1810 /// optimization is performed and it is required.
1811 SDValue
1812 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1813                                            SDValue &OutRetAddr, SDValue Chain,
1814                                            bool IsTailCall, bool Is64Bit,
1815                                            int FPDiff, DebugLoc dl) const {
1816   // Adjust the Return address stack slot.
1817   EVT VT = getPointerTy();
1818   OutRetAddr = getReturnAddressFrameIndex(DAG);
1819
1820   // Load the "old" Return address.
1821   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1822                            false, false, 0);
1823   return SDValue(OutRetAddr.getNode(), 1);
1824 }
1825
1826 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1827 /// optimization is performed and it is required (FPDiff!=0).
1828 static SDValue
1829 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1830                          SDValue Chain, SDValue RetAddrFrIdx,
1831                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1832   // Store the return address to the appropriate stack slot.
1833   if (!FPDiff) return Chain;
1834   // Calculate the new stack slot for the return address.
1835   int SlotSize = Is64Bit ? 8 : 4;
1836   int NewReturnAddrFI =
1837     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1838   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1839   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1840   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1841                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1842                        false, false, 0);
1843   return Chain;
1844 }
1845
1846 SDValue
1847 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1848                              CallingConv::ID CallConv, bool isVarArg,
1849                              bool &isTailCall,
1850                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1851                              const SmallVectorImpl<SDValue> &OutVals,
1852                              const SmallVectorImpl<ISD::InputArg> &Ins,
1853                              DebugLoc dl, SelectionDAG &DAG,
1854                              SmallVectorImpl<SDValue> &InVals) const {
1855   MachineFunction &MF = DAG.getMachineFunction();
1856   bool Is64Bit        = Subtarget->is64Bit();
1857   bool IsStructRet    = CallIsStructReturn(Outs);
1858   bool IsSibcall      = false;
1859
1860   if (isTailCall) {
1861     // Check if it's really possible to do a tail call.
1862     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1863                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1864                                                    Outs, OutVals, Ins, DAG);
1865
1866     // Sibcalls are automatically detected tailcalls which do not require
1867     // ABI changes.
1868     if (!GuaranteedTailCallOpt && isTailCall)
1869       IsSibcall = true;
1870
1871     if (isTailCall)
1872       ++NumTailCalls;
1873   }
1874
1875   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1876          "Var args not supported with calling convention fastcc or ghc");
1877
1878   // Analyze operands of the call, assigning locations to each operand.
1879   SmallVector<CCValAssign, 16> ArgLocs;
1880   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1881                  ArgLocs, *DAG.getContext());
1882   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1883
1884   // Get a count of how many bytes are to be pushed on the stack.
1885   unsigned NumBytes = CCInfo.getNextStackOffset();
1886   if (IsSibcall)
1887     // This is a sibcall. The memory operands are available in caller's
1888     // own caller's stack.
1889     NumBytes = 0;
1890   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1891     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1892
1893   int FPDiff = 0;
1894   if (isTailCall && !IsSibcall) {
1895     // Lower arguments at fp - stackoffset + fpdiff.
1896     unsigned NumBytesCallerPushed =
1897       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1898     FPDiff = NumBytesCallerPushed - NumBytes;
1899
1900     // Set the delta of movement of the returnaddr stackslot.
1901     // But only set if delta is greater than previous delta.
1902     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1903       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1904   }
1905
1906   if (!IsSibcall)
1907     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1908
1909   SDValue RetAddrFrIdx;
1910   // Load return adress for tail calls.
1911   if (isTailCall && FPDiff)
1912     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1913                                     Is64Bit, FPDiff, dl);
1914
1915   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1916   SmallVector<SDValue, 8> MemOpChains;
1917   SDValue StackPtr;
1918
1919   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1920   // of tail call optimization arguments are handle later.
1921   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1922     CCValAssign &VA = ArgLocs[i];
1923     EVT RegVT = VA.getLocVT();
1924     SDValue Arg = OutVals[i];
1925     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1926     bool isByVal = Flags.isByVal();
1927
1928     // Promote the value if needed.
1929     switch (VA.getLocInfo()) {
1930     default: llvm_unreachable("Unknown loc info!");
1931     case CCValAssign::Full: break;
1932     case CCValAssign::SExt:
1933       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1934       break;
1935     case CCValAssign::ZExt:
1936       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1937       break;
1938     case CCValAssign::AExt:
1939       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1940         // Special case: passing MMX values in XMM registers.
1941         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1942         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1943         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1944       } else
1945         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1946       break;
1947     case CCValAssign::BCvt:
1948       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1949       break;
1950     case CCValAssign::Indirect: {
1951       // Store the argument.
1952       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1953       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1954       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1955                            MachinePointerInfo::getFixedStack(FI),
1956                            false, false, 0);
1957       Arg = SpillSlot;
1958       break;
1959     }
1960     }
1961
1962     if (VA.isRegLoc()) {
1963       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1964       if (isVarArg && Subtarget->isTargetWin64()) {
1965         // Win64 ABI requires argument XMM reg to be copied to the corresponding
1966         // shadow reg if callee is a varargs function.
1967         unsigned ShadowReg = 0;
1968         switch (VA.getLocReg()) {
1969         case X86::XMM0: ShadowReg = X86::RCX; break;
1970         case X86::XMM1: ShadowReg = X86::RDX; break;
1971         case X86::XMM2: ShadowReg = X86::R8; break;
1972         case X86::XMM3: ShadowReg = X86::R9; break;
1973         }
1974         if (ShadowReg)
1975           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1976       }
1977     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1978       assert(VA.isMemLoc());
1979       if (StackPtr.getNode() == 0)
1980         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1981       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1982                                              dl, DAG, VA, Flags));
1983     }
1984   }
1985
1986   if (!MemOpChains.empty())
1987     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1988                         &MemOpChains[0], MemOpChains.size());
1989
1990   // Build a sequence of copy-to-reg nodes chained together with token chain
1991   // and flag operands which copy the outgoing args into registers.
1992   SDValue InFlag;
1993   // Tail call byval lowering might overwrite argument registers so in case of
1994   // tail call optimization the copies to registers are lowered later.
1995   if (!isTailCall)
1996     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1997       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1998                                RegsToPass[i].second, InFlag);
1999       InFlag = Chain.getValue(1);
2000     }
2001
2002   if (Subtarget->isPICStyleGOT()) {
2003     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2004     // GOT pointer.
2005     if (!isTailCall) {
2006       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2007                                DAG.getNode(X86ISD::GlobalBaseReg,
2008                                            DebugLoc(), getPointerTy()),
2009                                InFlag);
2010       InFlag = Chain.getValue(1);
2011     } else {
2012       // If we are tail calling and generating PIC/GOT style code load the
2013       // address of the callee into ECX. The value in ecx is used as target of
2014       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2015       // for tail calls on PIC/GOT architectures. Normally we would just put the
2016       // address of GOT into ebx and then call target@PLT. But for tail calls
2017       // ebx would be restored (since ebx is callee saved) before jumping to the
2018       // target@PLT.
2019
2020       // Note: The actual moving to ECX is done further down.
2021       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2022       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2023           !G->getGlobal()->hasProtectedVisibility())
2024         Callee = LowerGlobalAddress(Callee, DAG);
2025       else if (isa<ExternalSymbolSDNode>(Callee))
2026         Callee = LowerExternalSymbol(Callee, DAG);
2027     }
2028   }
2029
2030   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2031     // From AMD64 ABI document:
2032     // For calls that may call functions that use varargs or stdargs
2033     // (prototype-less calls or calls to functions containing ellipsis (...) in
2034     // the declaration) %al is used as hidden argument to specify the number
2035     // of SSE registers used. The contents of %al do not need to match exactly
2036     // the number of registers, but must be an ubound on the number of SSE
2037     // registers used and is in the range 0 - 8 inclusive.
2038
2039     // Count the number of XMM registers allocated.
2040     static const unsigned XMMArgRegs[] = {
2041       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2042       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2043     };
2044     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2045     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2046            && "SSE registers cannot be used when SSE is disabled");
2047
2048     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2049                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2050     InFlag = Chain.getValue(1);
2051   }
2052
2053
2054   // For tail calls lower the arguments to the 'real' stack slot.
2055   if (isTailCall) {
2056     // Force all the incoming stack arguments to be loaded from the stack
2057     // before any new outgoing arguments are stored to the stack, because the
2058     // outgoing stack slots may alias the incoming argument stack slots, and
2059     // the alias isn't otherwise explicit. This is slightly more conservative
2060     // than necessary, because it means that each store effectively depends
2061     // on every argument instead of just those arguments it would clobber.
2062     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2063
2064     SmallVector<SDValue, 8> MemOpChains2;
2065     SDValue FIN;
2066     int FI = 0;
2067     // Do not flag preceeding copytoreg stuff together with the following stuff.
2068     InFlag = SDValue();
2069     if (GuaranteedTailCallOpt) {
2070       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2071         CCValAssign &VA = ArgLocs[i];
2072         if (VA.isRegLoc())
2073           continue;
2074         assert(VA.isMemLoc());
2075         SDValue Arg = OutVals[i];
2076         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2077         // Create frame index.
2078         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2079         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2080         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2081         FIN = DAG.getFrameIndex(FI, getPointerTy());
2082
2083         if (Flags.isByVal()) {
2084           // Copy relative to framepointer.
2085           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2086           if (StackPtr.getNode() == 0)
2087             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2088                                           getPointerTy());
2089           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2090
2091           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2092                                                            ArgChain,
2093                                                            Flags, DAG, dl));
2094         } else {
2095           // Store relative to framepointer.
2096           MemOpChains2.push_back(
2097             DAG.getStore(ArgChain, dl, Arg, FIN,
2098                          MachinePointerInfo::getFixedStack(FI),
2099                          false, false, 0));
2100         }
2101       }
2102     }
2103
2104     if (!MemOpChains2.empty())
2105       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2106                           &MemOpChains2[0], MemOpChains2.size());
2107
2108     // Copy arguments to their registers.
2109     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2110       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2111                                RegsToPass[i].second, InFlag);
2112       InFlag = Chain.getValue(1);
2113     }
2114     InFlag =SDValue();
2115
2116     // Store the return address to the appropriate stack slot.
2117     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2118                                      FPDiff, dl);
2119   }
2120
2121   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2122     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2123     // In the 64-bit large code model, we have to make all calls
2124     // through a register, since the call instruction's 32-bit
2125     // pc-relative offset may not be large enough to hold the whole
2126     // address.
2127   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2128     // If the callee is a GlobalAddress node (quite common, every direct call
2129     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2130     // it.
2131
2132     // We should use extra load for direct calls to dllimported functions in
2133     // non-JIT mode.
2134     const GlobalValue *GV = G->getGlobal();
2135     if (!GV->hasDLLImportLinkage()) {
2136       unsigned char OpFlags = 0;
2137
2138       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2139       // external symbols most go through the PLT in PIC mode.  If the symbol
2140       // has hidden or protected visibility, or if it is static or local, then
2141       // we don't need to use the PLT - we can directly call it.
2142       if (Subtarget->isTargetELF() &&
2143           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2144           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2145         OpFlags = X86II::MO_PLT;
2146       } else if (Subtarget->isPICStyleStubAny() &&
2147                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2148                  Subtarget->getDarwinVers() < 9) {
2149         // PC-relative references to external symbols should go through $stub,
2150         // unless we're building with the leopard linker or later, which
2151         // automatically synthesizes these stubs.
2152         OpFlags = X86II::MO_DARWIN_STUB;
2153       }
2154
2155       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2156                                           G->getOffset(), OpFlags);
2157     }
2158   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2159     unsigned char OpFlags = 0;
2160
2161     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2162     // symbols should go through the PLT.
2163     if (Subtarget->isTargetELF() &&
2164         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2165       OpFlags = X86II::MO_PLT;
2166     } else if (Subtarget->isPICStyleStubAny() &&
2167                Subtarget->getDarwinVers() < 9) {
2168       // PC-relative references to external symbols should go through $stub,
2169       // unless we're building with the leopard linker or later, which
2170       // automatically synthesizes these stubs.
2171       OpFlags = X86II::MO_DARWIN_STUB;
2172     }
2173
2174     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2175                                          OpFlags);
2176   }
2177
2178   // Returns a chain & a flag for retval copy to use.
2179   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2180   SmallVector<SDValue, 8> Ops;
2181
2182   if (!IsSibcall && isTailCall) {
2183     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2184                            DAG.getIntPtrConstant(0, true), InFlag);
2185     InFlag = Chain.getValue(1);
2186   }
2187
2188   Ops.push_back(Chain);
2189   Ops.push_back(Callee);
2190
2191   if (isTailCall)
2192     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2193
2194   // Add argument registers to the end of the list so that they are known live
2195   // into the call.
2196   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2197     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2198                                   RegsToPass[i].second.getValueType()));
2199
2200   // Add an implicit use GOT pointer in EBX.
2201   if (!isTailCall && Subtarget->isPICStyleGOT())
2202     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2203
2204   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2205   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2206     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2207
2208   if (InFlag.getNode())
2209     Ops.push_back(InFlag);
2210
2211   if (isTailCall) {
2212     // We used to do:
2213     //// If this is the first return lowered for this function, add the regs
2214     //// to the liveout set for the function.
2215     // This isn't right, although it's probably harmless on x86; liveouts
2216     // should be computed from returns not tail calls.  Consider a void
2217     // function making a tail call to a function returning int.
2218     return DAG.getNode(X86ISD::TC_RETURN, dl,
2219                        NodeTys, &Ops[0], Ops.size());
2220   }
2221
2222   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2223   InFlag = Chain.getValue(1);
2224
2225   // Create the CALLSEQ_END node.
2226   unsigned NumBytesForCalleeToPush;
2227   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2228     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2229   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2230     // If this is a call to a struct-return function, the callee
2231     // pops the hidden struct pointer, so we have to push it back.
2232     // This is common for Darwin/X86, Linux & Mingw32 targets.
2233     NumBytesForCalleeToPush = 4;
2234   else
2235     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2236
2237   // Returns a flag for retval copy to use.
2238   if (!IsSibcall) {
2239     Chain = DAG.getCALLSEQ_END(Chain,
2240                                DAG.getIntPtrConstant(NumBytes, true),
2241                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2242                                                      true),
2243                                InFlag);
2244     InFlag = Chain.getValue(1);
2245   }
2246
2247   // Handle result values, copying them out of physregs into vregs that we
2248   // return.
2249   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2250                          Ins, dl, DAG, InVals);
2251 }
2252
2253
2254 //===----------------------------------------------------------------------===//
2255 //                Fast Calling Convention (tail call) implementation
2256 //===----------------------------------------------------------------------===//
2257
2258 //  Like std call, callee cleans arguments, convention except that ECX is
2259 //  reserved for storing the tail called function address. Only 2 registers are
2260 //  free for argument passing (inreg). Tail call optimization is performed
2261 //  provided:
2262 //                * tailcallopt is enabled
2263 //                * caller/callee are fastcc
2264 //  On X86_64 architecture with GOT-style position independent code only local
2265 //  (within module) calls are supported at the moment.
2266 //  To keep the stack aligned according to platform abi the function
2267 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2268 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2269 //  If a tail called function callee has more arguments than the caller the
2270 //  caller needs to make sure that there is room to move the RETADDR to. This is
2271 //  achieved by reserving an area the size of the argument delta right after the
2272 //  original REtADDR, but before the saved framepointer or the spilled registers
2273 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2274 //  stack layout:
2275 //    arg1
2276 //    arg2
2277 //    RETADDR
2278 //    [ new RETADDR
2279 //      move area ]
2280 //    (possible EBP)
2281 //    ESI
2282 //    EDI
2283 //    local1 ..
2284
2285 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2286 /// for a 16 byte align requirement.
2287 unsigned
2288 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2289                                                SelectionDAG& DAG) const {
2290   MachineFunction &MF = DAG.getMachineFunction();
2291   const TargetMachine &TM = MF.getTarget();
2292   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2293   unsigned StackAlignment = TFI.getStackAlignment();
2294   uint64_t AlignMask = StackAlignment - 1;
2295   int64_t Offset = StackSize;
2296   uint64_t SlotSize = TD->getPointerSize();
2297   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2298     // Number smaller than 12 so just add the difference.
2299     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2300   } else {
2301     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2302     Offset = ((~AlignMask) & Offset) + StackAlignment +
2303       (StackAlignment-SlotSize);
2304   }
2305   return Offset;
2306 }
2307
2308 /// MatchingStackOffset - Return true if the given stack call argument is
2309 /// already available in the same position (relatively) of the caller's
2310 /// incoming argument stack.
2311 static
2312 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2313                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2314                          const X86InstrInfo *TII) {
2315   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2316   int FI = INT_MAX;
2317   if (Arg.getOpcode() == ISD::CopyFromReg) {
2318     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2319     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2320       return false;
2321     MachineInstr *Def = MRI->getVRegDef(VR);
2322     if (!Def)
2323       return false;
2324     if (!Flags.isByVal()) {
2325       if (!TII->isLoadFromStackSlot(Def, FI))
2326         return false;
2327     } else {
2328       unsigned Opcode = Def->getOpcode();
2329       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2330           Def->getOperand(1).isFI()) {
2331         FI = Def->getOperand(1).getIndex();
2332         Bytes = Flags.getByValSize();
2333       } else
2334         return false;
2335     }
2336   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2337     if (Flags.isByVal())
2338       // ByVal argument is passed in as a pointer but it's now being
2339       // dereferenced. e.g.
2340       // define @foo(%struct.X* %A) {
2341       //   tail call @bar(%struct.X* byval %A)
2342       // }
2343       return false;
2344     SDValue Ptr = Ld->getBasePtr();
2345     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2346     if (!FINode)
2347       return false;
2348     FI = FINode->getIndex();
2349   } else
2350     return false;
2351
2352   assert(FI != INT_MAX);
2353   if (!MFI->isFixedObjectIndex(FI))
2354     return false;
2355   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2356 }
2357
2358 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2359 /// for tail call optimization. Targets which want to do tail call
2360 /// optimization should implement this function.
2361 bool
2362 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2363                                                      CallingConv::ID CalleeCC,
2364                                                      bool isVarArg,
2365                                                      bool isCalleeStructRet,
2366                                                      bool isCallerStructRet,
2367                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2368                                     const SmallVectorImpl<SDValue> &OutVals,
2369                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2370                                                      SelectionDAG& DAG) const {
2371   if (!IsTailCallConvention(CalleeCC) &&
2372       CalleeCC != CallingConv::C)
2373     return false;
2374
2375   // If -tailcallopt is specified, make fastcc functions tail-callable.
2376   const MachineFunction &MF = DAG.getMachineFunction();
2377   const Function *CallerF = DAG.getMachineFunction().getFunction();
2378   CallingConv::ID CallerCC = CallerF->getCallingConv();
2379   bool CCMatch = CallerCC == CalleeCC;
2380
2381   if (GuaranteedTailCallOpt) {
2382     if (IsTailCallConvention(CalleeCC) && CCMatch)
2383       return true;
2384     return false;
2385   }
2386
2387   // Look for obvious safe cases to perform tail call optimization that do not
2388   // require ABI changes. This is what gcc calls sibcall.
2389
2390   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2391   // emit a special epilogue.
2392   if (RegInfo->needsStackRealignment(MF))
2393     return false;
2394
2395   // Do not sibcall optimize vararg calls unless the call site is not passing
2396   // any arguments.
2397   if (isVarArg && !Outs.empty())
2398     return false;
2399
2400   // Also avoid sibcall optimization if either caller or callee uses struct
2401   // return semantics.
2402   if (isCalleeStructRet || isCallerStructRet)
2403     return false;
2404
2405   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2406   // Therefore if it's not used by the call it is not safe to optimize this into
2407   // a sibcall.
2408   bool Unused = false;
2409   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2410     if (!Ins[i].Used) {
2411       Unused = true;
2412       break;
2413     }
2414   }
2415   if (Unused) {
2416     SmallVector<CCValAssign, 16> RVLocs;
2417     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2418                    RVLocs, *DAG.getContext());
2419     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2420     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2421       CCValAssign &VA = RVLocs[i];
2422       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2423         return false;
2424     }
2425   }
2426
2427   // If the calling conventions do not match, then we'd better make sure the
2428   // results are returned in the same way as what the caller expects.
2429   if (!CCMatch) {
2430     SmallVector<CCValAssign, 16> RVLocs1;
2431     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2432                     RVLocs1, *DAG.getContext());
2433     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2434
2435     SmallVector<CCValAssign, 16> RVLocs2;
2436     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2437                     RVLocs2, *DAG.getContext());
2438     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2439
2440     if (RVLocs1.size() != RVLocs2.size())
2441       return false;
2442     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2443       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2444         return false;
2445       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2446         return false;
2447       if (RVLocs1[i].isRegLoc()) {
2448         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2449           return false;
2450       } else {
2451         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2452           return false;
2453       }
2454     }
2455   }
2456
2457   // If the callee takes no arguments then go on to check the results of the
2458   // call.
2459   if (!Outs.empty()) {
2460     // Check if stack adjustment is needed. For now, do not do this if any
2461     // argument is passed on the stack.
2462     SmallVector<CCValAssign, 16> ArgLocs;
2463     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2464                    ArgLocs, *DAG.getContext());
2465     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2466     if (CCInfo.getNextStackOffset()) {
2467       MachineFunction &MF = DAG.getMachineFunction();
2468       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2469         return false;
2470       if (Subtarget->isTargetWin64())
2471         // Win64 ABI has additional complications.
2472         return false;
2473
2474       // Check if the arguments are already laid out in the right way as
2475       // the caller's fixed stack objects.
2476       MachineFrameInfo *MFI = MF.getFrameInfo();
2477       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2478       const X86InstrInfo *TII =
2479         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2480       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2481         CCValAssign &VA = ArgLocs[i];
2482         SDValue Arg = OutVals[i];
2483         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2484         if (VA.getLocInfo() == CCValAssign::Indirect)
2485           return false;
2486         if (!VA.isRegLoc()) {
2487           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2488                                    MFI, MRI, TII))
2489             return false;
2490         }
2491       }
2492     }
2493
2494     // If the tailcall address may be in a register, then make sure it's
2495     // possible to register allocate for it. In 32-bit, the call address can
2496     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2497     // callee-saved registers are restored. These happen to be the same
2498     // registers used to pass 'inreg' arguments so watch out for those.
2499     if (!Subtarget->is64Bit() &&
2500         !isa<GlobalAddressSDNode>(Callee) &&
2501         !isa<ExternalSymbolSDNode>(Callee)) {
2502       unsigned NumInRegs = 0;
2503       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504         CCValAssign &VA = ArgLocs[i];
2505         if (!VA.isRegLoc())
2506           continue;
2507         unsigned Reg = VA.getLocReg();
2508         switch (Reg) {
2509         default: break;
2510         case X86::EAX: case X86::EDX: case X86::ECX:
2511           if (++NumInRegs == 3)
2512             return false;
2513           break;
2514         }
2515       }
2516     }
2517   }
2518
2519   return true;
2520 }
2521
2522 FastISel *
2523 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2524   return X86::createFastISel(funcInfo);
2525 }
2526
2527
2528 //===----------------------------------------------------------------------===//
2529 //                           Other Lowering Hooks
2530 //===----------------------------------------------------------------------===//
2531
2532 static bool MayFoldLoad(SDValue Op) {
2533   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2534 }
2535
2536 static bool MayFoldIntoStore(SDValue Op) {
2537   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2538 }
2539
2540 static bool isTargetShuffle(unsigned Opcode) {
2541   switch(Opcode) {
2542   default: return false;
2543   case X86ISD::PSHUFD:
2544   case X86ISD::PSHUFHW:
2545   case X86ISD::PSHUFLW:
2546   case X86ISD::SHUFPD:
2547   case X86ISD::PALIGN:
2548   case X86ISD::SHUFPS:
2549   case X86ISD::MOVLHPS:
2550   case X86ISD::MOVLHPD:
2551   case X86ISD::MOVHLPS:
2552   case X86ISD::MOVLPS:
2553   case X86ISD::MOVLPD:
2554   case X86ISD::MOVSHDUP:
2555   case X86ISD::MOVSLDUP:
2556   case X86ISD::MOVDDUP:
2557   case X86ISD::MOVSS:
2558   case X86ISD::MOVSD:
2559   case X86ISD::UNPCKLPS:
2560   case X86ISD::UNPCKLPD:
2561   case X86ISD::PUNPCKLWD:
2562   case X86ISD::PUNPCKLBW:
2563   case X86ISD::PUNPCKLDQ:
2564   case X86ISD::PUNPCKLQDQ:
2565   case X86ISD::UNPCKHPS:
2566   case X86ISD::UNPCKHPD:
2567   case X86ISD::PUNPCKHWD:
2568   case X86ISD::PUNPCKHBW:
2569   case X86ISD::PUNPCKHDQ:
2570   case X86ISD::PUNPCKHQDQ:
2571     return true;
2572   }
2573   return false;
2574 }
2575
2576 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2577                                                SDValue V1, SelectionDAG &DAG) {
2578   switch(Opc) {
2579   default: llvm_unreachable("Unknown x86 shuffle node");
2580   case X86ISD::MOVSHDUP:
2581   case X86ISD::MOVSLDUP:
2582   case X86ISD::MOVDDUP:
2583     return DAG.getNode(Opc, dl, VT, V1);
2584   }
2585
2586   return SDValue();
2587 }
2588
2589 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2590                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2591   switch(Opc) {
2592   default: llvm_unreachable("Unknown x86 shuffle node");
2593   case X86ISD::PSHUFD:
2594   case X86ISD::PSHUFHW:
2595   case X86ISD::PSHUFLW:
2596     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2597   }
2598
2599   return SDValue();
2600 }
2601
2602 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2603                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2604   switch(Opc) {
2605   default: llvm_unreachable("Unknown x86 shuffle node");
2606   case X86ISD::PALIGN:
2607   case X86ISD::SHUFPD:
2608   case X86ISD::SHUFPS:
2609     return DAG.getNode(Opc, dl, VT, V1, V2,
2610                        DAG.getConstant(TargetMask, MVT::i8));
2611   }
2612   return SDValue();
2613 }
2614
2615 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2616                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2617   switch(Opc) {
2618   default: llvm_unreachable("Unknown x86 shuffle node");
2619   case X86ISD::MOVLHPS:
2620   case X86ISD::MOVLHPD:
2621   case X86ISD::MOVHLPS:
2622   case X86ISD::MOVLPS:
2623   case X86ISD::MOVLPD:
2624   case X86ISD::MOVSS:
2625   case X86ISD::MOVSD:
2626   case X86ISD::UNPCKLPS:
2627   case X86ISD::UNPCKLPD:
2628   case X86ISD::PUNPCKLWD:
2629   case X86ISD::PUNPCKLBW:
2630   case X86ISD::PUNPCKLDQ:
2631   case X86ISD::PUNPCKLQDQ:
2632   case X86ISD::UNPCKHPS:
2633   case X86ISD::UNPCKHPD:
2634   case X86ISD::PUNPCKHWD:
2635   case X86ISD::PUNPCKHBW:
2636   case X86ISD::PUNPCKHDQ:
2637   case X86ISD::PUNPCKHQDQ:
2638     return DAG.getNode(Opc, dl, VT, V1, V2);
2639   }
2640   return SDValue();
2641 }
2642
2643 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2644   MachineFunction &MF = DAG.getMachineFunction();
2645   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2646   int ReturnAddrIndex = FuncInfo->getRAIndex();
2647
2648   if (ReturnAddrIndex == 0) {
2649     // Set up a frame object for the return address.
2650     uint64_t SlotSize = TD->getPointerSize();
2651     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2652                                                            false);
2653     FuncInfo->setRAIndex(ReturnAddrIndex);
2654   }
2655
2656   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2657 }
2658
2659
2660 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2661                                        bool hasSymbolicDisplacement) {
2662   // Offset should fit into 32 bit immediate field.
2663   if (!isInt<32>(Offset))
2664     return false;
2665
2666   // If we don't have a symbolic displacement - we don't have any extra
2667   // restrictions.
2668   if (!hasSymbolicDisplacement)
2669     return true;
2670
2671   // FIXME: Some tweaks might be needed for medium code model.
2672   if (M != CodeModel::Small && M != CodeModel::Kernel)
2673     return false;
2674
2675   // For small code model we assume that latest object is 16MB before end of 31
2676   // bits boundary. We may also accept pretty large negative constants knowing
2677   // that all objects are in the positive half of address space.
2678   if (M == CodeModel::Small && Offset < 16*1024*1024)
2679     return true;
2680
2681   // For kernel code model we know that all object resist in the negative half
2682   // of 32bits address space. We may not accept negative offsets, since they may
2683   // be just off and we may accept pretty large positive ones.
2684   if (M == CodeModel::Kernel && Offset > 0)
2685     return true;
2686
2687   return false;
2688 }
2689
2690 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2691 /// specific condition code, returning the condition code and the LHS/RHS of the
2692 /// comparison to make.
2693 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2694                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2695   if (!isFP) {
2696     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2697       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2698         // X > -1   -> X == 0, jump !sign.
2699         RHS = DAG.getConstant(0, RHS.getValueType());
2700         return X86::COND_NS;
2701       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2702         // X < 0   -> X == 0, jump on sign.
2703         return X86::COND_S;
2704       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2705         // X < 1   -> X <= 0
2706         RHS = DAG.getConstant(0, RHS.getValueType());
2707         return X86::COND_LE;
2708       }
2709     }
2710
2711     switch (SetCCOpcode) {
2712     default: llvm_unreachable("Invalid integer condition!");
2713     case ISD::SETEQ:  return X86::COND_E;
2714     case ISD::SETGT:  return X86::COND_G;
2715     case ISD::SETGE:  return X86::COND_GE;
2716     case ISD::SETLT:  return X86::COND_L;
2717     case ISD::SETLE:  return X86::COND_LE;
2718     case ISD::SETNE:  return X86::COND_NE;
2719     case ISD::SETULT: return X86::COND_B;
2720     case ISD::SETUGT: return X86::COND_A;
2721     case ISD::SETULE: return X86::COND_BE;
2722     case ISD::SETUGE: return X86::COND_AE;
2723     }
2724   }
2725
2726   // First determine if it is required or is profitable to flip the operands.
2727
2728   // If LHS is a foldable load, but RHS is not, flip the condition.
2729   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2730       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2731     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2732     std::swap(LHS, RHS);
2733   }
2734
2735   switch (SetCCOpcode) {
2736   default: break;
2737   case ISD::SETOLT:
2738   case ISD::SETOLE:
2739   case ISD::SETUGT:
2740   case ISD::SETUGE:
2741     std::swap(LHS, RHS);
2742     break;
2743   }
2744
2745   // On a floating point condition, the flags are set as follows:
2746   // ZF  PF  CF   op
2747   //  0 | 0 | 0 | X > Y
2748   //  0 | 0 | 1 | X < Y
2749   //  1 | 0 | 0 | X == Y
2750   //  1 | 1 | 1 | unordered
2751   switch (SetCCOpcode) {
2752   default: llvm_unreachable("Condcode should be pre-legalized away");
2753   case ISD::SETUEQ:
2754   case ISD::SETEQ:   return X86::COND_E;
2755   case ISD::SETOLT:              // flipped
2756   case ISD::SETOGT:
2757   case ISD::SETGT:   return X86::COND_A;
2758   case ISD::SETOLE:              // flipped
2759   case ISD::SETOGE:
2760   case ISD::SETGE:   return X86::COND_AE;
2761   case ISD::SETUGT:              // flipped
2762   case ISD::SETULT:
2763   case ISD::SETLT:   return X86::COND_B;
2764   case ISD::SETUGE:              // flipped
2765   case ISD::SETULE:
2766   case ISD::SETLE:   return X86::COND_BE;
2767   case ISD::SETONE:
2768   case ISD::SETNE:   return X86::COND_NE;
2769   case ISD::SETUO:   return X86::COND_P;
2770   case ISD::SETO:    return X86::COND_NP;
2771   case ISD::SETOEQ:
2772   case ISD::SETUNE:  return X86::COND_INVALID;
2773   }
2774 }
2775
2776 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2777 /// code. Current x86 isa includes the following FP cmov instructions:
2778 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2779 static bool hasFPCMov(unsigned X86CC) {
2780   switch (X86CC) {
2781   default:
2782     return false;
2783   case X86::COND_B:
2784   case X86::COND_BE:
2785   case X86::COND_E:
2786   case X86::COND_P:
2787   case X86::COND_A:
2788   case X86::COND_AE:
2789   case X86::COND_NE:
2790   case X86::COND_NP:
2791     return true;
2792   }
2793 }
2794
2795 /// isFPImmLegal - Returns true if the target can instruction select the
2796 /// specified FP immediate natively. If false, the legalizer will
2797 /// materialize the FP immediate as a load from a constant pool.
2798 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2799   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2800     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2801       return true;
2802   }
2803   return false;
2804 }
2805
2806 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2807 /// the specified range (L, H].
2808 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2809   return (Val < 0) || (Val >= Low && Val < Hi);
2810 }
2811
2812 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2813 /// specified value.
2814 static bool isUndefOrEqual(int Val, int CmpVal) {
2815   if (Val < 0 || Val == CmpVal)
2816     return true;
2817   return false;
2818 }
2819
2820 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2821 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2822 /// the second operand.
2823 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2824   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2825     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2826   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2827     return (Mask[0] < 2 && Mask[1] < 2);
2828   return false;
2829 }
2830
2831 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2832   SmallVector<int, 8> M;
2833   N->getMask(M);
2834   return ::isPSHUFDMask(M, N->getValueType(0));
2835 }
2836
2837 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2838 /// is suitable for input to PSHUFHW.
2839 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2840   if (VT != MVT::v8i16)
2841     return false;
2842
2843   // Lower quadword copied in order or undef.
2844   for (int i = 0; i != 4; ++i)
2845     if (Mask[i] >= 0 && Mask[i] != i)
2846       return false;
2847
2848   // Upper quadword shuffled.
2849   for (int i = 4; i != 8; ++i)
2850     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2851       return false;
2852
2853   return true;
2854 }
2855
2856 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2857   SmallVector<int, 8> M;
2858   N->getMask(M);
2859   return ::isPSHUFHWMask(M, N->getValueType(0));
2860 }
2861
2862 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2863 /// is suitable for input to PSHUFLW.
2864 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2865   if (VT != MVT::v8i16)
2866     return false;
2867
2868   // Upper quadword copied in order.
2869   for (int i = 4; i != 8; ++i)
2870     if (Mask[i] >= 0 && Mask[i] != i)
2871       return false;
2872
2873   // Lower quadword shuffled.
2874   for (int i = 0; i != 4; ++i)
2875     if (Mask[i] >= 4)
2876       return false;
2877
2878   return true;
2879 }
2880
2881 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2882   SmallVector<int, 8> M;
2883   N->getMask(M);
2884   return ::isPSHUFLWMask(M, N->getValueType(0));
2885 }
2886
2887 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2888 /// is suitable for input to PALIGNR.
2889 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2890                           bool hasSSSE3) {
2891   int i, e = VT.getVectorNumElements();
2892   
2893   // Do not handle v2i64 / v2f64 shuffles with palignr.
2894   if (e < 4 || !hasSSSE3)
2895     return false;
2896   
2897   for (i = 0; i != e; ++i)
2898     if (Mask[i] >= 0)
2899       break;
2900   
2901   // All undef, not a palignr.
2902   if (i == e)
2903     return false;
2904
2905   // Determine if it's ok to perform a palignr with only the LHS, since we
2906   // don't have access to the actual shuffle elements to see if RHS is undef.
2907   bool Unary = Mask[i] < (int)e;
2908   bool NeedsUnary = false;
2909
2910   int s = Mask[i] - i;
2911   
2912   // Check the rest of the elements to see if they are consecutive.
2913   for (++i; i != e; ++i) {
2914     int m = Mask[i];
2915     if (m < 0) 
2916       continue;
2917     
2918     Unary = Unary && (m < (int)e);
2919     NeedsUnary = NeedsUnary || (m < s);
2920
2921     if (NeedsUnary && !Unary)
2922       return false;
2923     if (Unary && m != ((s+i) & (e-1)))
2924       return false;
2925     if (!Unary && m != (s+i))
2926       return false;
2927   }
2928   return true;
2929 }
2930
2931 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2932   SmallVector<int, 8> M;
2933   N->getMask(M);
2934   return ::isPALIGNRMask(M, N->getValueType(0), true);
2935 }
2936
2937 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2938 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2939 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2940   int NumElems = VT.getVectorNumElements();
2941   if (NumElems != 2 && NumElems != 4)
2942     return false;
2943
2944   int Half = NumElems / 2;
2945   for (int i = 0; i < Half; ++i)
2946     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2947       return false;
2948   for (int i = Half; i < NumElems; ++i)
2949     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2950       return false;
2951
2952   return true;
2953 }
2954
2955 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2956   SmallVector<int, 8> M;
2957   N->getMask(M);
2958   return ::isSHUFPMask(M, N->getValueType(0));
2959 }
2960
2961 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2962 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2963 /// half elements to come from vector 1 (which would equal the dest.) and
2964 /// the upper half to come from vector 2.
2965 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2966   int NumElems = VT.getVectorNumElements();
2967
2968   if (NumElems != 2 && NumElems != 4)
2969     return false;
2970
2971   int Half = NumElems / 2;
2972   for (int i = 0; i < Half; ++i)
2973     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2974       return false;
2975   for (int i = Half; i < NumElems; ++i)
2976     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2977       return false;
2978   return true;
2979 }
2980
2981 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2982   SmallVector<int, 8> M;
2983   N->getMask(M);
2984   return isCommutedSHUFPMask(M, N->getValueType(0));
2985 }
2986
2987 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2988 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2989 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2990   if (N->getValueType(0).getVectorNumElements() != 4)
2991     return false;
2992
2993   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2994   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2995          isUndefOrEqual(N->getMaskElt(1), 7) &&
2996          isUndefOrEqual(N->getMaskElt(2), 2) &&
2997          isUndefOrEqual(N->getMaskElt(3), 3);
2998 }
2999
3000 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3001 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3002 /// <2, 3, 2, 3>
3003 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3004   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3005   
3006   if (NumElems != 4)
3007     return false;
3008   
3009   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3010   isUndefOrEqual(N->getMaskElt(1), 3) &&
3011   isUndefOrEqual(N->getMaskElt(2), 2) &&
3012   isUndefOrEqual(N->getMaskElt(3), 3);
3013 }
3014
3015 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3016 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3017 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3018   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3019
3020   if (NumElems != 2 && NumElems != 4)
3021     return false;
3022
3023   for (unsigned i = 0; i < NumElems/2; ++i)
3024     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3025       return false;
3026
3027   for (unsigned i = NumElems/2; i < NumElems; ++i)
3028     if (!isUndefOrEqual(N->getMaskElt(i), i))
3029       return false;
3030
3031   return true;
3032 }
3033
3034 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3035 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3036 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3037   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3038
3039   if (NumElems != 2 && NumElems != 4)
3040     return false;
3041
3042   for (unsigned i = 0; i < NumElems/2; ++i)
3043     if (!isUndefOrEqual(N->getMaskElt(i), i))
3044       return false;
3045
3046   for (unsigned i = 0; i < NumElems/2; ++i)
3047     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3048       return false;
3049
3050   return true;
3051 }
3052
3053 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3054 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3055 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3056                          bool V2IsSplat = false) {
3057   int NumElts = VT.getVectorNumElements();
3058   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3059     return false;
3060
3061   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3062     int BitI  = Mask[i];
3063     int BitI1 = Mask[i+1];
3064     if (!isUndefOrEqual(BitI, j))
3065       return false;
3066     if (V2IsSplat) {
3067       if (!isUndefOrEqual(BitI1, NumElts))
3068         return false;
3069     } else {
3070       if (!isUndefOrEqual(BitI1, j + NumElts))
3071         return false;
3072     }
3073   }
3074   return true;
3075 }
3076
3077 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3078   SmallVector<int, 8> M;
3079   N->getMask(M);
3080   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3081 }
3082
3083 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3084 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3085 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3086                          bool V2IsSplat = false) {
3087   int NumElts = VT.getVectorNumElements();
3088   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3089     return false;
3090
3091   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3092     int BitI  = Mask[i];
3093     int BitI1 = Mask[i+1];
3094     if (!isUndefOrEqual(BitI, j + NumElts/2))
3095       return false;
3096     if (V2IsSplat) {
3097       if (isUndefOrEqual(BitI1, NumElts))
3098         return false;
3099     } else {
3100       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3101         return false;
3102     }
3103   }
3104   return true;
3105 }
3106
3107 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3108   SmallVector<int, 8> M;
3109   N->getMask(M);
3110   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3111 }
3112
3113 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3114 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3115 /// <0, 0, 1, 1>
3116 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3117   int NumElems = VT.getVectorNumElements();
3118   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3119     return false;
3120
3121   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3122     int BitI  = Mask[i];
3123     int BitI1 = Mask[i+1];
3124     if (!isUndefOrEqual(BitI, j))
3125       return false;
3126     if (!isUndefOrEqual(BitI1, j))
3127       return false;
3128   }
3129   return true;
3130 }
3131
3132 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3133   SmallVector<int, 8> M;
3134   N->getMask(M);
3135   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3136 }
3137
3138 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3139 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3140 /// <2, 2, 3, 3>
3141 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3142   int NumElems = VT.getVectorNumElements();
3143   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3144     return false;
3145
3146   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3147     int BitI  = Mask[i];
3148     int BitI1 = Mask[i+1];
3149     if (!isUndefOrEqual(BitI, j))
3150       return false;
3151     if (!isUndefOrEqual(BitI1, j))
3152       return false;
3153   }
3154   return true;
3155 }
3156
3157 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3158   SmallVector<int, 8> M;
3159   N->getMask(M);
3160   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3161 }
3162
3163 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3164 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3165 /// MOVSD, and MOVD, i.e. setting the lowest element.
3166 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3167   if (VT.getVectorElementType().getSizeInBits() < 32)
3168     return false;
3169
3170   int NumElts = VT.getVectorNumElements();
3171
3172   if (!isUndefOrEqual(Mask[0], NumElts))
3173     return false;
3174
3175   for (int i = 1; i < NumElts; ++i)
3176     if (!isUndefOrEqual(Mask[i], i))
3177       return false;
3178
3179   return true;
3180 }
3181
3182 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3183   SmallVector<int, 8> M;
3184   N->getMask(M);
3185   return ::isMOVLMask(M, N->getValueType(0));
3186 }
3187
3188 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3189 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3190 /// element of vector 2 and the other elements to come from vector 1 in order.
3191 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3192                                bool V2IsSplat = false, bool V2IsUndef = false) {
3193   int NumOps = VT.getVectorNumElements();
3194   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3195     return false;
3196
3197   if (!isUndefOrEqual(Mask[0], 0))
3198     return false;
3199
3200   for (int i = 1; i < NumOps; ++i)
3201     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3202           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3203           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3204       return false;
3205
3206   return true;
3207 }
3208
3209 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3210                            bool V2IsUndef = false) {
3211   SmallVector<int, 8> M;
3212   N->getMask(M);
3213   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3214 }
3215
3216 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3217 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3218 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3219   if (N->getValueType(0).getVectorNumElements() != 4)
3220     return false;
3221
3222   // Expect 1, 1, 3, 3
3223   for (unsigned i = 0; i < 2; ++i) {
3224     int Elt = N->getMaskElt(i);
3225     if (Elt >= 0 && Elt != 1)
3226       return false;
3227   }
3228
3229   bool HasHi = false;
3230   for (unsigned i = 2; i < 4; ++i) {
3231     int Elt = N->getMaskElt(i);
3232     if (Elt >= 0 && Elt != 3)
3233       return false;
3234     if (Elt == 3)
3235       HasHi = true;
3236   }
3237   // Don't use movshdup if it can be done with a shufps.
3238   // FIXME: verify that matching u, u, 3, 3 is what we want.
3239   return HasHi;
3240 }
3241
3242 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3243 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3244 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3245   if (N->getValueType(0).getVectorNumElements() != 4)
3246     return false;
3247
3248   // Expect 0, 0, 2, 2
3249   for (unsigned i = 0; i < 2; ++i)
3250     if (N->getMaskElt(i) > 0)
3251       return false;
3252
3253   bool HasHi = false;
3254   for (unsigned i = 2; i < 4; ++i) {
3255     int Elt = N->getMaskElt(i);
3256     if (Elt >= 0 && Elt != 2)
3257       return false;
3258     if (Elt == 2)
3259       HasHi = true;
3260   }
3261   // Don't use movsldup if it can be done with a shufps.
3262   return HasHi;
3263 }
3264
3265 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3266 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3267 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3268   int e = N->getValueType(0).getVectorNumElements() / 2;
3269
3270   for (int i = 0; i < e; ++i)
3271     if (!isUndefOrEqual(N->getMaskElt(i), i))
3272       return false;
3273   for (int i = 0; i < e; ++i)
3274     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3275       return false;
3276   return true;
3277 }
3278
3279 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3280 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3281 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3282   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3283   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3284
3285   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3286   unsigned Mask = 0;
3287   for (int i = 0; i < NumOperands; ++i) {
3288     int Val = SVOp->getMaskElt(NumOperands-i-1);
3289     if (Val < 0) Val = 0;
3290     if (Val >= NumOperands) Val -= NumOperands;
3291     Mask |= Val;
3292     if (i != NumOperands - 1)
3293       Mask <<= Shift;
3294   }
3295   return Mask;
3296 }
3297
3298 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3299 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3300 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3302   unsigned Mask = 0;
3303   // 8 nodes, but we only care about the last 4.
3304   for (unsigned i = 7; i >= 4; --i) {
3305     int Val = SVOp->getMaskElt(i);
3306     if (Val >= 0)
3307       Mask |= (Val - 4);
3308     if (i != 4)
3309       Mask <<= 2;
3310   }
3311   return Mask;
3312 }
3313
3314 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3315 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3316 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3317   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3318   unsigned Mask = 0;
3319   // 8 nodes, but we only care about the first 4.
3320   for (int i = 3; i >= 0; --i) {
3321     int Val = SVOp->getMaskElt(i);
3322     if (Val >= 0)
3323       Mask |= Val;
3324     if (i != 0)
3325       Mask <<= 2;
3326   }
3327   return Mask;
3328 }
3329
3330 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3331 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3332 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3333   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3334   EVT VVT = N->getValueType(0);
3335   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3336   int Val = 0;
3337
3338   unsigned i, e;
3339   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3340     Val = SVOp->getMaskElt(i);
3341     if (Val >= 0)
3342       break;
3343   }
3344   return (Val - i) * EltSize;
3345 }
3346
3347 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3348 /// constant +0.0.
3349 bool X86::isZeroNode(SDValue Elt) {
3350   return ((isa<ConstantSDNode>(Elt) &&
3351            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3352           (isa<ConstantFPSDNode>(Elt) &&
3353            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3354 }
3355
3356 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3357 /// their permute mask.
3358 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3359                                     SelectionDAG &DAG) {
3360   EVT VT = SVOp->getValueType(0);
3361   unsigned NumElems = VT.getVectorNumElements();
3362   SmallVector<int, 8> MaskVec;
3363
3364   for (unsigned i = 0; i != NumElems; ++i) {
3365     int idx = SVOp->getMaskElt(i);
3366     if (idx < 0)
3367       MaskVec.push_back(idx);
3368     else if (idx < (int)NumElems)
3369       MaskVec.push_back(idx + NumElems);
3370     else
3371       MaskVec.push_back(idx - NumElems);
3372   }
3373   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3374                               SVOp->getOperand(0), &MaskVec[0]);
3375 }
3376
3377 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3378 /// the two vector operands have swapped position.
3379 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3380   unsigned NumElems = VT.getVectorNumElements();
3381   for (unsigned i = 0; i != NumElems; ++i) {
3382     int idx = Mask[i];
3383     if (idx < 0)
3384       continue;
3385     else if (idx < (int)NumElems)
3386       Mask[i] = idx + NumElems;
3387     else
3388       Mask[i] = idx - NumElems;
3389   }
3390 }
3391
3392 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3393 /// match movhlps. The lower half elements should come from upper half of
3394 /// V1 (and in order), and the upper half elements should come from the upper
3395 /// half of V2 (and in order).
3396 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3397   if (Op->getValueType(0).getVectorNumElements() != 4)
3398     return false;
3399   for (unsigned i = 0, e = 2; i != e; ++i)
3400     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3401       return false;
3402   for (unsigned i = 2; i != 4; ++i)
3403     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3404       return false;
3405   return true;
3406 }
3407
3408 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3409 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3410 /// required.
3411 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3412   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3413     return false;
3414   N = N->getOperand(0).getNode();
3415   if (!ISD::isNON_EXTLoad(N))
3416     return false;
3417   if (LD)
3418     *LD = cast<LoadSDNode>(N);
3419   return true;
3420 }
3421
3422 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3423 /// match movlp{s|d}. The lower half elements should come from lower half of
3424 /// V1 (and in order), and the upper half elements should come from the upper
3425 /// half of V2 (and in order). And since V1 will become the source of the
3426 /// MOVLP, it must be either a vector load or a scalar load to vector.
3427 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3428                                ShuffleVectorSDNode *Op) {
3429   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3430     return false;
3431   // Is V2 is a vector load, don't do this transformation. We will try to use
3432   // load folding shufps op.
3433   if (ISD::isNON_EXTLoad(V2))
3434     return false;
3435
3436   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3437
3438   if (NumElems != 2 && NumElems != 4)
3439     return false;
3440   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3441     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3442       return false;
3443   for (unsigned i = NumElems/2; i != NumElems; ++i)
3444     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3445       return false;
3446   return true;
3447 }
3448
3449 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3450 /// all the same.
3451 static bool isSplatVector(SDNode *N) {
3452   if (N->getOpcode() != ISD::BUILD_VECTOR)
3453     return false;
3454
3455   SDValue SplatValue = N->getOperand(0);
3456   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3457     if (N->getOperand(i) != SplatValue)
3458       return false;
3459   return true;
3460 }
3461
3462 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3463 /// to an zero vector.
3464 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3465 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3466   SDValue V1 = N->getOperand(0);
3467   SDValue V2 = N->getOperand(1);
3468   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3469   for (unsigned i = 0; i != NumElems; ++i) {
3470     int Idx = N->getMaskElt(i);
3471     if (Idx >= (int)NumElems) {
3472       unsigned Opc = V2.getOpcode();
3473       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3474         continue;
3475       if (Opc != ISD::BUILD_VECTOR ||
3476           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3477         return false;
3478     } else if (Idx >= 0) {
3479       unsigned Opc = V1.getOpcode();
3480       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3481         continue;
3482       if (Opc != ISD::BUILD_VECTOR ||
3483           !X86::isZeroNode(V1.getOperand(Idx)))
3484         return false;
3485     }
3486   }
3487   return true;
3488 }
3489
3490 /// getZeroVector - Returns a vector of specified type with all zero elements.
3491 ///
3492 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3493                              DebugLoc dl) {
3494   assert(VT.isVector() && "Expected a vector type");
3495
3496   // Always build SSE zero vectors as <4 x i32> bitcasted
3497   // to their dest type. This ensures they get CSE'd.
3498   SDValue Vec;
3499   if (VT.getSizeInBits() == 128) {  // SSE
3500     if (HasSSE2) {  // SSE2
3501       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3502       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3503     } else { // SSE1
3504       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3505       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3506     }
3507   } else if (VT.getSizeInBits() == 256) { // AVX
3508     // 256-bit logic and arithmetic instructions in AVX are
3509     // all floating-point, no support for integer ops. Default
3510     // to emitting fp zeroed vectors then.
3511     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3512     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3513     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3514   }
3515   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3516 }
3517
3518 /// getOnesVector - Returns a vector of specified type with all bits set.
3519 ///
3520 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3521   assert(VT.isVector() && "Expected a vector type");
3522
3523   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3524   // type.  This ensures they get CSE'd.
3525   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3526   SDValue Vec;
3527   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3528   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3529 }
3530
3531
3532 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3533 /// that point to V2 points to its first element.
3534 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3535   EVT VT = SVOp->getValueType(0);
3536   unsigned NumElems = VT.getVectorNumElements();
3537
3538   bool Changed = false;
3539   SmallVector<int, 8> MaskVec;
3540   SVOp->getMask(MaskVec);
3541
3542   for (unsigned i = 0; i != NumElems; ++i) {
3543     if (MaskVec[i] > (int)NumElems) {
3544       MaskVec[i] = NumElems;
3545       Changed = true;
3546     }
3547   }
3548   if (Changed)
3549     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3550                                 SVOp->getOperand(1), &MaskVec[0]);
3551   return SDValue(SVOp, 0);
3552 }
3553
3554 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3555 /// operation of specified width.
3556 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3557                        SDValue V2) {
3558   unsigned NumElems = VT.getVectorNumElements();
3559   SmallVector<int, 8> Mask;
3560   Mask.push_back(NumElems);
3561   for (unsigned i = 1; i != NumElems; ++i)
3562     Mask.push_back(i);
3563   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3564 }
3565
3566 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3567 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3568                           SDValue V2) {
3569   unsigned NumElems = VT.getVectorNumElements();
3570   SmallVector<int, 8> Mask;
3571   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3572     Mask.push_back(i);
3573     Mask.push_back(i + NumElems);
3574   }
3575   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3576 }
3577
3578 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3579 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3580                           SDValue V2) {
3581   unsigned NumElems = VT.getVectorNumElements();
3582   unsigned Half = NumElems/2;
3583   SmallVector<int, 8> Mask;
3584   for (unsigned i = 0; i != Half; ++i) {
3585     Mask.push_back(i + Half);
3586     Mask.push_back(i + NumElems + Half);
3587   }
3588   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3589 }
3590
3591 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3592 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3593   EVT PVT = MVT::v4f32;
3594   EVT VT = SV->getValueType(0);
3595   DebugLoc dl = SV->getDebugLoc();
3596   SDValue V1 = SV->getOperand(0);
3597   int NumElems = VT.getVectorNumElements();
3598   int EltNo = SV->getSplatIndex();
3599
3600   // unpack elements to the correct location
3601   while (NumElems > 4) {
3602     if (EltNo < NumElems/2) {
3603       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3604     } else {
3605       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3606       EltNo -= NumElems/2;
3607     }
3608     NumElems >>= 1;
3609   }
3610
3611   // Perform the splat.
3612   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3613   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3614   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3615   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3616 }
3617
3618 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3619 /// vector of zero or undef vector.  This produces a shuffle where the low
3620 /// element of V2 is swizzled into the zero/undef vector, landing at element
3621 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3622 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3623                                              bool isZero, bool HasSSE2,
3624                                              SelectionDAG &DAG) {
3625   EVT VT = V2.getValueType();
3626   SDValue V1 = isZero
3627     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3628   unsigned NumElems = VT.getVectorNumElements();
3629   SmallVector<int, 16> MaskVec;
3630   for (unsigned i = 0; i != NumElems; ++i)
3631     // If this is the insertion idx, put the low elt of V2 here.
3632     MaskVec.push_back(i == Idx ? NumElems : i);
3633   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3634 }
3635
3636 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3637 /// element of the result of the vector shuffle.
3638 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3639                             unsigned Depth) {
3640   if (Depth == 6)
3641     return SDValue();  // Limit search depth.
3642
3643   SDValue V = SDValue(N, 0);
3644   EVT VT = V.getValueType();
3645   unsigned Opcode = V.getOpcode();
3646
3647   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3648   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3649     Index = SV->getMaskElt(Index);
3650
3651     if (Index < 0)
3652       return DAG.getUNDEF(VT.getVectorElementType());
3653
3654     int NumElems = VT.getVectorNumElements();
3655     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3656     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3657   }
3658
3659   // Recurse into target specific vector shuffles to find scalars.
3660   if (isTargetShuffle(Opcode)) {
3661     int NumElems = VT.getVectorNumElements();
3662     SmallVector<unsigned, 16> ShuffleMask;
3663     SDValue ImmN;
3664
3665     switch(Opcode) {
3666     case X86ISD::SHUFPS:
3667     case X86ISD::SHUFPD:
3668       ImmN = N->getOperand(N->getNumOperands()-1);
3669       DecodeSHUFPSMask(NumElems,
3670                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3671                        ShuffleMask);
3672       break;
3673     case X86ISD::PUNPCKHBW:
3674     case X86ISD::PUNPCKHWD:
3675     case X86ISD::PUNPCKHDQ:
3676     case X86ISD::PUNPCKHQDQ:
3677       DecodePUNPCKHMask(NumElems, ShuffleMask);
3678       break;
3679     case X86ISD::UNPCKHPS:
3680     case X86ISD::UNPCKHPD:
3681       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3682       break;
3683     case X86ISD::PUNPCKLBW:
3684     case X86ISD::PUNPCKLWD:
3685     case X86ISD::PUNPCKLDQ:
3686     case X86ISD::PUNPCKLQDQ:
3687       DecodePUNPCKLMask(NumElems, ShuffleMask);
3688       break;
3689     case X86ISD::UNPCKLPS:
3690     case X86ISD::UNPCKLPD:
3691       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3692       break;
3693     case X86ISD::MOVHLPS:
3694       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3695       break;
3696     case X86ISD::MOVLHPS:
3697       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3698       break;
3699     case X86ISD::PSHUFD:
3700       ImmN = N->getOperand(N->getNumOperands()-1);
3701       DecodePSHUFMask(NumElems,
3702                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3703                       ShuffleMask);
3704       break;
3705     case X86ISD::PSHUFHW:
3706       ImmN = N->getOperand(N->getNumOperands()-1);
3707       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3708                         ShuffleMask);
3709       break;
3710     case X86ISD::PSHUFLW:
3711       ImmN = N->getOperand(N->getNumOperands()-1);
3712       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3713                         ShuffleMask);
3714       break;
3715     case X86ISD::MOVSS:
3716     case X86ISD::MOVSD: {
3717       // The index 0 always comes from the first element of the second source,
3718       // this is why MOVSS and MOVSD are used in the first place. The other
3719       // elements come from the other positions of the first source vector.
3720       unsigned OpNum = (Index == 0) ? 1 : 0;
3721       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3722                                  Depth+1);
3723     }
3724     default:
3725       assert("not implemented for target shuffle node");
3726       return SDValue();
3727     }
3728
3729     Index = ShuffleMask[Index];
3730     if (Index < 0)
3731       return DAG.getUNDEF(VT.getVectorElementType());
3732
3733     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3734     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3735                                Depth+1);
3736   }
3737
3738   // Actual nodes that may contain scalar elements
3739   if (Opcode == ISD::BIT_CONVERT) {
3740     V = V.getOperand(0);
3741     EVT SrcVT = V.getValueType();
3742     unsigned NumElems = VT.getVectorNumElements();
3743
3744     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3745       return SDValue();
3746   }
3747
3748   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3749     return (Index == 0) ? V.getOperand(0)
3750                           : DAG.getUNDEF(VT.getVectorElementType());
3751
3752   if (V.getOpcode() == ISD::BUILD_VECTOR)
3753     return V.getOperand(Index);
3754
3755   return SDValue();
3756 }
3757
3758 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3759 /// shuffle operation which come from a consecutively from a zero. The
3760 /// search can start in two diferent directions, from left or right.
3761 static
3762 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3763                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3764   int i = 0;
3765
3766   while (i < NumElems) {
3767     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3768     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3769     if (!(Elt.getNode() &&
3770          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3771       break;
3772     ++i;
3773   }
3774
3775   return i;
3776 }
3777
3778 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3779 /// MaskE correspond consecutively to elements from one of the vector operands,
3780 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3781 static
3782 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3783                               int OpIdx, int NumElems, unsigned &OpNum) {
3784   bool SeenV1 = false;
3785   bool SeenV2 = false;
3786
3787   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3788     int Idx = SVOp->getMaskElt(i);
3789     // Ignore undef indicies
3790     if (Idx < 0)
3791       continue;
3792
3793     if (Idx < NumElems)
3794       SeenV1 = true;
3795     else
3796       SeenV2 = true;
3797
3798     // Only accept consecutive elements from the same vector
3799     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3800       return false;
3801   }
3802
3803   OpNum = SeenV1 ? 0 : 1;
3804   return true;
3805 }
3806
3807 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3808 /// logical left shift of a vector.
3809 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3810                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3811   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3812   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3813               false /* check zeros from right */, DAG);
3814   unsigned OpSrc;
3815
3816   if (!NumZeros)
3817     return false;
3818
3819   // Considering the elements in the mask that are not consecutive zeros,
3820   // check if they consecutively come from only one of the source vectors.
3821   //
3822   //               V1 = {X, A, B, C}     0
3823   //                         \  \  \    /
3824   //   vector_shuffle V1, V2 <1, 2, 3, X>
3825   //
3826   if (!isShuffleMaskConsecutive(SVOp,
3827             0,                   // Mask Start Index
3828             NumElems-NumZeros-1, // Mask End Index
3829             NumZeros,            // Where to start looking in the src vector
3830             NumElems,            // Number of elements in vector
3831             OpSrc))              // Which source operand ?
3832     return false;
3833
3834   isLeft = false;
3835   ShAmt = NumZeros;
3836   ShVal = SVOp->getOperand(OpSrc);
3837   return true;
3838 }
3839
3840 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3841 /// logical left shift of a vector.
3842 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3843                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3844   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3845   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3846               true /* check zeros from left */, DAG);
3847   unsigned OpSrc;
3848
3849   if (!NumZeros)
3850     return false;
3851
3852   // Considering the elements in the mask that are not consecutive zeros,
3853   // check if they consecutively come from only one of the source vectors.
3854   //
3855   //                           0    { A, B, X, X } = V2
3856   //                          / \    /  /
3857   //   vector_shuffle V1, V2 <X, X, 4, 5>
3858   //
3859   if (!isShuffleMaskConsecutive(SVOp,
3860             NumZeros,     // Mask Start Index
3861             NumElems-1,   // Mask End Index
3862             0,            // Where to start looking in the src vector
3863             NumElems,     // Number of elements in vector
3864             OpSrc))       // Which source operand ?
3865     return false;
3866
3867   isLeft = true;
3868   ShAmt = NumZeros;
3869   ShVal = SVOp->getOperand(OpSrc);
3870   return true;
3871 }
3872
3873 /// isVectorShift - Returns true if the shuffle can be implemented as a
3874 /// logical left or right shift of a vector.
3875 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3876                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3877   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3878       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3879     return true;
3880
3881   return false;
3882 }
3883
3884 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3885 ///
3886 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3887                                        unsigned NumNonZero, unsigned NumZero,
3888                                        SelectionDAG &DAG,
3889                                        const TargetLowering &TLI) {
3890   if (NumNonZero > 8)
3891     return SDValue();
3892
3893   DebugLoc dl = Op.getDebugLoc();
3894   SDValue V(0, 0);
3895   bool First = true;
3896   for (unsigned i = 0; i < 16; ++i) {
3897     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3898     if (ThisIsNonZero && First) {
3899       if (NumZero)
3900         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3901       else
3902         V = DAG.getUNDEF(MVT::v8i16);
3903       First = false;
3904     }
3905
3906     if ((i & 1) != 0) {
3907       SDValue ThisElt(0, 0), LastElt(0, 0);
3908       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3909       if (LastIsNonZero) {
3910         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3911                               MVT::i16, Op.getOperand(i-1));
3912       }
3913       if (ThisIsNonZero) {
3914         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3915         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3916                               ThisElt, DAG.getConstant(8, MVT::i8));
3917         if (LastIsNonZero)
3918           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3919       } else
3920         ThisElt = LastElt;
3921
3922       if (ThisElt.getNode())
3923         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3924                         DAG.getIntPtrConstant(i/2));
3925     }
3926   }
3927
3928   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3929 }
3930
3931 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3932 ///
3933 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3934                                      unsigned NumNonZero, unsigned NumZero,
3935                                      SelectionDAG &DAG,
3936                                      const TargetLowering &TLI) {
3937   if (NumNonZero > 4)
3938     return SDValue();
3939
3940   DebugLoc dl = Op.getDebugLoc();
3941   SDValue V(0, 0);
3942   bool First = true;
3943   for (unsigned i = 0; i < 8; ++i) {
3944     bool isNonZero = (NonZeros & (1 << i)) != 0;
3945     if (isNonZero) {
3946       if (First) {
3947         if (NumZero)
3948           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3949         else
3950           V = DAG.getUNDEF(MVT::v8i16);
3951         First = false;
3952       }
3953       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3954                       MVT::v8i16, V, Op.getOperand(i),
3955                       DAG.getIntPtrConstant(i));
3956     }
3957   }
3958
3959   return V;
3960 }
3961
3962 /// getVShift - Return a vector logical shift node.
3963 ///
3964 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3965                          unsigned NumBits, SelectionDAG &DAG,
3966                          const TargetLowering &TLI, DebugLoc dl) {
3967   EVT ShVT = MVT::v2i64;
3968   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3969   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3970   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3971                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3972                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3973 }
3974
3975 SDValue
3976 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3977                                           SelectionDAG &DAG) const {
3978   
3979   // Check if the scalar load can be widened into a vector load. And if
3980   // the address is "base + cst" see if the cst can be "absorbed" into
3981   // the shuffle mask.
3982   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3983     SDValue Ptr = LD->getBasePtr();
3984     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3985       return SDValue();
3986     EVT PVT = LD->getValueType(0);
3987     if (PVT != MVT::i32 && PVT != MVT::f32)
3988       return SDValue();
3989
3990     int FI = -1;
3991     int64_t Offset = 0;
3992     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3993       FI = FINode->getIndex();
3994       Offset = 0;
3995     } else if (Ptr.getOpcode() == ISD::ADD &&
3996                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3997                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3998       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3999       Offset = Ptr.getConstantOperandVal(1);
4000       Ptr = Ptr.getOperand(0);
4001     } else {
4002       return SDValue();
4003     }
4004
4005     SDValue Chain = LD->getChain();
4006     // Make sure the stack object alignment is at least 16.
4007     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4008     if (DAG.InferPtrAlignment(Ptr) < 16) {
4009       if (MFI->isFixedObjectIndex(FI)) {
4010         // Can't change the alignment. FIXME: It's possible to compute
4011         // the exact stack offset and reference FI + adjust offset instead.
4012         // If someone *really* cares about this. That's the way to implement it.
4013         return SDValue();
4014       } else {
4015         MFI->setObjectAlignment(FI, 16);
4016       }
4017     }
4018
4019     // (Offset % 16) must be multiple of 4. Then address is then
4020     // Ptr + (Offset & ~15).
4021     if (Offset < 0)
4022       return SDValue();
4023     if ((Offset % 16) & 3)
4024       return SDValue();
4025     int64_t StartOffset = Offset & ~15;
4026     if (StartOffset)
4027       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4028                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4029
4030     int EltNo = (Offset - StartOffset) >> 2;
4031     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4032     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4033     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4034                              LD->getPointerInfo().getWithOffset(StartOffset),
4035                              false, false, 0);
4036     // Canonicalize it to a v4i32 shuffle.
4037     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4038     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4039                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4040                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4041   }
4042
4043   return SDValue();
4044 }
4045
4046 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
4047 /// vector of type 'VT', see if the elements can be replaced by a single large 
4048 /// load which has the same value as a build_vector whose operands are 'elts'.
4049 ///
4050 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4051 /// 
4052 /// FIXME: we'd also like to handle the case where the last elements are zero
4053 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4054 /// There's even a handy isZeroNode for that purpose.
4055 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4056                                         DebugLoc &DL, SelectionDAG &DAG) {
4057   EVT EltVT = VT.getVectorElementType();
4058   unsigned NumElems = Elts.size();
4059   
4060   LoadSDNode *LDBase = NULL;
4061   unsigned LastLoadedElt = -1U;
4062   
4063   // For each element in the initializer, see if we've found a load or an undef.
4064   // If we don't find an initial load element, or later load elements are 
4065   // non-consecutive, bail out.
4066   for (unsigned i = 0; i < NumElems; ++i) {
4067     SDValue Elt = Elts[i];
4068     
4069     if (!Elt.getNode() ||
4070         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4071       return SDValue();
4072     if (!LDBase) {
4073       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4074         return SDValue();
4075       LDBase = cast<LoadSDNode>(Elt.getNode());
4076       LastLoadedElt = i;
4077       continue;
4078     }
4079     if (Elt.getOpcode() == ISD::UNDEF)
4080       continue;
4081
4082     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4083     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4084       return SDValue();
4085     LastLoadedElt = i;
4086   }
4087
4088   // If we have found an entire vector of loads and undefs, then return a large
4089   // load of the entire vector width starting at the base pointer.  If we found
4090   // consecutive loads for the low half, generate a vzext_load node.
4091   if (LastLoadedElt == NumElems - 1) {
4092     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4093       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4094                          LDBase->getPointerInfo(),
4095                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4096     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4097                        LDBase->getPointerInfo(),
4098                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4099                        LDBase->getAlignment());
4100   } else if (NumElems == 4 && LastLoadedElt == 1) {
4101     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4102     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4103     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4104                                               Ops, 2, MVT::i32,
4105                                               LDBase->getMemOperand());
4106     return DAG.getNode(ISD::BIT_CONVERT, DL, VT, ResNode);
4107   }
4108   return SDValue();
4109 }
4110
4111 SDValue
4112 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4113   DebugLoc dl = Op.getDebugLoc();
4114   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4115   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4116   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4117   // is present, so AllOnes is ignored.
4118   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4119       (Op.getValueType().getSizeInBits() != 256 &&
4120        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4121     // Canonicalize this to <4 x i32> (SSE) to
4122     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4123     // eliminated on x86-32 hosts.
4124     if (Op.getValueType() == MVT::v4i32)
4125       return Op;
4126
4127     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4128       return getOnesVector(Op.getValueType(), DAG, dl);
4129     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4130   }
4131
4132   EVT VT = Op.getValueType();
4133   EVT ExtVT = VT.getVectorElementType();
4134   unsigned EVTBits = ExtVT.getSizeInBits();
4135
4136   unsigned NumElems = Op.getNumOperands();
4137   unsigned NumZero  = 0;
4138   unsigned NumNonZero = 0;
4139   unsigned NonZeros = 0;
4140   bool IsAllConstants = true;
4141   SmallSet<SDValue, 8> Values;
4142   for (unsigned i = 0; i < NumElems; ++i) {
4143     SDValue Elt = Op.getOperand(i);
4144     if (Elt.getOpcode() == ISD::UNDEF)
4145       continue;
4146     Values.insert(Elt);
4147     if (Elt.getOpcode() != ISD::Constant &&
4148         Elt.getOpcode() != ISD::ConstantFP)
4149       IsAllConstants = false;
4150     if (X86::isZeroNode(Elt))
4151       NumZero++;
4152     else {
4153       NonZeros |= (1 << i);
4154       NumNonZero++;
4155     }
4156   }
4157
4158   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4159   if (NumNonZero == 0)
4160     return DAG.getUNDEF(VT);
4161
4162   // Special case for single non-zero, non-undef, element.
4163   if (NumNonZero == 1) {
4164     unsigned Idx = CountTrailingZeros_32(NonZeros);
4165     SDValue Item = Op.getOperand(Idx);
4166
4167     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4168     // the value are obviously zero, truncate the value to i32 and do the
4169     // insertion that way.  Only do this if the value is non-constant or if the
4170     // value is a constant being inserted into element 0.  It is cheaper to do
4171     // a constant pool load than it is to do a movd + shuffle.
4172     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4173         (!IsAllConstants || Idx == 0)) {
4174       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4175         // Handle SSE only.
4176         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4177         EVT VecVT = MVT::v4i32;
4178         unsigned VecElts = 4;
4179
4180         // Truncate the value (which may itself be a constant) to i32, and
4181         // convert it to a vector with movd (S2V+shuffle to zero extend).
4182         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4183         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4184         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4185                                            Subtarget->hasSSE2(), DAG);
4186
4187         // Now we have our 32-bit value zero extended in the low element of
4188         // a vector.  If Idx != 0, swizzle it into place.
4189         if (Idx != 0) {
4190           SmallVector<int, 4> Mask;
4191           Mask.push_back(Idx);
4192           for (unsigned i = 1; i != VecElts; ++i)
4193             Mask.push_back(i);
4194           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4195                                       DAG.getUNDEF(Item.getValueType()),
4196                                       &Mask[0]);
4197         }
4198         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4199       }
4200     }
4201
4202     // If we have a constant or non-constant insertion into the low element of
4203     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4204     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4205     // depending on what the source datatype is.
4206     if (Idx == 0) {
4207       if (NumZero == 0) {
4208         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4209       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4210           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4211         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4212         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4213         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4214                                            DAG);
4215       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4216         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4217         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4218         EVT MiddleVT = MVT::v4i32;
4219         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4220         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4221                                            Subtarget->hasSSE2(), DAG);
4222         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4223       }
4224     }
4225
4226     // Is it a vector logical left shift?
4227     if (NumElems == 2 && Idx == 1 &&
4228         X86::isZeroNode(Op.getOperand(0)) &&
4229         !X86::isZeroNode(Op.getOperand(1))) {
4230       unsigned NumBits = VT.getSizeInBits();
4231       return getVShift(true, VT,
4232                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4233                                    VT, Op.getOperand(1)),
4234                        NumBits/2, DAG, *this, dl);
4235     }
4236
4237     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4238       return SDValue();
4239
4240     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4241     // is a non-constant being inserted into an element other than the low one,
4242     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4243     // movd/movss) to move this into the low element, then shuffle it into
4244     // place.
4245     if (EVTBits == 32) {
4246       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4247
4248       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4249       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4250                                          Subtarget->hasSSE2(), DAG);
4251       SmallVector<int, 8> MaskVec;
4252       for (unsigned i = 0; i < NumElems; i++)
4253         MaskVec.push_back(i == Idx ? 0 : 1);
4254       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4255     }
4256   }
4257
4258   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4259   if (Values.size() == 1) {
4260     if (EVTBits == 32) {
4261       // Instead of a shuffle like this:
4262       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4263       // Check if it's possible to issue this instead.
4264       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4265       unsigned Idx = CountTrailingZeros_32(NonZeros);
4266       SDValue Item = Op.getOperand(Idx);
4267       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4268         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4269     }
4270     return SDValue();
4271   }
4272
4273   // A vector full of immediates; various special cases are already
4274   // handled, so this is best done with a single constant-pool load.
4275   if (IsAllConstants)
4276     return SDValue();
4277
4278   // Let legalizer expand 2-wide build_vectors.
4279   if (EVTBits == 64) {
4280     if (NumNonZero == 1) {
4281       // One half is zero or undef.
4282       unsigned Idx = CountTrailingZeros_32(NonZeros);
4283       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4284                                  Op.getOperand(Idx));
4285       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4286                                          Subtarget->hasSSE2(), DAG);
4287     }
4288     return SDValue();
4289   }
4290
4291   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4292   if (EVTBits == 8 && NumElems == 16) {
4293     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4294                                         *this);
4295     if (V.getNode()) return V;
4296   }
4297
4298   if (EVTBits == 16 && NumElems == 8) {
4299     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4300                                       *this);
4301     if (V.getNode()) return V;
4302   }
4303
4304   // If element VT is == 32 bits, turn it into a number of shuffles.
4305   SmallVector<SDValue, 8> V;
4306   V.resize(NumElems);
4307   if (NumElems == 4 && NumZero > 0) {
4308     for (unsigned i = 0; i < 4; ++i) {
4309       bool isZero = !(NonZeros & (1 << i));
4310       if (isZero)
4311         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4312       else
4313         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4314     }
4315
4316     for (unsigned i = 0; i < 2; ++i) {
4317       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4318         default: break;
4319         case 0:
4320           V[i] = V[i*2];  // Must be a zero vector.
4321           break;
4322         case 1:
4323           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4324           break;
4325         case 2:
4326           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4327           break;
4328         case 3:
4329           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4330           break;
4331       }
4332     }
4333
4334     SmallVector<int, 8> MaskVec;
4335     bool Reverse = (NonZeros & 0x3) == 2;
4336     for (unsigned i = 0; i < 2; ++i)
4337       MaskVec.push_back(Reverse ? 1-i : i);
4338     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4339     for (unsigned i = 0; i < 2; ++i)
4340       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4341     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4342   }
4343
4344   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4345     // Check for a build vector of consecutive loads.
4346     for (unsigned i = 0; i < NumElems; ++i)
4347       V[i] = Op.getOperand(i);
4348     
4349     // Check for elements which are consecutive loads.
4350     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4351     if (LD.getNode())
4352       return LD;
4353     
4354     // For SSE 4.1, use insertps to put the high elements into the low element. 
4355     if (getSubtarget()->hasSSE41()) {
4356       SDValue Result;
4357       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4358         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4359       else
4360         Result = DAG.getUNDEF(VT);
4361       
4362       for (unsigned i = 1; i < NumElems; ++i) {
4363         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4364         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4365                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4366       }
4367       return Result;
4368     }
4369     
4370     // Otherwise, expand into a number of unpckl*, start by extending each of
4371     // our (non-undef) elements to the full vector width with the element in the
4372     // bottom slot of the vector (which generates no code for SSE).
4373     for (unsigned i = 0; i < NumElems; ++i) {
4374       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4375         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4376       else
4377         V[i] = DAG.getUNDEF(VT);
4378     }
4379
4380     // Next, we iteratively mix elements, e.g. for v4f32:
4381     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4382     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4383     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4384     unsigned EltStride = NumElems >> 1;
4385     while (EltStride != 0) {
4386       for (unsigned i = 0; i < EltStride; ++i) {
4387         // If V[i+EltStride] is undef and this is the first round of mixing,
4388         // then it is safe to just drop this shuffle: V[i] is already in the
4389         // right place, the one element (since it's the first round) being
4390         // inserted as undef can be dropped.  This isn't safe for successive
4391         // rounds because they will permute elements within both vectors.
4392         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4393             EltStride == NumElems/2)
4394           continue;
4395         
4396         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4397       }
4398       EltStride >>= 1;
4399     }
4400     return V[0];
4401   }
4402   return SDValue();
4403 }
4404
4405 SDValue
4406 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4407   // We support concatenate two MMX registers and place them in a MMX
4408   // register.  This is better than doing a stack convert.
4409   DebugLoc dl = Op.getDebugLoc();
4410   EVT ResVT = Op.getValueType();
4411   assert(Op.getNumOperands() == 2);
4412   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4413          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4414   int Mask[2];
4415   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4416   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4417   InVec = Op.getOperand(1);
4418   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4419     unsigned NumElts = ResVT.getVectorNumElements();
4420     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4421     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4422                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4423   } else {
4424     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4425     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4426     Mask[0] = 0; Mask[1] = 2;
4427     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4428   }
4429   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4430 }
4431
4432 // v8i16 shuffles - Prefer shuffles in the following order:
4433 // 1. [all]   pshuflw, pshufhw, optional move
4434 // 2. [ssse3] 1 x pshufb
4435 // 3. [ssse3] 2 x pshufb + 1 x por
4436 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4437 SDValue
4438 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4439                                             SelectionDAG &DAG) const {
4440   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4441   SDValue V1 = SVOp->getOperand(0);
4442   SDValue V2 = SVOp->getOperand(1);
4443   DebugLoc dl = SVOp->getDebugLoc();
4444   SmallVector<int, 8> MaskVals;
4445
4446   // Determine if more than 1 of the words in each of the low and high quadwords
4447   // of the result come from the same quadword of one of the two inputs.  Undef
4448   // mask values count as coming from any quadword, for better codegen.
4449   SmallVector<unsigned, 4> LoQuad(4);
4450   SmallVector<unsigned, 4> HiQuad(4);
4451   BitVector InputQuads(4);
4452   for (unsigned i = 0; i < 8; ++i) {
4453     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4454     int EltIdx = SVOp->getMaskElt(i);
4455     MaskVals.push_back(EltIdx);
4456     if (EltIdx < 0) {
4457       ++Quad[0];
4458       ++Quad[1];
4459       ++Quad[2];
4460       ++Quad[3];
4461       continue;
4462     }
4463     ++Quad[EltIdx / 4];
4464     InputQuads.set(EltIdx / 4);
4465   }
4466
4467   int BestLoQuad = -1;
4468   unsigned MaxQuad = 1;
4469   for (unsigned i = 0; i < 4; ++i) {
4470     if (LoQuad[i] > MaxQuad) {
4471       BestLoQuad = i;
4472       MaxQuad = LoQuad[i];
4473     }
4474   }
4475
4476   int BestHiQuad = -1;
4477   MaxQuad = 1;
4478   for (unsigned i = 0; i < 4; ++i) {
4479     if (HiQuad[i] > MaxQuad) {
4480       BestHiQuad = i;
4481       MaxQuad = HiQuad[i];
4482     }
4483   }
4484
4485   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4486   // of the two input vectors, shuffle them into one input vector so only a
4487   // single pshufb instruction is necessary. If There are more than 2 input
4488   // quads, disable the next transformation since it does not help SSSE3.
4489   bool V1Used = InputQuads[0] || InputQuads[1];
4490   bool V2Used = InputQuads[2] || InputQuads[3];
4491   if (Subtarget->hasSSSE3()) {
4492     if (InputQuads.count() == 2 && V1Used && V2Used) {
4493       BestLoQuad = InputQuads.find_first();
4494       BestHiQuad = InputQuads.find_next(BestLoQuad);
4495     }
4496     if (InputQuads.count() > 2) {
4497       BestLoQuad = -1;
4498       BestHiQuad = -1;
4499     }
4500   }
4501
4502   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4503   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4504   // words from all 4 input quadwords.
4505   SDValue NewV;
4506   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4507     SmallVector<int, 8> MaskV;
4508     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4509     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4510     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4511                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4512                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4513     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4514
4515     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4516     // source words for the shuffle, to aid later transformations.
4517     bool AllWordsInNewV = true;
4518     bool InOrder[2] = { true, true };
4519     for (unsigned i = 0; i != 8; ++i) {
4520       int idx = MaskVals[i];
4521       if (idx != (int)i)
4522         InOrder[i/4] = false;
4523       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4524         continue;
4525       AllWordsInNewV = false;
4526       break;
4527     }
4528
4529     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4530     if (AllWordsInNewV) {
4531       for (int i = 0; i != 8; ++i) {
4532         int idx = MaskVals[i];
4533         if (idx < 0)
4534           continue;
4535         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4536         if ((idx != i) && idx < 4)
4537           pshufhw = false;
4538         if ((idx != i) && idx > 3)
4539           pshuflw = false;
4540       }
4541       V1 = NewV;
4542       V2Used = false;
4543       BestLoQuad = 0;
4544       BestHiQuad = 1;
4545     }
4546
4547     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4548     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4549     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4550       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4551       unsigned TargetMask = 0;
4552       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4553                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4554       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4555                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4556       V1 = NewV.getOperand(0);
4557       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4558     }
4559   }
4560
4561   // If we have SSSE3, and all words of the result are from 1 input vector,
4562   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4563   // is present, fall back to case 4.
4564   if (Subtarget->hasSSSE3()) {
4565     SmallVector<SDValue,16> pshufbMask;
4566
4567     // If we have elements from both input vectors, set the high bit of the
4568     // shuffle mask element to zero out elements that come from V2 in the V1
4569     // mask, and elements that come from V1 in the V2 mask, so that the two
4570     // results can be OR'd together.
4571     bool TwoInputs = V1Used && V2Used;
4572     for (unsigned i = 0; i != 8; ++i) {
4573       int EltIdx = MaskVals[i] * 2;
4574       if (TwoInputs && (EltIdx >= 16)) {
4575         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4576         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4577         continue;
4578       }
4579       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4580       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4581     }
4582     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4583     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4584                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4585                                  MVT::v16i8, &pshufbMask[0], 16));
4586     if (!TwoInputs)
4587       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4588
4589     // Calculate the shuffle mask for the second input, shuffle it, and
4590     // OR it with the first shuffled input.
4591     pshufbMask.clear();
4592     for (unsigned i = 0; i != 8; ++i) {
4593       int EltIdx = MaskVals[i] * 2;
4594       if (EltIdx < 16) {
4595         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4596         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4597         continue;
4598       }
4599       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4600       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4601     }
4602     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4603     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4604                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4605                                  MVT::v16i8, &pshufbMask[0], 16));
4606     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4607     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4608   }
4609
4610   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4611   // and update MaskVals with new element order.
4612   BitVector InOrder(8);
4613   if (BestLoQuad >= 0) {
4614     SmallVector<int, 8> MaskV;
4615     for (int i = 0; i != 4; ++i) {
4616       int idx = MaskVals[i];
4617       if (idx < 0) {
4618         MaskV.push_back(-1);
4619         InOrder.set(i);
4620       } else if ((idx / 4) == BestLoQuad) {
4621         MaskV.push_back(idx & 3);
4622         InOrder.set(i);
4623       } else {
4624         MaskV.push_back(-1);
4625       }
4626     }
4627     for (unsigned i = 4; i != 8; ++i)
4628       MaskV.push_back(i);
4629     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4630                                 &MaskV[0]);
4631
4632     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4633       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4634                                NewV.getOperand(0),
4635                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4636                                DAG);
4637   }
4638
4639   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4640   // and update MaskVals with the new element order.
4641   if (BestHiQuad >= 0) {
4642     SmallVector<int, 8> MaskV;
4643     for (unsigned i = 0; i != 4; ++i)
4644       MaskV.push_back(i);
4645     for (unsigned i = 4; i != 8; ++i) {
4646       int idx = MaskVals[i];
4647       if (idx < 0) {
4648         MaskV.push_back(-1);
4649         InOrder.set(i);
4650       } else if ((idx / 4) == BestHiQuad) {
4651         MaskV.push_back((idx & 3) + 4);
4652         InOrder.set(i);
4653       } else {
4654         MaskV.push_back(-1);
4655       }
4656     }
4657     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4658                                 &MaskV[0]);
4659
4660     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4661       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4662                               NewV.getOperand(0),
4663                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4664                               DAG);
4665   }
4666
4667   // In case BestHi & BestLo were both -1, which means each quadword has a word
4668   // from each of the four input quadwords, calculate the InOrder bitvector now
4669   // before falling through to the insert/extract cleanup.
4670   if (BestLoQuad == -1 && BestHiQuad == -1) {
4671     NewV = V1;
4672     for (int i = 0; i != 8; ++i)
4673       if (MaskVals[i] < 0 || MaskVals[i] == i)
4674         InOrder.set(i);
4675   }
4676
4677   // The other elements are put in the right place using pextrw and pinsrw.
4678   for (unsigned i = 0; i != 8; ++i) {
4679     if (InOrder[i])
4680       continue;
4681     int EltIdx = MaskVals[i];
4682     if (EltIdx < 0)
4683       continue;
4684     SDValue ExtOp = (EltIdx < 8)
4685     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4686                   DAG.getIntPtrConstant(EltIdx))
4687     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4688                   DAG.getIntPtrConstant(EltIdx - 8));
4689     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4690                        DAG.getIntPtrConstant(i));
4691   }
4692   return NewV;
4693 }
4694
4695 // v16i8 shuffles - Prefer shuffles in the following order:
4696 // 1. [ssse3] 1 x pshufb
4697 // 2. [ssse3] 2 x pshufb + 1 x por
4698 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4699 static
4700 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4701                                  SelectionDAG &DAG,
4702                                  const X86TargetLowering &TLI) {
4703   SDValue V1 = SVOp->getOperand(0);
4704   SDValue V2 = SVOp->getOperand(1);
4705   DebugLoc dl = SVOp->getDebugLoc();
4706   SmallVector<int, 16> MaskVals;
4707   SVOp->getMask(MaskVals);
4708
4709   // If we have SSSE3, case 1 is generated when all result bytes come from
4710   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4711   // present, fall back to case 3.
4712   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4713   bool V1Only = true;
4714   bool V2Only = true;
4715   for (unsigned i = 0; i < 16; ++i) {
4716     int EltIdx = MaskVals[i];
4717     if (EltIdx < 0)
4718       continue;
4719     if (EltIdx < 16)
4720       V2Only = false;
4721     else
4722       V1Only = false;
4723   }
4724
4725   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4726   if (TLI.getSubtarget()->hasSSSE3()) {
4727     SmallVector<SDValue,16> pshufbMask;
4728
4729     // If all result elements are from one input vector, then only translate
4730     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4731     //
4732     // Otherwise, we have elements from both input vectors, and must zero out
4733     // elements that come from V2 in the first mask, and V1 in the second mask
4734     // so that we can OR them together.
4735     bool TwoInputs = !(V1Only || V2Only);
4736     for (unsigned i = 0; i != 16; ++i) {
4737       int EltIdx = MaskVals[i];
4738       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4739         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4740         continue;
4741       }
4742       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4743     }
4744     // If all the elements are from V2, assign it to V1 and return after
4745     // building the first pshufb.
4746     if (V2Only)
4747       V1 = V2;
4748     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4749                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4750                                  MVT::v16i8, &pshufbMask[0], 16));
4751     if (!TwoInputs)
4752       return V1;
4753
4754     // Calculate the shuffle mask for the second input, shuffle it, and
4755     // OR it with the first shuffled input.
4756     pshufbMask.clear();
4757     for (unsigned i = 0; i != 16; ++i) {
4758       int EltIdx = MaskVals[i];
4759       if (EltIdx < 16) {
4760         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4761         continue;
4762       }
4763       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4764     }
4765     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4766                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4767                                  MVT::v16i8, &pshufbMask[0], 16));
4768     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4769   }
4770
4771   // No SSSE3 - Calculate in place words and then fix all out of place words
4772   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4773   // the 16 different words that comprise the two doublequadword input vectors.
4774   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4775   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4776   SDValue NewV = V2Only ? V2 : V1;
4777   for (int i = 0; i != 8; ++i) {
4778     int Elt0 = MaskVals[i*2];
4779     int Elt1 = MaskVals[i*2+1];
4780
4781     // This word of the result is all undef, skip it.
4782     if (Elt0 < 0 && Elt1 < 0)
4783       continue;
4784
4785     // This word of the result is already in the correct place, skip it.
4786     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4787       continue;
4788     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4789       continue;
4790
4791     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4792     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4793     SDValue InsElt;
4794
4795     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4796     // using a single extract together, load it and store it.
4797     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4798       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4799                            DAG.getIntPtrConstant(Elt1 / 2));
4800       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4801                         DAG.getIntPtrConstant(i));
4802       continue;
4803     }
4804
4805     // If Elt1 is defined, extract it from the appropriate source.  If the
4806     // source byte is not also odd, shift the extracted word left 8 bits
4807     // otherwise clear the bottom 8 bits if we need to do an or.
4808     if (Elt1 >= 0) {
4809       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4810                            DAG.getIntPtrConstant(Elt1 / 2));
4811       if ((Elt1 & 1) == 0)
4812         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4813                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4814       else if (Elt0 >= 0)
4815         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4816                              DAG.getConstant(0xFF00, MVT::i16));
4817     }
4818     // If Elt0 is defined, extract it from the appropriate source.  If the
4819     // source byte is not also even, shift the extracted word right 8 bits. If
4820     // Elt1 was also defined, OR the extracted values together before
4821     // inserting them in the result.
4822     if (Elt0 >= 0) {
4823       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4824                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4825       if ((Elt0 & 1) != 0)
4826         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4827                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4828       else if (Elt1 >= 0)
4829         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4830                              DAG.getConstant(0x00FF, MVT::i16));
4831       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4832                          : InsElt0;
4833     }
4834     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4835                        DAG.getIntPtrConstant(i));
4836   }
4837   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4838 }
4839
4840 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4841 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4842 /// done when every pair / quad of shuffle mask elements point to elements in
4843 /// the right sequence. e.g.
4844 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4845 static
4846 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4847                                  SelectionDAG &DAG, DebugLoc dl) {
4848   EVT VT = SVOp->getValueType(0);
4849   SDValue V1 = SVOp->getOperand(0);
4850   SDValue V2 = SVOp->getOperand(1);
4851   unsigned NumElems = VT.getVectorNumElements();
4852   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4853   EVT NewVT;
4854   switch (VT.getSimpleVT().SimpleTy) {
4855   default: assert(false && "Unexpected!");
4856   case MVT::v4f32: NewVT = MVT::v2f64; break;
4857   case MVT::v4i32: NewVT = MVT::v2i64; break;
4858   case MVT::v8i16: NewVT = MVT::v4i32; break;
4859   case MVT::v16i8: NewVT = MVT::v4i32; break;
4860   }
4861
4862   int Scale = NumElems / NewWidth;
4863   SmallVector<int, 8> MaskVec;
4864   for (unsigned i = 0; i < NumElems; i += Scale) {
4865     int StartIdx = -1;
4866     for (int j = 0; j < Scale; ++j) {
4867       int EltIdx = SVOp->getMaskElt(i+j);
4868       if (EltIdx < 0)
4869         continue;
4870       if (StartIdx == -1)
4871         StartIdx = EltIdx - (EltIdx % Scale);
4872       if (EltIdx != StartIdx + j)
4873         return SDValue();
4874     }
4875     if (StartIdx == -1)
4876       MaskVec.push_back(-1);
4877     else
4878       MaskVec.push_back(StartIdx / Scale);
4879   }
4880
4881   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4882   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4883   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4884 }
4885
4886 /// getVZextMovL - Return a zero-extending vector move low node.
4887 ///
4888 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4889                             SDValue SrcOp, SelectionDAG &DAG,
4890                             const X86Subtarget *Subtarget, DebugLoc dl) {
4891   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4892     LoadSDNode *LD = NULL;
4893     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4894       LD = dyn_cast<LoadSDNode>(SrcOp);
4895     if (!LD) {
4896       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4897       // instead.
4898       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4899       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4900           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4901           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4902           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4903         // PR2108
4904         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4905         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4906                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4907                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4908                                                    OpVT,
4909                                                    SrcOp.getOperand(0)
4910                                                           .getOperand(0))));
4911       }
4912     }
4913   }
4914
4915   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4916                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4917                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4918                                              OpVT, SrcOp)));
4919 }
4920
4921 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4922 /// shuffles.
4923 static SDValue
4924 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4925   SDValue V1 = SVOp->getOperand(0);
4926   SDValue V2 = SVOp->getOperand(1);
4927   DebugLoc dl = SVOp->getDebugLoc();
4928   EVT VT = SVOp->getValueType(0);
4929
4930   SmallVector<std::pair<int, int>, 8> Locs;
4931   Locs.resize(4);
4932   SmallVector<int, 8> Mask1(4U, -1);
4933   SmallVector<int, 8> PermMask;
4934   SVOp->getMask(PermMask);
4935
4936   unsigned NumHi = 0;
4937   unsigned NumLo = 0;
4938   for (unsigned i = 0; i != 4; ++i) {
4939     int Idx = PermMask[i];
4940     if (Idx < 0) {
4941       Locs[i] = std::make_pair(-1, -1);
4942     } else {
4943       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4944       if (Idx < 4) {
4945         Locs[i] = std::make_pair(0, NumLo);
4946         Mask1[NumLo] = Idx;
4947         NumLo++;
4948       } else {
4949         Locs[i] = std::make_pair(1, NumHi);
4950         if (2+NumHi < 4)
4951           Mask1[2+NumHi] = Idx;
4952         NumHi++;
4953       }
4954     }
4955   }
4956
4957   if (NumLo <= 2 && NumHi <= 2) {
4958     // If no more than two elements come from either vector. This can be
4959     // implemented with two shuffles. First shuffle gather the elements.
4960     // The second shuffle, which takes the first shuffle as both of its
4961     // vector operands, put the elements into the right order.
4962     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4963
4964     SmallVector<int, 8> Mask2(4U, -1);
4965
4966     for (unsigned i = 0; i != 4; ++i) {
4967       if (Locs[i].first == -1)
4968         continue;
4969       else {
4970         unsigned Idx = (i < 2) ? 0 : 4;
4971         Idx += Locs[i].first * 2 + Locs[i].second;
4972         Mask2[i] = Idx;
4973       }
4974     }
4975
4976     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4977   } else if (NumLo == 3 || NumHi == 3) {
4978     // Otherwise, we must have three elements from one vector, call it X, and
4979     // one element from the other, call it Y.  First, use a shufps to build an
4980     // intermediate vector with the one element from Y and the element from X
4981     // that will be in the same half in the final destination (the indexes don't
4982     // matter). Then, use a shufps to build the final vector, taking the half
4983     // containing the element from Y from the intermediate, and the other half
4984     // from X.
4985     if (NumHi == 3) {
4986       // Normalize it so the 3 elements come from V1.
4987       CommuteVectorShuffleMask(PermMask, VT);
4988       std::swap(V1, V2);
4989     }
4990
4991     // Find the element from V2.
4992     unsigned HiIndex;
4993     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4994       int Val = PermMask[HiIndex];
4995       if (Val < 0)
4996         continue;
4997       if (Val >= 4)
4998         break;
4999     }
5000
5001     Mask1[0] = PermMask[HiIndex];
5002     Mask1[1] = -1;
5003     Mask1[2] = PermMask[HiIndex^1];
5004     Mask1[3] = -1;
5005     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5006
5007     if (HiIndex >= 2) {
5008       Mask1[0] = PermMask[0];
5009       Mask1[1] = PermMask[1];
5010       Mask1[2] = HiIndex & 1 ? 6 : 4;
5011       Mask1[3] = HiIndex & 1 ? 4 : 6;
5012       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5013     } else {
5014       Mask1[0] = HiIndex & 1 ? 2 : 0;
5015       Mask1[1] = HiIndex & 1 ? 0 : 2;
5016       Mask1[2] = PermMask[2];
5017       Mask1[3] = PermMask[3];
5018       if (Mask1[2] >= 0)
5019         Mask1[2] += 4;
5020       if (Mask1[3] >= 0)
5021         Mask1[3] += 4;
5022       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5023     }
5024   }
5025
5026   // Break it into (shuffle shuffle_hi, shuffle_lo).
5027   Locs.clear();
5028   SmallVector<int,8> LoMask(4U, -1);
5029   SmallVector<int,8> HiMask(4U, -1);
5030
5031   SmallVector<int,8> *MaskPtr = &LoMask;
5032   unsigned MaskIdx = 0;
5033   unsigned LoIdx = 0;
5034   unsigned HiIdx = 2;
5035   for (unsigned i = 0; i != 4; ++i) {
5036     if (i == 2) {
5037       MaskPtr = &HiMask;
5038       MaskIdx = 1;
5039       LoIdx = 0;
5040       HiIdx = 2;
5041     }
5042     int Idx = PermMask[i];
5043     if (Idx < 0) {
5044       Locs[i] = std::make_pair(-1, -1);
5045     } else if (Idx < 4) {
5046       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5047       (*MaskPtr)[LoIdx] = Idx;
5048       LoIdx++;
5049     } else {
5050       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5051       (*MaskPtr)[HiIdx] = Idx;
5052       HiIdx++;
5053     }
5054   }
5055
5056   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5057   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5058   SmallVector<int, 8> MaskOps;
5059   for (unsigned i = 0; i != 4; ++i) {
5060     if (Locs[i].first == -1) {
5061       MaskOps.push_back(-1);
5062     } else {
5063       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5064       MaskOps.push_back(Idx);
5065     }
5066   }
5067   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5068 }
5069
5070 static bool MayFoldVectorLoad(SDValue V) {
5071   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5072     V = V.getOperand(0);
5073   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5074     V = V.getOperand(0);
5075   if (MayFoldLoad(V))
5076     return true;
5077   return false;
5078 }
5079
5080 // FIXME: the version above should always be used. Since there's
5081 // a bug where several vector shuffles can't be folded because the
5082 // DAG is not updated during lowering and a node claims to have two
5083 // uses while it only has one, use this version, and let isel match
5084 // another instruction if the load really happens to have more than
5085 // one use. Remove this version after this bug get fixed.
5086 // rdar://8434668, PR8156
5087 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5088   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5089     V = V.getOperand(0);
5090   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5091     V = V.getOperand(0);
5092   if (ISD::isNormalLoad(V.getNode()))
5093     return true;
5094   return false;
5095 }
5096
5097 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5098 /// a vector extract, and if both can be later optimized into a single load.
5099 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5100 /// here because otherwise a target specific shuffle node is going to be
5101 /// emitted for this shuffle, and the optimization not done.
5102 /// FIXME: This is probably not the best approach, but fix the problem
5103 /// until the right path is decided.
5104 static
5105 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5106                                          const TargetLowering &TLI) {
5107   EVT VT = V.getValueType();
5108   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5109
5110   // Be sure that the vector shuffle is present in a pattern like this:
5111   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5112   if (!V.hasOneUse())
5113     return false;
5114
5115   SDNode *N = *V.getNode()->use_begin();
5116   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5117     return false;
5118
5119   SDValue EltNo = N->getOperand(1);
5120   if (!isa<ConstantSDNode>(EltNo))
5121     return false;
5122
5123   // If the bit convert changed the number of elements, it is unsafe
5124   // to examine the mask.
5125   bool HasShuffleIntoBitcast = false;
5126   if (V.getOpcode() == ISD::BIT_CONVERT) {
5127     EVT SrcVT = V.getOperand(0).getValueType();
5128     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5129       return false;
5130     V = V.getOperand(0);
5131     HasShuffleIntoBitcast = true;
5132   }
5133
5134   // Select the input vector, guarding against out of range extract vector.
5135   unsigned NumElems = VT.getVectorNumElements();
5136   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5137   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5138   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5139
5140   // Skip one more bit_convert if necessary
5141   if (V.getOpcode() == ISD::BIT_CONVERT)
5142     V = V.getOperand(0);
5143
5144   if (ISD::isNormalLoad(V.getNode())) {
5145     // Is the original load suitable?
5146     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5147
5148     // FIXME: avoid the multi-use bug that is preventing lots of
5149     // of foldings to be detected, this is still wrong of course, but
5150     // give the temporary desired behavior, and if it happens that
5151     // the load has real more uses, during isel it will not fold, and
5152     // will generate poor code.
5153     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5154       return false;
5155
5156     if (!HasShuffleIntoBitcast)
5157       return true;
5158
5159     // If there's a bitcast before the shuffle, check if the load type and
5160     // alignment is valid.
5161     unsigned Align = LN0->getAlignment();
5162     unsigned NewAlign =
5163       TLI.getTargetData()->getABITypeAlignment(
5164                                     VT.getTypeForEVT(*DAG.getContext()));
5165
5166     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5167       return false;
5168   }
5169
5170   return true;
5171 }
5172
5173 static
5174 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5175   EVT VT = Op.getValueType();
5176
5177   // Canonizalize to v2f64.
5178   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, V1);
5179   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5180                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5181                                           V1, DAG));
5182 }
5183
5184 static
5185 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5186                         bool HasSSE2) {
5187   SDValue V1 = Op.getOperand(0);
5188   SDValue V2 = Op.getOperand(1);
5189   EVT VT = Op.getValueType();
5190
5191   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5192
5193   if (HasSSE2 && VT == MVT::v2f64)
5194     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5195
5196   // v4f32 or v4i32
5197   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5198 }
5199
5200 static
5201 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5202   SDValue V1 = Op.getOperand(0);
5203   SDValue V2 = Op.getOperand(1);
5204   EVT VT = Op.getValueType();
5205
5206   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5207          "unsupported shuffle type");
5208
5209   if (V2.getOpcode() == ISD::UNDEF)
5210     V2 = V1;
5211
5212   // v4i32 or v4f32
5213   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5214 }
5215
5216 static
5217 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5218   SDValue V1 = Op.getOperand(0);
5219   SDValue V2 = Op.getOperand(1);
5220   EVT VT = Op.getValueType();
5221   unsigned NumElems = VT.getVectorNumElements();
5222
5223   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5224   // operand of these instructions is only memory, so check if there's a
5225   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5226   // same masks.
5227   bool CanFoldLoad = false;
5228
5229   // Trivial case, when V2 comes from a load.
5230   if (MayFoldVectorLoad(V2))
5231     CanFoldLoad = true;
5232
5233   // When V1 is a load, it can be folded later into a store in isel, example:
5234   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5235   //    turns into:
5236   //  (MOVLPSmr addr:$src1, VR128:$src2)
5237   // So, recognize this potential and also use MOVLPS or MOVLPD
5238   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5239     CanFoldLoad = true;
5240
5241   if (CanFoldLoad) {
5242     if (HasSSE2 && NumElems == 2)
5243       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5244
5245     if (NumElems == 4)
5246       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5247   }
5248
5249   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5250   // movl and movlp will both match v2i64, but v2i64 is never matched by
5251   // movl earlier because we make it strict to avoid messing with the movlp load
5252   // folding logic (see the code above getMOVLP call). Match it here then,
5253   // this is horrible, but will stay like this until we move all shuffle
5254   // matching to x86 specific nodes. Note that for the 1st condition all
5255   // types are matched with movsd.
5256   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5257     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5258   else if (HasSSE2)
5259     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5260
5261
5262   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5263
5264   // Invert the operand order and use SHUFPS to match it.
5265   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5266                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5267 }
5268
5269 static inline unsigned getUNPCKLOpcode(EVT VT) {
5270   switch(VT.getSimpleVT().SimpleTy) {
5271   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5272   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5273   case MVT::v4f32: return X86ISD::UNPCKLPS;
5274   case MVT::v2f64: return X86ISD::UNPCKLPD;
5275   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5276   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5277   default:
5278     llvm_unreachable("Unknow type for unpckl");
5279   }
5280   return 0;
5281 }
5282
5283 static inline unsigned getUNPCKHOpcode(EVT VT) {
5284   switch(VT.getSimpleVT().SimpleTy) {
5285   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5286   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5287   case MVT::v4f32: return X86ISD::UNPCKHPS;
5288   case MVT::v2f64: return X86ISD::UNPCKHPD;
5289   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5290   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5291   default:
5292     llvm_unreachable("Unknow type for unpckh");
5293   }
5294   return 0;
5295 }
5296
5297 static
5298 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5299                                const TargetLowering &TLI,
5300                                const X86Subtarget *Subtarget) {
5301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5302   EVT VT = Op.getValueType();
5303   DebugLoc dl = Op.getDebugLoc();
5304   SDValue V1 = Op.getOperand(0);
5305   SDValue V2 = Op.getOperand(1);
5306
5307   if (isZeroShuffle(SVOp))
5308     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5309
5310   // Handle splat operations
5311   if (SVOp->isSplat()) {
5312     // Special case, this is the only place now where it's
5313     // allowed to return a vector_shuffle operation without
5314     // using a target specific node, because *hopefully* it
5315     // will be optimized away by the dag combiner.
5316     if (VT.getVectorNumElements() <= 4 &&
5317         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5318       return Op;
5319
5320     // Handle splats by matching through known masks
5321     if (VT.getVectorNumElements() <= 4)
5322       return SDValue();
5323
5324     // Canonicalize all of the remaining to v4f32.
5325     return PromoteSplat(SVOp, DAG);
5326   }
5327
5328   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5329   // do it!
5330   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5331     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5332     if (NewOp.getNode())
5333       return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5334   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5335     // FIXME: Figure out a cleaner way to do this.
5336     // Try to make use of movq to zero out the top part.
5337     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5338       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5339       if (NewOp.getNode()) {
5340         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5341           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5342                               DAG, Subtarget, dl);
5343       }
5344     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5345       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5346       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5347         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5348                             DAG, Subtarget, dl);
5349     }
5350   }
5351   return SDValue();
5352 }
5353
5354 SDValue
5355 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5356   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5357   SDValue V1 = Op.getOperand(0);
5358   SDValue V2 = Op.getOperand(1);
5359   EVT VT = Op.getValueType();
5360   DebugLoc dl = Op.getDebugLoc();
5361   unsigned NumElems = VT.getVectorNumElements();
5362   bool isMMX = VT.getSizeInBits() == 64;
5363   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5364   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5365   bool V1IsSplat = false;
5366   bool V2IsSplat = false;
5367   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5368   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5369   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5370   MachineFunction &MF = DAG.getMachineFunction();
5371   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5372
5373   // Shuffle operations on MMX not supported.
5374   if (isMMX)
5375     return Op;
5376
5377   // Vector shuffle lowering takes 3 steps:
5378   //
5379   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5380   //    narrowing and commutation of operands should be handled.
5381   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5382   //    shuffle nodes.
5383   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5384   //    so the shuffle can be broken into other shuffles and the legalizer can
5385   //    try the lowering again.
5386   //
5387   // The general ideia is that no vector_shuffle operation should be left to
5388   // be matched during isel, all of them must be converted to a target specific
5389   // node here.
5390
5391   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5392   // narrowing and commutation of operands should be handled. The actual code
5393   // doesn't include all of those, work in progress...
5394   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5395   if (NewOp.getNode())
5396     return NewOp;
5397
5398   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5399   // unpckh_undef). Only use pshufd if speed is more important than size.
5400   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5401     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5402       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5403   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5404     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5405       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5406
5407   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5408       RelaxedMayFoldVectorLoad(V1))
5409     return getMOVDDup(Op, dl, V1, DAG);
5410
5411   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5412     return getMOVHighToLow(Op, dl, DAG);
5413
5414   // Use to match splats
5415   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5416       (VT == MVT::v2f64 || VT == MVT::v2i64))
5417     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5418
5419   if (X86::isPSHUFDMask(SVOp)) {
5420     // The actual implementation will match the mask in the if above and then
5421     // during isel it can match several different instructions, not only pshufd
5422     // as its name says, sad but true, emulate the behavior for now...
5423     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5424         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5425
5426     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5427
5428     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5429       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5430
5431     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5432       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5433                                   TargetMask, DAG);
5434
5435     if (VT == MVT::v4f32)
5436       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5437                                   TargetMask, DAG);
5438   }
5439
5440   // Check if this can be converted into a logical shift.
5441   bool isLeft = false;
5442   unsigned ShAmt = 0;
5443   SDValue ShVal;
5444   bool isShift = getSubtarget()->hasSSE2() &&
5445     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5446   if (isShift && ShVal.hasOneUse()) {
5447     // If the shifted value has multiple uses, it may be cheaper to use
5448     // v_set0 + movlhps or movhlps, etc.
5449     EVT EltVT = VT.getVectorElementType();
5450     ShAmt *= EltVT.getSizeInBits();
5451     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5452   }
5453
5454   if (X86::isMOVLMask(SVOp)) {
5455     if (V1IsUndef)
5456       return V2;
5457     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5458       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5459     if (!X86::isMOVLPMask(SVOp)) {
5460       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5461         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5462
5463       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5464         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5465     }
5466   }
5467
5468   // FIXME: fold these into legal mask.
5469   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5470     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5471
5472   if (X86::isMOVHLPSMask(SVOp))
5473     return getMOVHighToLow(Op, dl, DAG);
5474
5475   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5476     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5477
5478   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5479     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5480
5481   if (X86::isMOVLPMask(SVOp))
5482     return getMOVLP(Op, dl, DAG, HasSSE2);
5483
5484   if (ShouldXformToMOVHLPS(SVOp) ||
5485       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5486     return CommuteVectorShuffle(SVOp, DAG);
5487
5488   if (isShift) {
5489     // No better options. Use a vshl / vsrl.
5490     EVT EltVT = VT.getVectorElementType();
5491     ShAmt *= EltVT.getSizeInBits();
5492     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5493   }
5494
5495   bool Commuted = false;
5496   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5497   // 1,1,1,1 -> v8i16 though.
5498   V1IsSplat = isSplatVector(V1.getNode());
5499   V2IsSplat = isSplatVector(V2.getNode());
5500
5501   // Canonicalize the splat or undef, if present, to be on the RHS.
5502   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5503     Op = CommuteVectorShuffle(SVOp, DAG);
5504     SVOp = cast<ShuffleVectorSDNode>(Op);
5505     V1 = SVOp->getOperand(0);
5506     V2 = SVOp->getOperand(1);
5507     std::swap(V1IsSplat, V2IsSplat);
5508     std::swap(V1IsUndef, V2IsUndef);
5509     Commuted = true;
5510   }
5511
5512   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5513     // Shuffling low element of v1 into undef, just return v1.
5514     if (V2IsUndef)
5515       return V1;
5516     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5517     // the instruction selector will not match, so get a canonical MOVL with
5518     // swapped operands to undo the commute.
5519     return getMOVL(DAG, dl, VT, V2, V1);
5520   }
5521
5522   if (X86::isUNPCKLMask(SVOp))
5523     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5524
5525   if (X86::isUNPCKHMask(SVOp))
5526     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5527
5528   if (V2IsSplat) {
5529     // Normalize mask so all entries that point to V2 points to its first
5530     // element then try to match unpck{h|l} again. If match, return a
5531     // new vector_shuffle with the corrected mask.
5532     SDValue NewMask = NormalizeMask(SVOp, DAG);
5533     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5534     if (NSVOp != SVOp) {
5535       if (X86::isUNPCKLMask(NSVOp, true)) {
5536         return NewMask;
5537       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5538         return NewMask;
5539       }
5540     }
5541   }
5542
5543   if (Commuted) {
5544     // Commute is back and try unpck* again.
5545     // FIXME: this seems wrong.
5546     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5547     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5548
5549     if (X86::isUNPCKLMask(NewSVOp))
5550       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5551
5552     if (X86::isUNPCKHMask(NewSVOp))
5553       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5554   }
5555
5556   // Normalize the node to match x86 shuffle ops if needed
5557   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5558     return CommuteVectorShuffle(SVOp, DAG);
5559
5560   // The checks below are all present in isShuffleMaskLegal, but they are
5561   // inlined here right now to enable us to directly emit target specific
5562   // nodes, and remove one by one until they don't return Op anymore.
5563   SmallVector<int, 16> M;
5564   SVOp->getMask(M);
5565
5566   if (isPALIGNRMask(M, VT, HasSSSE3))
5567     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5568                                 X86::getShufflePALIGNRImmediate(SVOp),
5569                                 DAG);
5570
5571   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5572       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5573     if (VT == MVT::v2f64)
5574       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5575     if (VT == MVT::v2i64)
5576       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5577   }
5578
5579   if (isPSHUFHWMask(M, VT))
5580     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5581                                 X86::getShufflePSHUFHWImmediate(SVOp),
5582                                 DAG);
5583
5584   if (isPSHUFLWMask(M, VT))
5585     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5586                                 X86::getShufflePSHUFLWImmediate(SVOp),
5587                                 DAG);
5588
5589   if (isSHUFPMask(M, VT)) {
5590     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5591     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5592       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5593                                   TargetMask, DAG);
5594     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5595       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5596                                   TargetMask, DAG);
5597   }
5598
5599   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5600     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5601       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5602   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5603     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5604       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5605
5606   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5607   if (VT == MVT::v8i16) {
5608     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5609     if (NewOp.getNode())
5610       return NewOp;
5611   }
5612
5613   if (VT == MVT::v16i8) {
5614     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5615     if (NewOp.getNode())
5616       return NewOp;
5617   }
5618
5619   // Handle all 4 wide cases with a number of shuffles.
5620   if (NumElems == 4)
5621     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5622
5623   return SDValue();
5624 }
5625
5626 SDValue
5627 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5628                                                 SelectionDAG &DAG) const {
5629   EVT VT = Op.getValueType();
5630   DebugLoc dl = Op.getDebugLoc();
5631   if (VT.getSizeInBits() == 8) {
5632     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5633                                     Op.getOperand(0), Op.getOperand(1));
5634     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5635                                     DAG.getValueType(VT));
5636     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5637   } else if (VT.getSizeInBits() == 16) {
5638     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5639     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5640     if (Idx == 0)
5641       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5642                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5643                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5644                                                  MVT::v4i32,
5645                                                  Op.getOperand(0)),
5646                                      Op.getOperand(1)));
5647     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5648                                     Op.getOperand(0), Op.getOperand(1));
5649     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5650                                     DAG.getValueType(VT));
5651     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5652   } else if (VT == MVT::f32) {
5653     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5654     // the result back to FR32 register. It's only worth matching if the
5655     // result has a single use which is a store or a bitcast to i32.  And in
5656     // the case of a store, it's not worth it if the index is a constant 0,
5657     // because a MOVSSmr can be used instead, which is smaller and faster.
5658     if (!Op.hasOneUse())
5659       return SDValue();
5660     SDNode *User = *Op.getNode()->use_begin();
5661     if ((User->getOpcode() != ISD::STORE ||
5662          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5663           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5664         (User->getOpcode() != ISD::BIT_CONVERT ||
5665          User->getValueType(0) != MVT::i32))
5666       return SDValue();
5667     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5668                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5669                                               Op.getOperand(0)),
5670                                               Op.getOperand(1));
5671     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5672   } else if (VT == MVT::i32) {
5673     // ExtractPS works with constant index.
5674     if (isa<ConstantSDNode>(Op.getOperand(1)))
5675       return Op;
5676   }
5677   return SDValue();
5678 }
5679
5680
5681 SDValue
5682 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5683                                            SelectionDAG &DAG) const {
5684   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5685     return SDValue();
5686
5687   if (Subtarget->hasSSE41()) {
5688     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5689     if (Res.getNode())
5690       return Res;
5691   }
5692
5693   EVT VT = Op.getValueType();
5694   DebugLoc dl = Op.getDebugLoc();
5695   // TODO: handle v16i8.
5696   if (VT.getSizeInBits() == 16) {
5697     SDValue Vec = Op.getOperand(0);
5698     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5699     if (Idx == 0)
5700       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5701                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5702                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5703                                                  MVT::v4i32, Vec),
5704                                      Op.getOperand(1)));
5705     // Transform it so it match pextrw which produces a 32-bit result.
5706     EVT EltVT = MVT::i32;
5707     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5708                                     Op.getOperand(0), Op.getOperand(1));
5709     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5710                                     DAG.getValueType(VT));
5711     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5712   } else if (VT.getSizeInBits() == 32) {
5713     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5714     if (Idx == 0)
5715       return Op;
5716
5717     // SHUFPS the element to the lowest double word, then movss.
5718     int Mask[4] = { Idx, -1, -1, -1 };
5719     EVT VVT = Op.getOperand(0).getValueType();
5720     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5721                                        DAG.getUNDEF(VVT), Mask);
5722     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5723                        DAG.getIntPtrConstant(0));
5724   } else if (VT.getSizeInBits() == 64) {
5725     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5726     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5727     //        to match extract_elt for f64.
5728     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5729     if (Idx == 0)
5730       return Op;
5731
5732     // UNPCKHPD the element to the lowest double word, then movsd.
5733     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5734     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5735     int Mask[2] = { 1, -1 };
5736     EVT VVT = Op.getOperand(0).getValueType();
5737     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5738                                        DAG.getUNDEF(VVT), Mask);
5739     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5740                        DAG.getIntPtrConstant(0));
5741   }
5742
5743   return SDValue();
5744 }
5745
5746 SDValue
5747 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5748                                                SelectionDAG &DAG) const {
5749   EVT VT = Op.getValueType();
5750   EVT EltVT = VT.getVectorElementType();
5751   DebugLoc dl = Op.getDebugLoc();
5752
5753   SDValue N0 = Op.getOperand(0);
5754   SDValue N1 = Op.getOperand(1);
5755   SDValue N2 = Op.getOperand(2);
5756
5757   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5758       isa<ConstantSDNode>(N2)) {
5759     unsigned Opc;
5760     if (VT == MVT::v8i16)
5761       Opc = X86ISD::PINSRW;
5762     else if (VT == MVT::v16i8)
5763       Opc = X86ISD::PINSRB;
5764     else
5765       Opc = X86ISD::PINSRB;
5766
5767     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5768     // argument.
5769     if (N1.getValueType() != MVT::i32)
5770       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5771     if (N2.getValueType() != MVT::i32)
5772       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5773     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5774   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5775     // Bits [7:6] of the constant are the source select.  This will always be
5776     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5777     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5778     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5779     // Bits [5:4] of the constant are the destination select.  This is the
5780     //  value of the incoming immediate.
5781     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5782     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5783     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5784     // Create this as a scalar to vector..
5785     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5786     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5787   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5788     // PINSR* works with constant index.
5789     return Op;
5790   }
5791   return SDValue();
5792 }
5793
5794 SDValue
5795 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5796   EVT VT = Op.getValueType();
5797   EVT EltVT = VT.getVectorElementType();
5798
5799   if (Subtarget->hasSSE41())
5800     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5801
5802   if (EltVT == MVT::i8)
5803     return SDValue();
5804
5805   DebugLoc dl = Op.getDebugLoc();
5806   SDValue N0 = Op.getOperand(0);
5807   SDValue N1 = Op.getOperand(1);
5808   SDValue N2 = Op.getOperand(2);
5809
5810   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5811     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5812     // as its second argument.
5813     if (N1.getValueType() != MVT::i32)
5814       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5815     if (N2.getValueType() != MVT::i32)
5816       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5817     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5818   }
5819   return SDValue();
5820 }
5821
5822 SDValue
5823 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5824   DebugLoc dl = Op.getDebugLoc();
5825   
5826   if (Op.getValueType() == MVT::v1i64 &&
5827       Op.getOperand(0).getValueType() == MVT::i64)
5828     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5829
5830   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5831   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5832          "Expected an SSE type!");
5833   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5834                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5835 }
5836
5837 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5838 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5839 // one of the above mentioned nodes. It has to be wrapped because otherwise
5840 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5841 // be used to form addressing mode. These wrapped nodes will be selected
5842 // into MOV32ri.
5843 SDValue
5844 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5845   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5846
5847   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5848   // global base reg.
5849   unsigned char OpFlag = 0;
5850   unsigned WrapperKind = X86ISD::Wrapper;
5851   CodeModel::Model M = getTargetMachine().getCodeModel();
5852
5853   if (Subtarget->isPICStyleRIPRel() &&
5854       (M == CodeModel::Small || M == CodeModel::Kernel))
5855     WrapperKind = X86ISD::WrapperRIP;
5856   else if (Subtarget->isPICStyleGOT())
5857     OpFlag = X86II::MO_GOTOFF;
5858   else if (Subtarget->isPICStyleStubPIC())
5859     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5860
5861   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5862                                              CP->getAlignment(),
5863                                              CP->getOffset(), OpFlag);
5864   DebugLoc DL = CP->getDebugLoc();
5865   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5866   // With PIC, the address is actually $g + Offset.
5867   if (OpFlag) {
5868     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5869                          DAG.getNode(X86ISD::GlobalBaseReg,
5870                                      DebugLoc(), getPointerTy()),
5871                          Result);
5872   }
5873
5874   return Result;
5875 }
5876
5877 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5878   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5879
5880   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5881   // global base reg.
5882   unsigned char OpFlag = 0;
5883   unsigned WrapperKind = X86ISD::Wrapper;
5884   CodeModel::Model M = getTargetMachine().getCodeModel();
5885
5886   if (Subtarget->isPICStyleRIPRel() &&
5887       (M == CodeModel::Small || M == CodeModel::Kernel))
5888     WrapperKind = X86ISD::WrapperRIP;
5889   else if (Subtarget->isPICStyleGOT())
5890     OpFlag = X86II::MO_GOTOFF;
5891   else if (Subtarget->isPICStyleStubPIC())
5892     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5893
5894   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5895                                           OpFlag);
5896   DebugLoc DL = JT->getDebugLoc();
5897   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5898
5899   // With PIC, the address is actually $g + Offset.
5900   if (OpFlag) {
5901     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5902                          DAG.getNode(X86ISD::GlobalBaseReg,
5903                                      DebugLoc(), getPointerTy()),
5904                          Result);
5905   }
5906
5907   return Result;
5908 }
5909
5910 SDValue
5911 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5912   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5913
5914   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5915   // global base reg.
5916   unsigned char OpFlag = 0;
5917   unsigned WrapperKind = X86ISD::Wrapper;
5918   CodeModel::Model M = getTargetMachine().getCodeModel();
5919
5920   if (Subtarget->isPICStyleRIPRel() &&
5921       (M == CodeModel::Small || M == CodeModel::Kernel))
5922     WrapperKind = X86ISD::WrapperRIP;
5923   else if (Subtarget->isPICStyleGOT())
5924     OpFlag = X86II::MO_GOTOFF;
5925   else if (Subtarget->isPICStyleStubPIC())
5926     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5927
5928   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5929
5930   DebugLoc DL = Op.getDebugLoc();
5931   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5932
5933
5934   // With PIC, the address is actually $g + Offset.
5935   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5936       !Subtarget->is64Bit()) {
5937     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5938                          DAG.getNode(X86ISD::GlobalBaseReg,
5939                                      DebugLoc(), getPointerTy()),
5940                          Result);
5941   }
5942
5943   return Result;
5944 }
5945
5946 SDValue
5947 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5948   // Create the TargetBlockAddressAddress node.
5949   unsigned char OpFlags =
5950     Subtarget->ClassifyBlockAddressReference();
5951   CodeModel::Model M = getTargetMachine().getCodeModel();
5952   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5953   DebugLoc dl = Op.getDebugLoc();
5954   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5955                                        /*isTarget=*/true, OpFlags);
5956
5957   if (Subtarget->isPICStyleRIPRel() &&
5958       (M == CodeModel::Small || M == CodeModel::Kernel))
5959     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5960   else
5961     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5962
5963   // With PIC, the address is actually $g + Offset.
5964   if (isGlobalRelativeToPICBase(OpFlags)) {
5965     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5966                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5967                          Result);
5968   }
5969
5970   return Result;
5971 }
5972
5973 SDValue
5974 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5975                                       int64_t Offset,
5976                                       SelectionDAG &DAG) const {
5977   // Create the TargetGlobalAddress node, folding in the constant
5978   // offset if it is legal.
5979   unsigned char OpFlags =
5980     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5981   CodeModel::Model M = getTargetMachine().getCodeModel();
5982   SDValue Result;
5983   if (OpFlags == X86II::MO_NO_FLAG &&
5984       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5985     // A direct static reference to a global.
5986     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5987     Offset = 0;
5988   } else {
5989     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5990   }
5991
5992   if (Subtarget->isPICStyleRIPRel() &&
5993       (M == CodeModel::Small || M == CodeModel::Kernel))
5994     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5995   else
5996     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5997
5998   // With PIC, the address is actually $g + Offset.
5999   if (isGlobalRelativeToPICBase(OpFlags)) {
6000     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6001                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6002                          Result);
6003   }
6004
6005   // For globals that require a load from a stub to get the address, emit the
6006   // load.
6007   if (isGlobalStubReference(OpFlags))
6008     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6009                          MachinePointerInfo::getGOT(), false, false, 0);
6010
6011   // If there was a non-zero offset that we didn't fold, create an explicit
6012   // addition for it.
6013   if (Offset != 0)
6014     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6015                          DAG.getConstant(Offset, getPointerTy()));
6016
6017   return Result;
6018 }
6019
6020 SDValue
6021 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6022   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6023   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6024   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6025 }
6026
6027 static SDValue
6028 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6029            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6030            unsigned char OperandFlags) {
6031   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6032   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6033   DebugLoc dl = GA->getDebugLoc();
6034   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6035                                            GA->getValueType(0),
6036                                            GA->getOffset(),
6037                                            OperandFlags);
6038   if (InFlag) {
6039     SDValue Ops[] = { Chain,  TGA, *InFlag };
6040     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6041   } else {
6042     SDValue Ops[]  = { Chain, TGA };
6043     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6044   }
6045
6046   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6047   MFI->setAdjustsStack(true);
6048
6049   SDValue Flag = Chain.getValue(1);
6050   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6051 }
6052
6053 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6054 static SDValue
6055 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6056                                 const EVT PtrVT) {
6057   SDValue InFlag;
6058   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6059   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6060                                      DAG.getNode(X86ISD::GlobalBaseReg,
6061                                                  DebugLoc(), PtrVT), InFlag);
6062   InFlag = Chain.getValue(1);
6063
6064   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6065 }
6066
6067 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6068 static SDValue
6069 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6070                                 const EVT PtrVT) {
6071   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6072                     X86::RAX, X86II::MO_TLSGD);
6073 }
6074
6075 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6076 // "local exec" model.
6077 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6078                                    const EVT PtrVT, TLSModel::Model model,
6079                                    bool is64Bit) {
6080   DebugLoc dl = GA->getDebugLoc();
6081   
6082   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6083   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6084                                                          is64Bit ? 257 : 256));
6085
6086   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 
6087                                       DAG.getIntPtrConstant(0),
6088                                       MachinePointerInfo(Ptr), false, false, 0);
6089
6090   unsigned char OperandFlags = 0;
6091   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6092   // initialexec.
6093   unsigned WrapperKind = X86ISD::Wrapper;
6094   if (model == TLSModel::LocalExec) {
6095     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6096   } else if (is64Bit) {
6097     assert(model == TLSModel::InitialExec);
6098     OperandFlags = X86II::MO_GOTTPOFF;
6099     WrapperKind = X86ISD::WrapperRIP;
6100   } else {
6101     assert(model == TLSModel::InitialExec);
6102     OperandFlags = X86II::MO_INDNTPOFF;
6103   }
6104
6105   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6106   // exec)
6107   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 
6108                                            GA->getValueType(0),
6109                                            GA->getOffset(), OperandFlags);
6110   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6111
6112   if (model == TLSModel::InitialExec)
6113     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6114                          MachinePointerInfo::getGOT(), false, false, 0);
6115
6116   // The address of the thread local variable is the add of the thread
6117   // pointer with the offset of the variable.
6118   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6119 }
6120
6121 SDValue
6122 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6123   
6124   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6125   const GlobalValue *GV = GA->getGlobal();
6126
6127   if (Subtarget->isTargetELF()) {
6128     // TODO: implement the "local dynamic" model
6129     // TODO: implement the "initial exec"model for pic executables
6130     
6131     // If GV is an alias then use the aliasee for determining
6132     // thread-localness.
6133     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6134       GV = GA->resolveAliasedGlobal(false);
6135     
6136     TLSModel::Model model 
6137       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6138     
6139     switch (model) {
6140       case TLSModel::GeneralDynamic:
6141       case TLSModel::LocalDynamic: // not implemented
6142         if (Subtarget->is64Bit())
6143           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6144         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6145         
6146       case TLSModel::InitialExec:
6147       case TLSModel::LocalExec:
6148         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6149                                    Subtarget->is64Bit());
6150     }
6151   } else if (Subtarget->isTargetDarwin()) {
6152     // Darwin only has one model of TLS.  Lower to that.
6153     unsigned char OpFlag = 0;
6154     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6155                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6156     
6157     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6158     // global base reg.
6159     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6160                   !Subtarget->is64Bit();
6161     if (PIC32)
6162       OpFlag = X86II::MO_TLVP_PIC_BASE;
6163     else
6164       OpFlag = X86II::MO_TLVP;
6165     DebugLoc DL = Op.getDebugLoc();    
6166     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6167                                                 getPointerTy(),
6168                                                 GA->getOffset(), OpFlag);
6169     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6170   
6171     // With PIC32, the address is actually $g + Offset.
6172     if (PIC32)
6173       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6174                            DAG.getNode(X86ISD::GlobalBaseReg,
6175                                        DebugLoc(), getPointerTy()),
6176                            Offset);
6177     
6178     // Lowering the machine isd will make sure everything is in the right
6179     // location.
6180     SDValue Args[] = { Offset };
6181     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6182     
6183     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6184     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6185     MFI->setAdjustsStack(true);
6186
6187     // And our return value (tls address) is in the standard call return value
6188     // location.
6189     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6190     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6191   }
6192   
6193   assert(false &&
6194          "TLS not implemented for this target.");
6195
6196   llvm_unreachable("Unreachable");
6197   return SDValue();
6198 }
6199
6200
6201 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6202 /// take a 2 x i32 value to shift plus a shift amount.
6203 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6204   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6205   EVT VT = Op.getValueType();
6206   unsigned VTBits = VT.getSizeInBits();
6207   DebugLoc dl = Op.getDebugLoc();
6208   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6209   SDValue ShOpLo = Op.getOperand(0);
6210   SDValue ShOpHi = Op.getOperand(1);
6211   SDValue ShAmt  = Op.getOperand(2);
6212   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6213                                      DAG.getConstant(VTBits - 1, MVT::i8))
6214                        : DAG.getConstant(0, VT);
6215
6216   SDValue Tmp2, Tmp3;
6217   if (Op.getOpcode() == ISD::SHL_PARTS) {
6218     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6219     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6220   } else {
6221     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6222     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6223   }
6224
6225   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6226                                 DAG.getConstant(VTBits, MVT::i8));
6227   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6228                              AndNode, DAG.getConstant(0, MVT::i8));
6229
6230   SDValue Hi, Lo;
6231   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6232   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6233   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6234
6235   if (Op.getOpcode() == ISD::SHL_PARTS) {
6236     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6237     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6238   } else {
6239     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6240     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6241   }
6242
6243   SDValue Ops[2] = { Lo, Hi };
6244   return DAG.getMergeValues(Ops, 2, dl);
6245 }
6246
6247 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6248                                            SelectionDAG &DAG) const {
6249   EVT SrcVT = Op.getOperand(0).getValueType();
6250
6251   if (SrcVT.isVector())
6252     return SDValue();
6253
6254   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6255          "Unknown SINT_TO_FP to lower!");
6256
6257   // These are really Legal; return the operand so the caller accepts it as
6258   // Legal.
6259   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6260     return Op;
6261   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6262       Subtarget->is64Bit()) {
6263     return Op;
6264   }
6265
6266   DebugLoc dl = Op.getDebugLoc();
6267   unsigned Size = SrcVT.getSizeInBits()/8;
6268   MachineFunction &MF = DAG.getMachineFunction();
6269   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6270   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6271   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6272                                StackSlot,
6273                                MachinePointerInfo::getFixedStack(SSFI),
6274                                false, false, 0);
6275   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6276 }
6277
6278 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6279                                      SDValue StackSlot, 
6280                                      SelectionDAG &DAG) const {
6281   // Build the FILD
6282   DebugLoc DL = Op.getDebugLoc();
6283   SDVTList Tys;
6284   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6285   if (useSSE)
6286     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6287   else
6288     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6289   
6290   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6291   
6292   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6293   MachineMemOperand *MMO =
6294     DAG.getMachineFunction()
6295     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6296                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6297   
6298   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6299   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6300                                            X86ISD::FILD, DL,
6301                                            Tys, Ops, array_lengthof(Ops),
6302                                            SrcVT, MMO);
6303
6304   if (useSSE) {
6305     Chain = Result.getValue(1);
6306     SDValue InFlag = Result.getValue(2);
6307
6308     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6309     // shouldn't be necessary except that RFP cannot be live across
6310     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6311     MachineFunction &MF = DAG.getMachineFunction();
6312     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6313     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6314     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6315     Tys = DAG.getVTList(MVT::Other);
6316     SDValue Ops[] = {
6317       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6318     };
6319     MachineMemOperand *MMO =
6320       DAG.getMachineFunction()
6321       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6322                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6323     
6324     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6325                                     Ops, array_lengthof(Ops),
6326                                     Op.getValueType(), MMO);
6327     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6328                          MachinePointerInfo::getFixedStack(SSFI),
6329                          false, false, 0);
6330   }
6331
6332   return Result;
6333 }
6334
6335 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6336 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6337                                                SelectionDAG &DAG) const {
6338   // This algorithm is not obvious. Here it is in C code, more or less:
6339   /*
6340     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6341       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6342       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6343
6344       // Copy ints to xmm registers.
6345       __m128i xh = _mm_cvtsi32_si128( hi );
6346       __m128i xl = _mm_cvtsi32_si128( lo );
6347
6348       // Combine into low half of a single xmm register.
6349       __m128i x = _mm_unpacklo_epi32( xh, xl );
6350       __m128d d;
6351       double sd;
6352
6353       // Merge in appropriate exponents to give the integer bits the right
6354       // magnitude.
6355       x = _mm_unpacklo_epi32( x, exp );
6356
6357       // Subtract away the biases to deal with the IEEE-754 double precision
6358       // implicit 1.
6359       d = _mm_sub_pd( (__m128d) x, bias );
6360
6361       // All conversions up to here are exact. The correctly rounded result is
6362       // calculated using the current rounding mode using the following
6363       // horizontal add.
6364       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6365       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6366                                 // store doesn't really need to be here (except
6367                                 // maybe to zero the other double)
6368       return sd;
6369     }
6370   */
6371
6372   DebugLoc dl = Op.getDebugLoc();
6373   LLVMContext *Context = DAG.getContext();
6374
6375   // Build some magic constants.
6376   std::vector<Constant*> CV0;
6377   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6378   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6379   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6380   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6381   Constant *C0 = ConstantVector::get(CV0);
6382   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6383
6384   std::vector<Constant*> CV1;
6385   CV1.push_back(
6386     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6387   CV1.push_back(
6388     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6389   Constant *C1 = ConstantVector::get(CV1);
6390   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6391
6392   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6393                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6394                                         Op.getOperand(0),
6395                                         DAG.getIntPtrConstant(1)));
6396   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6397                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6398                                         Op.getOperand(0),
6399                                         DAG.getIntPtrConstant(0)));
6400   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6401   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6402                               MachinePointerInfo::getConstantPool(),
6403                               false, false, 16);
6404   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6405   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6406   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6407                               MachinePointerInfo::getConstantPool(),
6408                               false, false, 16);
6409   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6410
6411   // Add the halves; easiest way is to swap them into another reg first.
6412   int ShufMask[2] = { 1, -1 };
6413   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6414                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6415   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6416   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6417                      DAG.getIntPtrConstant(0));
6418 }
6419
6420 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6421 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6422                                                SelectionDAG &DAG) const {
6423   DebugLoc dl = Op.getDebugLoc();
6424   // FP constant to bias correct the final result.
6425   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6426                                    MVT::f64);
6427
6428   // Load the 32-bit value into an XMM register.
6429   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6430                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6431                                          Op.getOperand(0),
6432                                          DAG.getIntPtrConstant(0)));
6433
6434   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6435                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6436                      DAG.getIntPtrConstant(0));
6437
6438   // Or the load with the bias.
6439   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6440                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6441                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6442                                                    MVT::v2f64, Load)),
6443                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6444                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6445                                                    MVT::v2f64, Bias)));
6446   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6447                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6448                    DAG.getIntPtrConstant(0));
6449
6450   // Subtract the bias.
6451   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6452
6453   // Handle final rounding.
6454   EVT DestVT = Op.getValueType();
6455
6456   if (DestVT.bitsLT(MVT::f64)) {
6457     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6458                        DAG.getIntPtrConstant(0));
6459   } else if (DestVT.bitsGT(MVT::f64)) {
6460     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6461   }
6462
6463   // Handle final rounding.
6464   return Sub;
6465 }
6466
6467 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6468                                            SelectionDAG &DAG) const {
6469   SDValue N0 = Op.getOperand(0);
6470   DebugLoc dl = Op.getDebugLoc();
6471
6472   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6473   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6474   // the optimization here.
6475   if (DAG.SignBitIsZero(N0))
6476     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6477
6478   EVT SrcVT = N0.getValueType();
6479   EVT DstVT = Op.getValueType();
6480   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6481     return LowerUINT_TO_FP_i64(Op, DAG);
6482   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6483     return LowerUINT_TO_FP_i32(Op, DAG);
6484
6485   // Make a 64-bit buffer, and use it to build an FILD.
6486   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6487   if (SrcVT == MVT::i32) {
6488     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6489     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6490                                      getPointerTy(), StackSlot, WordOff);
6491     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6492                                   StackSlot, MachinePointerInfo(),
6493                                   false, false, 0);
6494     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6495                                   OffsetSlot, MachinePointerInfo(),
6496                                   false, false, 0);
6497     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6498     return Fild;
6499   }
6500
6501   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6502   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6503                                 StackSlot, MachinePointerInfo(),
6504                                false, false, 0);
6505   // For i64 source, we need to add the appropriate power of 2 if the input
6506   // was negative.  This is the same as the optimization in
6507   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6508   // we must be careful to do the computation in x87 extended precision, not
6509   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6510   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6511   MachineMemOperand *MMO =
6512     DAG.getMachineFunction()
6513     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6514                           MachineMemOperand::MOLoad, 8, 8);
6515   
6516   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6517   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6518   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6519                                          MVT::i64, MMO);
6520
6521   APInt FF(32, 0x5F800000ULL);
6522
6523   // Check whether the sign bit is set.
6524   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6525                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6526                                  ISD::SETLT);
6527
6528   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6529   SDValue FudgePtr = DAG.getConstantPool(
6530                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6531                                          getPointerTy());
6532
6533   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6534   SDValue Zero = DAG.getIntPtrConstant(0);
6535   SDValue Four = DAG.getIntPtrConstant(4);
6536   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6537                                Zero, Four);
6538   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6539
6540   // Load the value out, extending it from f32 to f80.
6541   // FIXME: Avoid the extend by constructing the right constant pool?
6542   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6543                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6544                                  MVT::f32, false, false, 4);
6545   // Extend everything to 80 bits to force it to be done on x87.
6546   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6547   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6548 }
6549
6550 std::pair<SDValue,SDValue> X86TargetLowering::
6551 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6552   DebugLoc DL = Op.getDebugLoc();
6553
6554   EVT DstTy = Op.getValueType();
6555
6556   if (!IsSigned) {
6557     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6558     DstTy = MVT::i64;
6559   }
6560
6561   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6562          DstTy.getSimpleVT() >= MVT::i16 &&
6563          "Unknown FP_TO_SINT to lower!");
6564
6565   // These are really Legal.
6566   if (DstTy == MVT::i32 &&
6567       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6568     return std::make_pair(SDValue(), SDValue());
6569   if (Subtarget->is64Bit() &&
6570       DstTy == MVT::i64 &&
6571       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6572     return std::make_pair(SDValue(), SDValue());
6573
6574   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6575   // stack slot.
6576   MachineFunction &MF = DAG.getMachineFunction();
6577   unsigned MemSize = DstTy.getSizeInBits()/8;
6578   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6579   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6580
6581   
6582   
6583   unsigned Opc;
6584   switch (DstTy.getSimpleVT().SimpleTy) {
6585   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6586   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6587   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6588   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6589   }
6590
6591   SDValue Chain = DAG.getEntryNode();
6592   SDValue Value = Op.getOperand(0);
6593   EVT TheVT = Op.getOperand(0).getValueType();
6594   if (isScalarFPTypeInSSEReg(TheVT)) {
6595     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6596     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6597                          MachinePointerInfo::getFixedStack(SSFI),
6598                          false, false, 0);
6599     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6600     SDValue Ops[] = {
6601       Chain, StackSlot, DAG.getValueType(TheVT)
6602     };
6603     
6604     MachineMemOperand *MMO =
6605       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6606                               MachineMemOperand::MOLoad, MemSize, MemSize);
6607     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6608                                     DstTy, MMO);
6609     Chain = Value.getValue(1);
6610     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6611     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6612   }
6613   
6614   MachineMemOperand *MMO =
6615     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6616                             MachineMemOperand::MOStore, MemSize, MemSize);
6617
6618   // Build the FP_TO_INT*_IN_MEM
6619   SDValue Ops[] = { Chain, Value, StackSlot };
6620   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6621                                          Ops, 3, DstTy, MMO);
6622
6623   return std::make_pair(FIST, StackSlot);
6624 }
6625
6626 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6627                                            SelectionDAG &DAG) const {
6628   if (Op.getValueType().isVector())
6629     return SDValue();
6630
6631   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6632   SDValue FIST = Vals.first, StackSlot = Vals.second;
6633   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6634   if (FIST.getNode() == 0) return Op;
6635
6636   // Load the result.
6637   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6638                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6639 }
6640
6641 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6642                                            SelectionDAG &DAG) const {
6643   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6644   SDValue FIST = Vals.first, StackSlot = Vals.second;
6645   assert(FIST.getNode() && "Unexpected failure");
6646
6647   // Load the result.
6648   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6649                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6650 }
6651
6652 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6653                                      SelectionDAG &DAG) const {
6654   LLVMContext *Context = DAG.getContext();
6655   DebugLoc dl = Op.getDebugLoc();
6656   EVT VT = Op.getValueType();
6657   EVT EltVT = VT;
6658   if (VT.isVector())
6659     EltVT = VT.getVectorElementType();
6660   std::vector<Constant*> CV;
6661   if (EltVT == MVT::f64) {
6662     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6663     CV.push_back(C);
6664     CV.push_back(C);
6665   } else {
6666     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6667     CV.push_back(C);
6668     CV.push_back(C);
6669     CV.push_back(C);
6670     CV.push_back(C);
6671   }
6672   Constant *C = ConstantVector::get(CV);
6673   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6674   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6675                              MachinePointerInfo::getConstantPool(),
6676                              false, false, 16);
6677   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6678 }
6679
6680 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6681   LLVMContext *Context = DAG.getContext();
6682   DebugLoc dl = Op.getDebugLoc();
6683   EVT VT = Op.getValueType();
6684   EVT EltVT = VT;
6685   if (VT.isVector())
6686     EltVT = VT.getVectorElementType();
6687   std::vector<Constant*> CV;
6688   if (EltVT == MVT::f64) {
6689     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6690     CV.push_back(C);
6691     CV.push_back(C);
6692   } else {
6693     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6694     CV.push_back(C);
6695     CV.push_back(C);
6696     CV.push_back(C);
6697     CV.push_back(C);
6698   }
6699   Constant *C = ConstantVector::get(CV);
6700   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6701   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6702                              MachinePointerInfo::getConstantPool(),
6703                              false, false, 16);
6704   if (VT.isVector()) {
6705     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6706                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6707                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6708                                 Op.getOperand(0)),
6709                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6710   } else {
6711     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6712   }
6713 }
6714
6715 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6716   LLVMContext *Context = DAG.getContext();
6717   SDValue Op0 = Op.getOperand(0);
6718   SDValue Op1 = Op.getOperand(1);
6719   DebugLoc dl = Op.getDebugLoc();
6720   EVT VT = Op.getValueType();
6721   EVT SrcVT = Op1.getValueType();
6722
6723   // If second operand is smaller, extend it first.
6724   if (SrcVT.bitsLT(VT)) {
6725     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6726     SrcVT = VT;
6727   }
6728   // And if it is bigger, shrink it first.
6729   if (SrcVT.bitsGT(VT)) {
6730     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6731     SrcVT = VT;
6732   }
6733
6734   // At this point the operands and the result should have the same
6735   // type, and that won't be f80 since that is not custom lowered.
6736
6737   // First get the sign bit of second operand.
6738   std::vector<Constant*> CV;
6739   if (SrcVT == MVT::f64) {
6740     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6741     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6742   } else {
6743     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6744     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6745     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6746     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6747   }
6748   Constant *C = ConstantVector::get(CV);
6749   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6750   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6751                               MachinePointerInfo::getConstantPool(),
6752                               false, false, 16);
6753   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6754
6755   // Shift sign bit right or left if the two operands have different types.
6756   if (SrcVT.bitsGT(VT)) {
6757     // Op0 is MVT::f32, Op1 is MVT::f64.
6758     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6759     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6760                           DAG.getConstant(32, MVT::i32));
6761     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6762     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6763                           DAG.getIntPtrConstant(0));
6764   }
6765
6766   // Clear first operand sign bit.
6767   CV.clear();
6768   if (VT == MVT::f64) {
6769     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6770     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6771   } else {
6772     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6773     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6774     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6775     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6776   }
6777   C = ConstantVector::get(CV);
6778   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6779   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6780                               MachinePointerInfo::getConstantPool(),
6781                               false, false, 16);
6782   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6783
6784   // Or the value with the sign bit.
6785   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6786 }
6787
6788 /// Emit nodes that will be selected as "test Op0,Op0", or something
6789 /// equivalent.
6790 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6791                                     SelectionDAG &DAG) const {
6792   DebugLoc dl = Op.getDebugLoc();
6793
6794   // CF and OF aren't always set the way we want. Determine which
6795   // of these we need.
6796   bool NeedCF = false;
6797   bool NeedOF = false;
6798   switch (X86CC) {
6799   default: break;
6800   case X86::COND_A: case X86::COND_AE:
6801   case X86::COND_B: case X86::COND_BE:
6802     NeedCF = true;
6803     break;
6804   case X86::COND_G: case X86::COND_GE:
6805   case X86::COND_L: case X86::COND_LE:
6806   case X86::COND_O: case X86::COND_NO:
6807     NeedOF = true;
6808     break;
6809   }
6810
6811   // See if we can use the EFLAGS value from the operand instead of
6812   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6813   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6814   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6815     // Emit a CMP with 0, which is the TEST pattern.
6816     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6817                        DAG.getConstant(0, Op.getValueType()));
6818
6819   unsigned Opcode = 0;
6820   unsigned NumOperands = 0;
6821   switch (Op.getNode()->getOpcode()) {
6822   case ISD::ADD:
6823     // Due to an isel shortcoming, be conservative if this add is likely to be
6824     // selected as part of a load-modify-store instruction. When the root node
6825     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6826     // uses of other nodes in the match, such as the ADD in this case. This
6827     // leads to the ADD being left around and reselected, with the result being
6828     // two adds in the output.  Alas, even if none our users are stores, that
6829     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6830     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6831     // climbing the DAG back to the root, and it doesn't seem to be worth the
6832     // effort.
6833     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6834            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6835       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6836         goto default_case;
6837
6838     if (ConstantSDNode *C =
6839         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6840       // An add of one will be selected as an INC.
6841       if (C->getAPIntValue() == 1) {
6842         Opcode = X86ISD::INC;
6843         NumOperands = 1;
6844         break;
6845       }
6846
6847       // An add of negative one (subtract of one) will be selected as a DEC.
6848       if (C->getAPIntValue().isAllOnesValue()) {
6849         Opcode = X86ISD::DEC;
6850         NumOperands = 1;
6851         break;
6852       }
6853     }
6854
6855     // Otherwise use a regular EFLAGS-setting add.
6856     Opcode = X86ISD::ADD;
6857     NumOperands = 2;
6858     break;
6859   case ISD::AND: {
6860     // If the primary and result isn't used, don't bother using X86ISD::AND,
6861     // because a TEST instruction will be better.
6862     bool NonFlagUse = false;
6863     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6864            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6865       SDNode *User = *UI;
6866       unsigned UOpNo = UI.getOperandNo();
6867       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6868         // Look pass truncate.
6869         UOpNo = User->use_begin().getOperandNo();
6870         User = *User->use_begin();
6871       }
6872
6873       if (User->getOpcode() != ISD::BRCOND &&
6874           User->getOpcode() != ISD::SETCC &&
6875           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6876         NonFlagUse = true;
6877         break;
6878       }
6879     }
6880
6881     if (!NonFlagUse)
6882       break;
6883   }
6884     // FALL THROUGH
6885   case ISD::SUB:
6886   case ISD::OR:
6887   case ISD::XOR:
6888     // Due to the ISEL shortcoming noted above, be conservative if this op is
6889     // likely to be selected as part of a load-modify-store instruction.
6890     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6891            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6892       if (UI->getOpcode() == ISD::STORE)
6893         goto default_case;
6894
6895     // Otherwise use a regular EFLAGS-setting instruction.
6896     switch (Op.getNode()->getOpcode()) {
6897     default: llvm_unreachable("unexpected operator!");
6898     case ISD::SUB: Opcode = X86ISD::SUB; break;
6899     case ISD::OR:  Opcode = X86ISD::OR;  break;
6900     case ISD::XOR: Opcode = X86ISD::XOR; break;
6901     case ISD::AND: Opcode = X86ISD::AND; break;
6902     }
6903
6904     NumOperands = 2;
6905     break;
6906   case X86ISD::ADD:
6907   case X86ISD::SUB:
6908   case X86ISD::INC:
6909   case X86ISD::DEC:
6910   case X86ISD::OR:
6911   case X86ISD::XOR:
6912   case X86ISD::AND:
6913     return SDValue(Op.getNode(), 1);
6914   default:
6915   default_case:
6916     break;
6917   }
6918
6919   if (Opcode == 0)
6920     // Emit a CMP with 0, which is the TEST pattern.
6921     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6922                        DAG.getConstant(0, Op.getValueType()));
6923
6924   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6925   SmallVector<SDValue, 4> Ops;
6926   for (unsigned i = 0; i != NumOperands; ++i)
6927     Ops.push_back(Op.getOperand(i));
6928
6929   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6930   DAG.ReplaceAllUsesWith(Op, New);
6931   return SDValue(New.getNode(), 1);
6932 }
6933
6934 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6935 /// equivalent.
6936 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6937                                    SelectionDAG &DAG) const {
6938   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6939     if (C->getAPIntValue() == 0)
6940       return EmitTest(Op0, X86CC, DAG);
6941
6942   DebugLoc dl = Op0.getDebugLoc();
6943   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6944 }
6945
6946 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6947 /// if it's possible.
6948 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6949                                      DebugLoc dl, SelectionDAG &DAG) const {
6950   SDValue Op0 = And.getOperand(0);
6951   SDValue Op1 = And.getOperand(1);
6952   if (Op0.getOpcode() == ISD::TRUNCATE)
6953     Op0 = Op0.getOperand(0);
6954   if (Op1.getOpcode() == ISD::TRUNCATE)
6955     Op1 = Op1.getOperand(0);
6956
6957   SDValue LHS, RHS;
6958   if (Op1.getOpcode() == ISD::SHL)
6959     std::swap(Op0, Op1);
6960   if (Op0.getOpcode() == ISD::SHL) {
6961     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6962       if (And00C->getZExtValue() == 1) {
6963         // If we looked past a truncate, check that it's only truncating away
6964         // known zeros.
6965         unsigned BitWidth = Op0.getValueSizeInBits();
6966         unsigned AndBitWidth = And.getValueSizeInBits();
6967         if (BitWidth > AndBitWidth) {
6968           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6969           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6970           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6971             return SDValue();
6972         }
6973         LHS = Op1;
6974         RHS = Op0.getOperand(1);
6975       }
6976   } else if (Op1.getOpcode() == ISD::Constant) {
6977     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6978     SDValue AndLHS = Op0;
6979     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6980       LHS = AndLHS.getOperand(0);
6981       RHS = AndLHS.getOperand(1);
6982     }
6983   }
6984
6985   if (LHS.getNode()) {
6986     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6987     // instruction.  Since the shift amount is in-range-or-undefined, we know
6988     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6989     // the encoding for the i16 version is larger than the i32 version.
6990     // Also promote i16 to i32 for performance / code size reason.
6991     if (LHS.getValueType() == MVT::i8 ||
6992         LHS.getValueType() == MVT::i16)
6993       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6994
6995     // If the operand types disagree, extend the shift amount to match.  Since
6996     // BT ignores high bits (like shifts) we can use anyextend.
6997     if (LHS.getValueType() != RHS.getValueType())
6998       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6999
7000     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7001     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7002     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7003                        DAG.getConstant(Cond, MVT::i8), BT);
7004   }
7005
7006   return SDValue();
7007 }
7008
7009 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7010   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7011   SDValue Op0 = Op.getOperand(0);
7012   SDValue Op1 = Op.getOperand(1);
7013   DebugLoc dl = Op.getDebugLoc();
7014   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7015
7016   // Optimize to BT if possible.
7017   // Lower (X & (1 << N)) == 0 to BT(X, N).
7018   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7019   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7020   if (Op0.getOpcode() == ISD::AND &&
7021       Op0.hasOneUse() &&
7022       Op1.getOpcode() == ISD::Constant &&
7023       cast<ConstantSDNode>(Op1)->isNullValue() &&
7024       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7025     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7026     if (NewSetCC.getNode())
7027       return NewSetCC;
7028   }
7029
7030   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7031   if (Op0.getOpcode() == X86ISD::SETCC &&
7032       Op1.getOpcode() == ISD::Constant &&
7033       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7034        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7035       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7036     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7037     bool Invert = (CC == ISD::SETNE) ^
7038       cast<ConstantSDNode>(Op1)->isNullValue();
7039     if (Invert)
7040       CCode = X86::GetOppositeBranchCondition(CCode);
7041     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7042                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7043   }
7044
7045   bool isFP = Op1.getValueType().isFloatingPoint();
7046   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7047   if (X86CC == X86::COND_INVALID)
7048     return SDValue();
7049
7050   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7051
7052   // Use sbb x, x to materialize carry bit into a GPR.
7053   if (X86CC == X86::COND_B)
7054     return DAG.getNode(ISD::AND, dl, MVT::i8,
7055                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7056                                    DAG.getConstant(X86CC, MVT::i8), Cond),
7057                        DAG.getConstant(1, MVT::i8));
7058
7059   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7060                      DAG.getConstant(X86CC, MVT::i8), Cond);
7061 }
7062
7063 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7064   SDValue Cond;
7065   SDValue Op0 = Op.getOperand(0);
7066   SDValue Op1 = Op.getOperand(1);
7067   SDValue CC = Op.getOperand(2);
7068   EVT VT = Op.getValueType();
7069   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7070   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7071   DebugLoc dl = Op.getDebugLoc();
7072
7073   if (isFP) {
7074     unsigned SSECC = 8;
7075     EVT VT0 = Op0.getValueType();
7076     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7077     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7078     bool Swap = false;
7079
7080     switch (SetCCOpcode) {
7081     default: break;
7082     case ISD::SETOEQ:
7083     case ISD::SETEQ:  SSECC = 0; break;
7084     case ISD::SETOGT:
7085     case ISD::SETGT: Swap = true; // Fallthrough
7086     case ISD::SETLT:
7087     case ISD::SETOLT: SSECC = 1; break;
7088     case ISD::SETOGE:
7089     case ISD::SETGE: Swap = true; // Fallthrough
7090     case ISD::SETLE:
7091     case ISD::SETOLE: SSECC = 2; break;
7092     case ISD::SETUO:  SSECC = 3; break;
7093     case ISD::SETUNE:
7094     case ISD::SETNE:  SSECC = 4; break;
7095     case ISD::SETULE: Swap = true;
7096     case ISD::SETUGE: SSECC = 5; break;
7097     case ISD::SETULT: Swap = true;
7098     case ISD::SETUGT: SSECC = 6; break;
7099     case ISD::SETO:   SSECC = 7; break;
7100     }
7101     if (Swap)
7102       std::swap(Op0, Op1);
7103
7104     // In the two special cases we can't handle, emit two comparisons.
7105     if (SSECC == 8) {
7106       if (SetCCOpcode == ISD::SETUEQ) {
7107         SDValue UNORD, EQ;
7108         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7109         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7110         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7111       }
7112       else if (SetCCOpcode == ISD::SETONE) {
7113         SDValue ORD, NEQ;
7114         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7115         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7116         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7117       }
7118       llvm_unreachable("Illegal FP comparison");
7119     }
7120     // Handle all other FP comparisons here.
7121     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7122   }
7123
7124   // We are handling one of the integer comparisons here.  Since SSE only has
7125   // GT and EQ comparisons for integer, swapping operands and multiple
7126   // operations may be required for some comparisons.
7127   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7128   bool Swap = false, Invert = false, FlipSigns = false;
7129
7130   switch (VT.getSimpleVT().SimpleTy) {
7131   default: break;
7132   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7133   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7134   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7135   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7136   }
7137
7138   switch (SetCCOpcode) {
7139   default: break;
7140   case ISD::SETNE:  Invert = true;
7141   case ISD::SETEQ:  Opc = EQOpc; break;
7142   case ISD::SETLT:  Swap = true;
7143   case ISD::SETGT:  Opc = GTOpc; break;
7144   case ISD::SETGE:  Swap = true;
7145   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7146   case ISD::SETULT: Swap = true;
7147   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7148   case ISD::SETUGE: Swap = true;
7149   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7150   }
7151   if (Swap)
7152     std::swap(Op0, Op1);
7153
7154   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7155   // bits of the inputs before performing those operations.
7156   if (FlipSigns) {
7157     EVT EltVT = VT.getVectorElementType();
7158     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7159                                       EltVT);
7160     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7161     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7162                                     SignBits.size());
7163     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7164     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7165   }
7166
7167   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7168
7169   // If the logical-not of the result is required, perform that now.
7170   if (Invert)
7171     Result = DAG.getNOT(dl, Result, VT);
7172
7173   return Result;
7174 }
7175
7176 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7177 static bool isX86LogicalCmp(SDValue Op) {
7178   unsigned Opc = Op.getNode()->getOpcode();
7179   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7180     return true;
7181   if (Op.getResNo() == 1 &&
7182       (Opc == X86ISD::ADD ||
7183        Opc == X86ISD::SUB ||
7184        Opc == X86ISD::SMUL ||
7185        Opc == X86ISD::UMUL ||
7186        Opc == X86ISD::INC ||
7187        Opc == X86ISD::DEC ||
7188        Opc == X86ISD::OR ||
7189        Opc == X86ISD::XOR ||
7190        Opc == X86ISD::AND))
7191     return true;
7192
7193   return false;
7194 }
7195
7196 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7197   bool addTest = true;
7198   SDValue Cond  = Op.getOperand(0);
7199   DebugLoc dl = Op.getDebugLoc();
7200   SDValue CC;
7201
7202   if (Cond.getOpcode() == ISD::SETCC) {
7203     SDValue NewCond = LowerSETCC(Cond, DAG);
7204     if (NewCond.getNode())
7205       Cond = NewCond;
7206   }
7207
7208   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7209   SDValue Op1 = Op.getOperand(1);
7210   SDValue Op2 = Op.getOperand(2);
7211   if (Cond.getOpcode() == X86ISD::SETCC &&
7212       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7213     SDValue Cmp = Cond.getOperand(1);
7214     if (Cmp.getOpcode() == X86ISD::CMP) {
7215       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7216       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7217       ConstantSDNode *RHSC =
7218         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7219       if (N1C && N1C->isAllOnesValue() &&
7220           N2C && N2C->isNullValue() &&
7221           RHSC && RHSC->isNullValue()) {
7222         SDValue CmpOp0 = Cmp.getOperand(0);
7223         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7224                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7225         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7226                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7227       }
7228     }
7229   }
7230
7231   // Look pass (and (setcc_carry (cmp ...)), 1).
7232   if (Cond.getOpcode() == ISD::AND &&
7233       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7234     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7235     if (C && C->getAPIntValue() == 1) 
7236       Cond = Cond.getOperand(0);
7237   }
7238
7239   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7240   // setting operand in place of the X86ISD::SETCC.
7241   if (Cond.getOpcode() == X86ISD::SETCC ||
7242       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7243     CC = Cond.getOperand(0);
7244
7245     SDValue Cmp = Cond.getOperand(1);
7246     unsigned Opc = Cmp.getOpcode();
7247     EVT VT = Op.getValueType();
7248
7249     bool IllegalFPCMov = false;
7250     if (VT.isFloatingPoint() && !VT.isVector() &&
7251         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7252       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7253
7254     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7255         Opc == X86ISD::BT) { // FIXME
7256       Cond = Cmp;
7257       addTest = false;
7258     }
7259   }
7260
7261   if (addTest) {
7262     // Look pass the truncate.
7263     if (Cond.getOpcode() == ISD::TRUNCATE)
7264       Cond = Cond.getOperand(0);
7265
7266     // We know the result of AND is compared against zero. Try to match
7267     // it to BT.
7268     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7269       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7270       if (NewSetCC.getNode()) {
7271         CC = NewSetCC.getOperand(0);
7272         Cond = NewSetCC.getOperand(1);
7273         addTest = false;
7274       }
7275     }
7276   }
7277
7278   if (addTest) {
7279     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7280     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7281   }
7282
7283   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7284   // condition is true.
7285   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7286   SDValue Ops[] = { Op2, Op1, CC, Cond };
7287   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7288 }
7289
7290 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7291 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7292 // from the AND / OR.
7293 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7294   Opc = Op.getOpcode();
7295   if (Opc != ISD::OR && Opc != ISD::AND)
7296     return false;
7297   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7298           Op.getOperand(0).hasOneUse() &&
7299           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7300           Op.getOperand(1).hasOneUse());
7301 }
7302
7303 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7304 // 1 and that the SETCC node has a single use.
7305 static bool isXor1OfSetCC(SDValue Op) {
7306   if (Op.getOpcode() != ISD::XOR)
7307     return false;
7308   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7309   if (N1C && N1C->getAPIntValue() == 1) {
7310     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7311       Op.getOperand(0).hasOneUse();
7312   }
7313   return false;
7314 }
7315
7316 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7317   bool addTest = true;
7318   SDValue Chain = Op.getOperand(0);
7319   SDValue Cond  = Op.getOperand(1);
7320   SDValue Dest  = Op.getOperand(2);
7321   DebugLoc dl = Op.getDebugLoc();
7322   SDValue CC;
7323
7324   if (Cond.getOpcode() == ISD::SETCC) {
7325     SDValue NewCond = LowerSETCC(Cond, DAG);
7326     if (NewCond.getNode())
7327       Cond = NewCond;
7328   }
7329 #if 0
7330   // FIXME: LowerXALUO doesn't handle these!!
7331   else if (Cond.getOpcode() == X86ISD::ADD  ||
7332            Cond.getOpcode() == X86ISD::SUB  ||
7333            Cond.getOpcode() == X86ISD::SMUL ||
7334            Cond.getOpcode() == X86ISD::UMUL)
7335     Cond = LowerXALUO(Cond, DAG);
7336 #endif
7337
7338   // Look pass (and (setcc_carry (cmp ...)), 1).
7339   if (Cond.getOpcode() == ISD::AND &&
7340       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7341     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7342     if (C && C->getAPIntValue() == 1) 
7343       Cond = Cond.getOperand(0);
7344   }
7345
7346   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7347   // setting operand in place of the X86ISD::SETCC.
7348   if (Cond.getOpcode() == X86ISD::SETCC ||
7349       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7350     CC = Cond.getOperand(0);
7351
7352     SDValue Cmp = Cond.getOperand(1);
7353     unsigned Opc = Cmp.getOpcode();
7354     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7355     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7356       Cond = Cmp;
7357       addTest = false;
7358     } else {
7359       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7360       default: break;
7361       case X86::COND_O:
7362       case X86::COND_B:
7363         // These can only come from an arithmetic instruction with overflow,
7364         // e.g. SADDO, UADDO.
7365         Cond = Cond.getNode()->getOperand(1);
7366         addTest = false;
7367         break;
7368       }
7369     }
7370   } else {
7371     unsigned CondOpc;
7372     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7373       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7374       if (CondOpc == ISD::OR) {
7375         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7376         // two branches instead of an explicit OR instruction with a
7377         // separate test.
7378         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7379             isX86LogicalCmp(Cmp)) {
7380           CC = Cond.getOperand(0).getOperand(0);
7381           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7382                               Chain, Dest, CC, Cmp);
7383           CC = Cond.getOperand(1).getOperand(0);
7384           Cond = Cmp;
7385           addTest = false;
7386         }
7387       } else { // ISD::AND
7388         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7389         // two branches instead of an explicit AND instruction with a
7390         // separate test. However, we only do this if this block doesn't
7391         // have a fall-through edge, because this requires an explicit
7392         // jmp when the condition is false.
7393         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7394             isX86LogicalCmp(Cmp) &&
7395             Op.getNode()->hasOneUse()) {
7396           X86::CondCode CCode =
7397             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7398           CCode = X86::GetOppositeBranchCondition(CCode);
7399           CC = DAG.getConstant(CCode, MVT::i8);
7400           SDNode *User = *Op.getNode()->use_begin();
7401           // Look for an unconditional branch following this conditional branch.
7402           // We need this because we need to reverse the successors in order
7403           // to implement FCMP_OEQ.
7404           if (User->getOpcode() == ISD::BR) {
7405             SDValue FalseBB = User->getOperand(1);
7406             SDNode *NewBR =
7407               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7408             assert(NewBR == User);
7409             (void)NewBR;
7410             Dest = FalseBB;
7411
7412             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7413                                 Chain, Dest, CC, Cmp);
7414             X86::CondCode CCode =
7415               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7416             CCode = X86::GetOppositeBranchCondition(CCode);
7417             CC = DAG.getConstant(CCode, MVT::i8);
7418             Cond = Cmp;
7419             addTest = false;
7420           }
7421         }
7422       }
7423     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7424       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7425       // It should be transformed during dag combiner except when the condition
7426       // is set by a arithmetics with overflow node.
7427       X86::CondCode CCode =
7428         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7429       CCode = X86::GetOppositeBranchCondition(CCode);
7430       CC = DAG.getConstant(CCode, MVT::i8);
7431       Cond = Cond.getOperand(0).getOperand(1);
7432       addTest = false;
7433     }
7434   }
7435
7436   if (addTest) {
7437     // Look pass the truncate.
7438     if (Cond.getOpcode() == ISD::TRUNCATE)
7439       Cond = Cond.getOperand(0);
7440
7441     // We know the result of AND is compared against zero. Try to match
7442     // it to BT.
7443     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7444       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7445       if (NewSetCC.getNode()) {
7446         CC = NewSetCC.getOperand(0);
7447         Cond = NewSetCC.getOperand(1);
7448         addTest = false;
7449       }
7450     }
7451   }
7452
7453   if (addTest) {
7454     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7455     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7456   }
7457   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7458                      Chain, Dest, CC, Cond);
7459 }
7460
7461
7462 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7463 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7464 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7465 // that the guard pages used by the OS virtual memory manager are allocated in
7466 // correct sequence.
7467 SDValue
7468 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7469                                            SelectionDAG &DAG) const {
7470   assert(Subtarget->isTargetCygMing() &&
7471          "This should be used only on Cygwin/Mingw targets");
7472   DebugLoc dl = Op.getDebugLoc();
7473
7474   // Get the inputs.
7475   SDValue Chain = Op.getOperand(0);
7476   SDValue Size  = Op.getOperand(1);
7477   // FIXME: Ensure alignment here
7478
7479   SDValue Flag;
7480
7481   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7482
7483   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7484   Flag = Chain.getValue(1);
7485
7486   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7487
7488   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7489   Flag = Chain.getValue(1);
7490
7491   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7492
7493   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7494   return DAG.getMergeValues(Ops1, 2, dl);
7495 }
7496
7497 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7498   MachineFunction &MF = DAG.getMachineFunction();
7499   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7500
7501   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7502   DebugLoc DL = Op.getDebugLoc();
7503
7504   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7505     // vastart just stores the address of the VarArgsFrameIndex slot into the
7506     // memory location argument.
7507     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7508                                    getPointerTy());
7509     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7510                         MachinePointerInfo(SV), false, false, 0);
7511   }
7512
7513   // __va_list_tag:
7514   //   gp_offset         (0 - 6 * 8)
7515   //   fp_offset         (48 - 48 + 8 * 16)
7516   //   overflow_arg_area (point to parameters coming in memory).
7517   //   reg_save_area
7518   SmallVector<SDValue, 8> MemOps;
7519   SDValue FIN = Op.getOperand(1);
7520   // Store gp_offset
7521   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7522                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7523                                                MVT::i32),
7524                                FIN, MachinePointerInfo(SV), false, false, 0);
7525   MemOps.push_back(Store);
7526
7527   // Store fp_offset
7528   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7529                     FIN, DAG.getIntPtrConstant(4));
7530   Store = DAG.getStore(Op.getOperand(0), DL,
7531                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7532                                        MVT::i32),
7533                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7534   MemOps.push_back(Store);
7535
7536   // Store ptr to overflow_arg_area
7537   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7538                     FIN, DAG.getIntPtrConstant(4));
7539   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7540                                     getPointerTy());
7541   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7542                        MachinePointerInfo(SV, 8),
7543                        false, false, 0);
7544   MemOps.push_back(Store);
7545
7546   // Store ptr to reg_save_area.
7547   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7548                     FIN, DAG.getIntPtrConstant(8));
7549   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7550                                     getPointerTy());
7551   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7552                        MachinePointerInfo(SV, 16), false, false, 0);
7553   MemOps.push_back(Store);
7554   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7555                      &MemOps[0], MemOps.size());
7556 }
7557
7558 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7559   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7560   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7561
7562   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7563   return SDValue();
7564 }
7565
7566 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7567   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7568   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7569   SDValue Chain = Op.getOperand(0);
7570   SDValue DstPtr = Op.getOperand(1);
7571   SDValue SrcPtr = Op.getOperand(2);
7572   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7573   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7574   DebugLoc DL = Op.getDebugLoc();
7575
7576   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7577                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7578                        false, 
7579                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7580 }
7581
7582 SDValue
7583 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7584   DebugLoc dl = Op.getDebugLoc();
7585   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7586   switch (IntNo) {
7587   default: return SDValue();    // Don't custom lower most intrinsics.
7588   // Comparison intrinsics.
7589   case Intrinsic::x86_sse_comieq_ss:
7590   case Intrinsic::x86_sse_comilt_ss:
7591   case Intrinsic::x86_sse_comile_ss:
7592   case Intrinsic::x86_sse_comigt_ss:
7593   case Intrinsic::x86_sse_comige_ss:
7594   case Intrinsic::x86_sse_comineq_ss:
7595   case Intrinsic::x86_sse_ucomieq_ss:
7596   case Intrinsic::x86_sse_ucomilt_ss:
7597   case Intrinsic::x86_sse_ucomile_ss:
7598   case Intrinsic::x86_sse_ucomigt_ss:
7599   case Intrinsic::x86_sse_ucomige_ss:
7600   case Intrinsic::x86_sse_ucomineq_ss:
7601   case Intrinsic::x86_sse2_comieq_sd:
7602   case Intrinsic::x86_sse2_comilt_sd:
7603   case Intrinsic::x86_sse2_comile_sd:
7604   case Intrinsic::x86_sse2_comigt_sd:
7605   case Intrinsic::x86_sse2_comige_sd:
7606   case Intrinsic::x86_sse2_comineq_sd:
7607   case Intrinsic::x86_sse2_ucomieq_sd:
7608   case Intrinsic::x86_sse2_ucomilt_sd:
7609   case Intrinsic::x86_sse2_ucomile_sd:
7610   case Intrinsic::x86_sse2_ucomigt_sd:
7611   case Intrinsic::x86_sse2_ucomige_sd:
7612   case Intrinsic::x86_sse2_ucomineq_sd: {
7613     unsigned Opc = 0;
7614     ISD::CondCode CC = ISD::SETCC_INVALID;
7615     switch (IntNo) {
7616     default: break;
7617     case Intrinsic::x86_sse_comieq_ss:
7618     case Intrinsic::x86_sse2_comieq_sd:
7619       Opc = X86ISD::COMI;
7620       CC = ISD::SETEQ;
7621       break;
7622     case Intrinsic::x86_sse_comilt_ss:
7623     case Intrinsic::x86_sse2_comilt_sd:
7624       Opc = X86ISD::COMI;
7625       CC = ISD::SETLT;
7626       break;
7627     case Intrinsic::x86_sse_comile_ss:
7628     case Intrinsic::x86_sse2_comile_sd:
7629       Opc = X86ISD::COMI;
7630       CC = ISD::SETLE;
7631       break;
7632     case Intrinsic::x86_sse_comigt_ss:
7633     case Intrinsic::x86_sse2_comigt_sd:
7634       Opc = X86ISD::COMI;
7635       CC = ISD::SETGT;
7636       break;
7637     case Intrinsic::x86_sse_comige_ss:
7638     case Intrinsic::x86_sse2_comige_sd:
7639       Opc = X86ISD::COMI;
7640       CC = ISD::SETGE;
7641       break;
7642     case Intrinsic::x86_sse_comineq_ss:
7643     case Intrinsic::x86_sse2_comineq_sd:
7644       Opc = X86ISD::COMI;
7645       CC = ISD::SETNE;
7646       break;
7647     case Intrinsic::x86_sse_ucomieq_ss:
7648     case Intrinsic::x86_sse2_ucomieq_sd:
7649       Opc = X86ISD::UCOMI;
7650       CC = ISD::SETEQ;
7651       break;
7652     case Intrinsic::x86_sse_ucomilt_ss:
7653     case Intrinsic::x86_sse2_ucomilt_sd:
7654       Opc = X86ISD::UCOMI;
7655       CC = ISD::SETLT;
7656       break;
7657     case Intrinsic::x86_sse_ucomile_ss:
7658     case Intrinsic::x86_sse2_ucomile_sd:
7659       Opc = X86ISD::UCOMI;
7660       CC = ISD::SETLE;
7661       break;
7662     case Intrinsic::x86_sse_ucomigt_ss:
7663     case Intrinsic::x86_sse2_ucomigt_sd:
7664       Opc = X86ISD::UCOMI;
7665       CC = ISD::SETGT;
7666       break;
7667     case Intrinsic::x86_sse_ucomige_ss:
7668     case Intrinsic::x86_sse2_ucomige_sd:
7669       Opc = X86ISD::UCOMI;
7670       CC = ISD::SETGE;
7671       break;
7672     case Intrinsic::x86_sse_ucomineq_ss:
7673     case Intrinsic::x86_sse2_ucomineq_sd:
7674       Opc = X86ISD::UCOMI;
7675       CC = ISD::SETNE;
7676       break;
7677     }
7678
7679     SDValue LHS = Op.getOperand(1);
7680     SDValue RHS = Op.getOperand(2);
7681     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7682     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7683     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7684     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7685                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7686     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7687   }
7688   // ptest and testp intrinsics. The intrinsic these come from are designed to
7689   // return an integer value, not just an instruction so lower it to the ptest
7690   // or testp pattern and a setcc for the result.
7691   case Intrinsic::x86_sse41_ptestz:
7692   case Intrinsic::x86_sse41_ptestc:
7693   case Intrinsic::x86_sse41_ptestnzc:
7694   case Intrinsic::x86_avx_ptestz_256:
7695   case Intrinsic::x86_avx_ptestc_256:
7696   case Intrinsic::x86_avx_ptestnzc_256:
7697   case Intrinsic::x86_avx_vtestz_ps:
7698   case Intrinsic::x86_avx_vtestc_ps:
7699   case Intrinsic::x86_avx_vtestnzc_ps:
7700   case Intrinsic::x86_avx_vtestz_pd:
7701   case Intrinsic::x86_avx_vtestc_pd:
7702   case Intrinsic::x86_avx_vtestnzc_pd:
7703   case Intrinsic::x86_avx_vtestz_ps_256:
7704   case Intrinsic::x86_avx_vtestc_ps_256:
7705   case Intrinsic::x86_avx_vtestnzc_ps_256:
7706   case Intrinsic::x86_avx_vtestz_pd_256:
7707   case Intrinsic::x86_avx_vtestc_pd_256:
7708   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7709     bool IsTestPacked = false;
7710     unsigned X86CC = 0;
7711     switch (IntNo) {
7712     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7713     case Intrinsic::x86_avx_vtestz_ps:
7714     case Intrinsic::x86_avx_vtestz_pd:
7715     case Intrinsic::x86_avx_vtestz_ps_256:
7716     case Intrinsic::x86_avx_vtestz_pd_256:
7717       IsTestPacked = true; // Fallthrough
7718     case Intrinsic::x86_sse41_ptestz:
7719     case Intrinsic::x86_avx_ptestz_256:
7720       // ZF = 1
7721       X86CC = X86::COND_E;
7722       break;
7723     case Intrinsic::x86_avx_vtestc_ps:
7724     case Intrinsic::x86_avx_vtestc_pd:
7725     case Intrinsic::x86_avx_vtestc_ps_256:
7726     case Intrinsic::x86_avx_vtestc_pd_256:
7727       IsTestPacked = true; // Fallthrough
7728     case Intrinsic::x86_sse41_ptestc:
7729     case Intrinsic::x86_avx_ptestc_256:
7730       // CF = 1
7731       X86CC = X86::COND_B;
7732       break;
7733     case Intrinsic::x86_avx_vtestnzc_ps:
7734     case Intrinsic::x86_avx_vtestnzc_pd:
7735     case Intrinsic::x86_avx_vtestnzc_ps_256:
7736     case Intrinsic::x86_avx_vtestnzc_pd_256:
7737       IsTestPacked = true; // Fallthrough
7738     case Intrinsic::x86_sse41_ptestnzc:
7739     case Intrinsic::x86_avx_ptestnzc_256:
7740       // ZF and CF = 0
7741       X86CC = X86::COND_A;
7742       break;
7743     }
7744
7745     SDValue LHS = Op.getOperand(1);
7746     SDValue RHS = Op.getOperand(2);
7747     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7748     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7749     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7750     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7751     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7752   }
7753
7754   // Fix vector shift instructions where the last operand is a non-immediate
7755   // i32 value.
7756   case Intrinsic::x86_sse2_pslli_w:
7757   case Intrinsic::x86_sse2_pslli_d:
7758   case Intrinsic::x86_sse2_pslli_q:
7759   case Intrinsic::x86_sse2_psrli_w:
7760   case Intrinsic::x86_sse2_psrli_d:
7761   case Intrinsic::x86_sse2_psrli_q:
7762   case Intrinsic::x86_sse2_psrai_w:
7763   case Intrinsic::x86_sse2_psrai_d:
7764   case Intrinsic::x86_mmx_pslli_w:
7765   case Intrinsic::x86_mmx_pslli_d:
7766   case Intrinsic::x86_mmx_pslli_q:
7767   case Intrinsic::x86_mmx_psrli_w:
7768   case Intrinsic::x86_mmx_psrli_d:
7769   case Intrinsic::x86_mmx_psrli_q:
7770   case Intrinsic::x86_mmx_psrai_w:
7771   case Intrinsic::x86_mmx_psrai_d: {
7772     SDValue ShAmt = Op.getOperand(2);
7773     if (isa<ConstantSDNode>(ShAmt))
7774       return SDValue();
7775
7776     unsigned NewIntNo = 0;
7777     EVT ShAmtVT = MVT::v4i32;
7778     switch (IntNo) {
7779     case Intrinsic::x86_sse2_pslli_w:
7780       NewIntNo = Intrinsic::x86_sse2_psll_w;
7781       break;
7782     case Intrinsic::x86_sse2_pslli_d:
7783       NewIntNo = Intrinsic::x86_sse2_psll_d;
7784       break;
7785     case Intrinsic::x86_sse2_pslli_q:
7786       NewIntNo = Intrinsic::x86_sse2_psll_q;
7787       break;
7788     case Intrinsic::x86_sse2_psrli_w:
7789       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7790       break;
7791     case Intrinsic::x86_sse2_psrli_d:
7792       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7793       break;
7794     case Intrinsic::x86_sse2_psrli_q:
7795       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7796       break;
7797     case Intrinsic::x86_sse2_psrai_w:
7798       NewIntNo = Intrinsic::x86_sse2_psra_w;
7799       break;
7800     case Intrinsic::x86_sse2_psrai_d:
7801       NewIntNo = Intrinsic::x86_sse2_psra_d;
7802       break;
7803     default: {
7804       ShAmtVT = MVT::v2i32;
7805       switch (IntNo) {
7806       case Intrinsic::x86_mmx_pslli_w:
7807         NewIntNo = Intrinsic::x86_mmx_psll_w;
7808         break;
7809       case Intrinsic::x86_mmx_pslli_d:
7810         NewIntNo = Intrinsic::x86_mmx_psll_d;
7811         break;
7812       case Intrinsic::x86_mmx_pslli_q:
7813         NewIntNo = Intrinsic::x86_mmx_psll_q;
7814         break;
7815       case Intrinsic::x86_mmx_psrli_w:
7816         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7817         break;
7818       case Intrinsic::x86_mmx_psrli_d:
7819         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7820         break;
7821       case Intrinsic::x86_mmx_psrli_q:
7822         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7823         break;
7824       case Intrinsic::x86_mmx_psrai_w:
7825         NewIntNo = Intrinsic::x86_mmx_psra_w;
7826         break;
7827       case Intrinsic::x86_mmx_psrai_d:
7828         NewIntNo = Intrinsic::x86_mmx_psra_d;
7829         break;
7830       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7831       }
7832       break;
7833     }
7834     }
7835
7836     // The vector shift intrinsics with scalars uses 32b shift amounts but
7837     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7838     // to be zero.
7839     SDValue ShOps[4];
7840     ShOps[0] = ShAmt;
7841     ShOps[1] = DAG.getConstant(0, MVT::i32);
7842     if (ShAmtVT == MVT::v4i32) {
7843       ShOps[2] = DAG.getUNDEF(MVT::i32);
7844       ShOps[3] = DAG.getUNDEF(MVT::i32);
7845       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7846     } else {
7847       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7848 // FIXME this must be lowered to get rid of the invalid type.
7849     }
7850
7851     EVT VT = Op.getValueType();
7852     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7853     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7854                        DAG.getConstant(NewIntNo, MVT::i32),
7855                        Op.getOperand(1), ShAmt);
7856   }
7857   }
7858 }
7859
7860 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7861                                            SelectionDAG &DAG) const {
7862   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7863   MFI->setReturnAddressIsTaken(true);
7864
7865   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7866   DebugLoc dl = Op.getDebugLoc();
7867
7868   if (Depth > 0) {
7869     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7870     SDValue Offset =
7871       DAG.getConstant(TD->getPointerSize(),
7872                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7873     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7874                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7875                                    FrameAddr, Offset),
7876                        MachinePointerInfo(), false, false, 0);
7877   }
7878
7879   // Just load the return address.
7880   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7881   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7882                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7883 }
7884
7885 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7886   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7887   MFI->setFrameAddressIsTaken(true);
7888
7889   EVT VT = Op.getValueType();
7890   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7891   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7892   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7893   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7894   while (Depth--)
7895     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7896                             MachinePointerInfo(),
7897                             false, false, 0);
7898   return FrameAddr;
7899 }
7900
7901 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7902                                                      SelectionDAG &DAG) const {
7903   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7904 }
7905
7906 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7907   MachineFunction &MF = DAG.getMachineFunction();
7908   SDValue Chain     = Op.getOperand(0);
7909   SDValue Offset    = Op.getOperand(1);
7910   SDValue Handler   = Op.getOperand(2);
7911   DebugLoc dl       = Op.getDebugLoc();
7912
7913   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7914                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7915                                      getPointerTy());
7916   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7917
7918   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7919                                   DAG.getIntPtrConstant(TD->getPointerSize()));
7920   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7921   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
7922                        false, false, 0);
7923   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7924   MF.getRegInfo().addLiveOut(StoreAddrReg);
7925
7926   return DAG.getNode(X86ISD::EH_RETURN, dl,
7927                      MVT::Other,
7928                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7929 }
7930
7931 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7932                                              SelectionDAG &DAG) const {
7933   SDValue Root = Op.getOperand(0);
7934   SDValue Trmp = Op.getOperand(1); // trampoline
7935   SDValue FPtr = Op.getOperand(2); // nested function
7936   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7937   DebugLoc dl  = Op.getDebugLoc();
7938
7939   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7940
7941   if (Subtarget->is64Bit()) {
7942     SDValue OutChains[6];
7943
7944     // Large code-model.
7945     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7946     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7947
7948     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7949     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7950
7951     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7952
7953     // Load the pointer to the nested function into R11.
7954     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7955     SDValue Addr = Trmp;
7956     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7957                                 Addr, MachinePointerInfo(TrmpAddr),
7958                                 false, false, 0);
7959
7960     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7961                        DAG.getConstant(2, MVT::i64));
7962     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
7963                                 MachinePointerInfo(TrmpAddr, 2),
7964                                 false, false, 2);
7965
7966     // Load the 'nest' parameter value into R10.
7967     // R10 is specified in X86CallingConv.td
7968     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7969     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7970                        DAG.getConstant(10, MVT::i64));
7971     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7972                                 Addr, MachinePointerInfo(TrmpAddr, 10),
7973                                 false, false, 0);
7974
7975     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7976                        DAG.getConstant(12, MVT::i64));
7977     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
7978                                 MachinePointerInfo(TrmpAddr, 12),
7979                                 false, false, 2);
7980
7981     // Jump to the nested function.
7982     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7983     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7984                        DAG.getConstant(20, MVT::i64));
7985     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7986                                 Addr, MachinePointerInfo(TrmpAddr, 20),
7987                                 false, false, 0);
7988
7989     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7990     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7991                        DAG.getConstant(22, MVT::i64));
7992     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7993                                 MachinePointerInfo(TrmpAddr, 22),
7994                                 false, false, 0);
7995
7996     SDValue Ops[] =
7997       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7998     return DAG.getMergeValues(Ops, 2, dl);
7999   } else {
8000     const Function *Func =
8001       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8002     CallingConv::ID CC = Func->getCallingConv();
8003     unsigned NestReg;
8004
8005     switch (CC) {
8006     default:
8007       llvm_unreachable("Unsupported calling convention");
8008     case CallingConv::C:
8009     case CallingConv::X86_StdCall: {
8010       // Pass 'nest' parameter in ECX.
8011       // Must be kept in sync with X86CallingConv.td
8012       NestReg = X86::ECX;
8013
8014       // Check that ECX wasn't needed by an 'inreg' parameter.
8015       const FunctionType *FTy = Func->getFunctionType();
8016       const AttrListPtr &Attrs = Func->getAttributes();
8017
8018       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8019         unsigned InRegCount = 0;
8020         unsigned Idx = 1;
8021
8022         for (FunctionType::param_iterator I = FTy->param_begin(),
8023              E = FTy->param_end(); I != E; ++I, ++Idx)
8024           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8025             // FIXME: should only count parameters that are lowered to integers.
8026             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8027
8028         if (InRegCount > 2) {
8029           report_fatal_error("Nest register in use - reduce number of inreg"
8030                              " parameters!");
8031         }
8032       }
8033       break;
8034     }
8035     case CallingConv::X86_FastCall:
8036     case CallingConv::X86_ThisCall:
8037     case CallingConv::Fast:
8038       // Pass 'nest' parameter in EAX.
8039       // Must be kept in sync with X86CallingConv.td
8040       NestReg = X86::EAX;
8041       break;
8042     }
8043
8044     SDValue OutChains[4];
8045     SDValue Addr, Disp;
8046
8047     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8048                        DAG.getConstant(10, MVT::i32));
8049     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8050
8051     // This is storing the opcode for MOV32ri.
8052     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8053     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8054     OutChains[0] = DAG.getStore(Root, dl,
8055                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8056                                 Trmp, MachinePointerInfo(TrmpAddr),
8057                                 false, false, 0);
8058
8059     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8060                        DAG.getConstant(1, MVT::i32));
8061     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8062                                 MachinePointerInfo(TrmpAddr, 1),
8063                                 false, false, 1);
8064
8065     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8066     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8067                        DAG.getConstant(5, MVT::i32));
8068     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8069                                 MachinePointerInfo(TrmpAddr, 5),
8070                                 false, false, 1);
8071
8072     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8073                        DAG.getConstant(6, MVT::i32));
8074     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8075                                 MachinePointerInfo(TrmpAddr, 6),
8076                                 false, false, 1);
8077
8078     SDValue Ops[] =
8079       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8080     return DAG.getMergeValues(Ops, 2, dl);
8081   }
8082 }
8083
8084 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8085                                             SelectionDAG &DAG) const {
8086   /*
8087    The rounding mode is in bits 11:10 of FPSR, and has the following
8088    settings:
8089      00 Round to nearest
8090      01 Round to -inf
8091      10 Round to +inf
8092      11 Round to 0
8093
8094   FLT_ROUNDS, on the other hand, expects the following:
8095     -1 Undefined
8096      0 Round to 0
8097      1 Round to nearest
8098      2 Round to +inf
8099      3 Round to -inf
8100
8101   To perform the conversion, we do:
8102     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8103   */
8104
8105   MachineFunction &MF = DAG.getMachineFunction();
8106   const TargetMachine &TM = MF.getTarget();
8107   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8108   unsigned StackAlignment = TFI.getStackAlignment();
8109   EVT VT = Op.getValueType();
8110   DebugLoc DL = Op.getDebugLoc();
8111
8112   // Save FP Control Word to stack slot
8113   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8114   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8115
8116   
8117   MachineMemOperand *MMO =
8118    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8119                            MachineMemOperand::MOStore, 2, 2);
8120   
8121   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8122   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8123                                           DAG.getVTList(MVT::Other),
8124                                           Ops, 2, MVT::i16, MMO);
8125
8126   // Load FP Control Word from stack slot
8127   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8128                             MachinePointerInfo(), false, false, 0);
8129
8130   // Transform as necessary
8131   SDValue CWD1 =
8132     DAG.getNode(ISD::SRL, DL, MVT::i16,
8133                 DAG.getNode(ISD::AND, DL, MVT::i16,
8134                             CWD, DAG.getConstant(0x800, MVT::i16)),
8135                 DAG.getConstant(11, MVT::i8));
8136   SDValue CWD2 =
8137     DAG.getNode(ISD::SRL, DL, MVT::i16,
8138                 DAG.getNode(ISD::AND, DL, MVT::i16,
8139                             CWD, DAG.getConstant(0x400, MVT::i16)),
8140                 DAG.getConstant(9, MVT::i8));
8141
8142   SDValue RetVal =
8143     DAG.getNode(ISD::AND, DL, MVT::i16,
8144                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8145                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8146                             DAG.getConstant(1, MVT::i16)),
8147                 DAG.getConstant(3, MVT::i16));
8148
8149
8150   return DAG.getNode((VT.getSizeInBits() < 16 ?
8151                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8152 }
8153
8154 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8155   EVT VT = Op.getValueType();
8156   EVT OpVT = VT;
8157   unsigned NumBits = VT.getSizeInBits();
8158   DebugLoc dl = Op.getDebugLoc();
8159
8160   Op = Op.getOperand(0);
8161   if (VT == MVT::i8) {
8162     // Zero extend to i32 since there is not an i8 bsr.
8163     OpVT = MVT::i32;
8164     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8165   }
8166
8167   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8168   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8169   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8170
8171   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8172   SDValue Ops[] = {
8173     Op,
8174     DAG.getConstant(NumBits+NumBits-1, OpVT),
8175     DAG.getConstant(X86::COND_E, MVT::i8),
8176     Op.getValue(1)
8177   };
8178   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8179
8180   // Finally xor with NumBits-1.
8181   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8182
8183   if (VT == MVT::i8)
8184     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8185   return Op;
8186 }
8187
8188 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8189   EVT VT = Op.getValueType();
8190   EVT OpVT = VT;
8191   unsigned NumBits = VT.getSizeInBits();
8192   DebugLoc dl = Op.getDebugLoc();
8193
8194   Op = Op.getOperand(0);
8195   if (VT == MVT::i8) {
8196     OpVT = MVT::i32;
8197     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8198   }
8199
8200   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8201   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8202   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8203
8204   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8205   SDValue Ops[] = {
8206     Op,
8207     DAG.getConstant(NumBits, OpVT),
8208     DAG.getConstant(X86::COND_E, MVT::i8),
8209     Op.getValue(1)
8210   };
8211   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8212
8213   if (VT == MVT::i8)
8214     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8215   return Op;
8216 }
8217
8218 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8219   EVT VT = Op.getValueType();
8220   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8221   DebugLoc dl = Op.getDebugLoc();
8222
8223   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8224   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8225   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8226   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8227   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8228   //
8229   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8230   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8231   //  return AloBlo + AloBhi + AhiBlo;
8232
8233   SDValue A = Op.getOperand(0);
8234   SDValue B = Op.getOperand(1);
8235
8236   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8237                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8238                        A, DAG.getConstant(32, MVT::i32));
8239   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8240                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8241                        B, DAG.getConstant(32, MVT::i32));
8242   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8243                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8244                        A, B);
8245   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8246                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8247                        A, Bhi);
8248   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8249                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8250                        Ahi, B);
8251   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8252                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8253                        AloBhi, DAG.getConstant(32, MVT::i32));
8254   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8255                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8256                        AhiBlo, DAG.getConstant(32, MVT::i32));
8257   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8258   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8259   return Res;
8260 }
8261
8262 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8263   EVT VT = Op.getValueType();
8264   DebugLoc dl = Op.getDebugLoc();
8265   SDValue R = Op.getOperand(0);
8266
8267   LLVMContext *Context = DAG.getContext();
8268
8269   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8270
8271   if (VT == MVT::v4i32) {
8272     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8273                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8274                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8275
8276     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8277     
8278     std::vector<Constant*> CV(4, CI);
8279     Constant *C = ConstantVector::get(CV);
8280     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8281     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8282                                  MachinePointerInfo::getConstantPool(),
8283                                  false, false, 16);
8284
8285     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8286     Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8287     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8288     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8289   }
8290   if (VT == MVT::v16i8) {
8291     // a = a << 5;
8292     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8293                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8294                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8295
8296     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8297     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8298
8299     std::vector<Constant*> CVM1(16, CM1);
8300     std::vector<Constant*> CVM2(16, CM2);
8301     Constant *C = ConstantVector::get(CVM1);
8302     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8303     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8304                             MachinePointerInfo::getConstantPool(),
8305                             false, false, 16);
8306
8307     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8308     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8309     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8310                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8311                     DAG.getConstant(4, MVT::i32));
8312     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8313                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8314                     R, M, Op);
8315     // a += a
8316     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8317     
8318     C = ConstantVector::get(CVM2);
8319     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8320     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8321                     MachinePointerInfo::getConstantPool(),
8322                     false, false, 16);
8323     
8324     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8325     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8326     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8327                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8328                     DAG.getConstant(2, MVT::i32));
8329     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8330                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8331                     R, M, Op);
8332     // a += a
8333     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8334     
8335     // return pblendv(r, r+r, a);
8336     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8337                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8338                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8339     return R;
8340   }
8341   return SDValue();
8342 }
8343
8344 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8345   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8346   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8347   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8348   // has only one use.
8349   SDNode *N = Op.getNode();
8350   SDValue LHS = N->getOperand(0);
8351   SDValue RHS = N->getOperand(1);
8352   unsigned BaseOp = 0;
8353   unsigned Cond = 0;
8354   DebugLoc dl = Op.getDebugLoc();
8355
8356   switch (Op.getOpcode()) {
8357   default: llvm_unreachable("Unknown ovf instruction!");
8358   case ISD::SADDO:
8359     // A subtract of one will be selected as a INC. Note that INC doesn't
8360     // set CF, so we can't do this for UADDO.
8361     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8362       if (C->getAPIntValue() == 1) {
8363         BaseOp = X86ISD::INC;
8364         Cond = X86::COND_O;
8365         break;
8366       }
8367     BaseOp = X86ISD::ADD;
8368     Cond = X86::COND_O;
8369     break;
8370   case ISD::UADDO:
8371     BaseOp = X86ISD::ADD;
8372     Cond = X86::COND_B;
8373     break;
8374   case ISD::SSUBO:
8375     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8376     // set CF, so we can't do this for USUBO.
8377     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8378       if (C->getAPIntValue() == 1) {
8379         BaseOp = X86ISD::DEC;
8380         Cond = X86::COND_O;
8381         break;
8382       }
8383     BaseOp = X86ISD::SUB;
8384     Cond = X86::COND_O;
8385     break;
8386   case ISD::USUBO:
8387     BaseOp = X86ISD::SUB;
8388     Cond = X86::COND_B;
8389     break;
8390   case ISD::SMULO:
8391     BaseOp = X86ISD::SMUL;
8392     Cond = X86::COND_O;
8393     break;
8394   case ISD::UMULO:
8395     BaseOp = X86ISD::UMUL;
8396     Cond = X86::COND_B;
8397     break;
8398   }
8399
8400   // Also sets EFLAGS.
8401   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8402   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8403
8404   SDValue SetCC =
8405     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8406                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8407
8408   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8409   return Sum;
8410 }
8411
8412 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8413   DebugLoc dl = Op.getDebugLoc();
8414   
8415   if (!Subtarget->hasSSE2()) {
8416     SDValue Chain = Op.getOperand(0);
8417     SDValue Zero = DAG.getConstant(0, 
8418                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8419     SDValue Ops[] = {
8420       DAG.getRegister(X86::ESP, MVT::i32), // Base
8421       DAG.getTargetConstant(1, MVT::i8),   // Scale
8422       DAG.getRegister(0, MVT::i32),        // Index
8423       DAG.getTargetConstant(0, MVT::i32),  // Disp
8424       DAG.getRegister(0, MVT::i32),        // Segment.
8425       Zero,
8426       Chain
8427     };
8428     SDNode *Res = 
8429       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8430                           array_lengthof(Ops));
8431     return SDValue(Res, 0);
8432   }
8433   
8434   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8435   if (!isDev)
8436     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8437   
8438   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8439   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8440   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8441   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8442   
8443   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8444   if (!Op1 && !Op2 && !Op3 && Op4)
8445     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8446   
8447   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8448   if (Op1 && !Op2 && !Op3 && !Op4)
8449     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8450   
8451   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 
8452   //           (MFENCE)>;
8453   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8454 }
8455
8456 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8457   EVT T = Op.getValueType();
8458   DebugLoc DL = Op.getDebugLoc();
8459   unsigned Reg = 0;
8460   unsigned size = 0;
8461   switch(T.getSimpleVT().SimpleTy) {
8462   default:
8463     assert(false && "Invalid value type!");
8464   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8465   case MVT::i16: Reg = X86::AX;  size = 2; break;
8466   case MVT::i32: Reg = X86::EAX; size = 4; break;
8467   case MVT::i64:
8468     assert(Subtarget->is64Bit() && "Node not type legal!");
8469     Reg = X86::RAX; size = 8;
8470     break;
8471   }
8472   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8473                                     Op.getOperand(2), SDValue());
8474   SDValue Ops[] = { cpIn.getValue(0),
8475                     Op.getOperand(1),
8476                     Op.getOperand(3),
8477                     DAG.getTargetConstant(size, MVT::i8),
8478                     cpIn.getValue(1) };
8479   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8480   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8481   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8482                                            Ops, 5, T, MMO);
8483   SDValue cpOut =
8484     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8485   return cpOut;
8486 }
8487
8488 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8489                                                  SelectionDAG &DAG) const {
8490   assert(Subtarget->is64Bit() && "Result not type legalized?");
8491   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8492   SDValue TheChain = Op.getOperand(0);
8493   DebugLoc dl = Op.getDebugLoc();
8494   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8495   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8496   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8497                                    rax.getValue(2));
8498   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8499                             DAG.getConstant(32, MVT::i8));
8500   SDValue Ops[] = {
8501     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8502     rdx.getValue(1)
8503   };
8504   return DAG.getMergeValues(Ops, 2, dl);
8505 }
8506
8507 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8508                                             SelectionDAG &DAG) const {
8509   EVT SrcVT = Op.getOperand(0).getValueType();
8510   EVT DstVT = Op.getValueType();
8511   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
8512           Subtarget->hasMMX() && !DisableMMX) &&
8513          "Unexpected custom BIT_CONVERT");
8514   assert((DstVT == MVT::i64 || 
8515           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8516          "Unexpected custom BIT_CONVERT");
8517   // i64 <=> MMX conversions are Legal.
8518   if (SrcVT==MVT::i64 && DstVT.isVector())
8519     return Op;
8520   if (DstVT==MVT::i64 && SrcVT.isVector())
8521     return Op;
8522   // MMX <=> MMX conversions are Legal.
8523   if (SrcVT.isVector() && DstVT.isVector())
8524     return Op;
8525   // All other conversions need to be expanded.
8526   return SDValue();
8527 }
8528 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8529   SDNode *Node = Op.getNode();
8530   DebugLoc dl = Node->getDebugLoc();
8531   EVT T = Node->getValueType(0);
8532   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8533                               DAG.getConstant(0, T), Node->getOperand(2));
8534   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8535                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8536                        Node->getOperand(0),
8537                        Node->getOperand(1), negOp,
8538                        cast<AtomicSDNode>(Node)->getSrcValue(),
8539                        cast<AtomicSDNode>(Node)->getAlignment());
8540 }
8541
8542 /// LowerOperation - Provide custom lowering hooks for some operations.
8543 ///
8544 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8545   switch (Op.getOpcode()) {
8546   default: llvm_unreachable("Should not custom lower this!");
8547   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8548   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8549   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8550   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8551   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8552   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8553   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8554   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8555   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8556   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8557   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8558   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8559   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8560   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8561   case ISD::SHL_PARTS:
8562   case ISD::SRA_PARTS:
8563   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8564   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8565   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8566   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8567   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8568   case ISD::FABS:               return LowerFABS(Op, DAG);
8569   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8570   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8571   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8572   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8573   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8574   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8575   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8576   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8577   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8578   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8579   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8580   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8581   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8582   case ISD::FRAME_TO_ARGS_OFFSET:
8583                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8584   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8585   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8586   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8587   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8588   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8589   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8590   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8591   case ISD::SHL:                return LowerSHL(Op, DAG);
8592   case ISD::SADDO:
8593   case ISD::UADDO:
8594   case ISD::SSUBO:
8595   case ISD::USUBO:
8596   case ISD::SMULO:
8597   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8598   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8599   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
8600   }
8601 }
8602
8603 void X86TargetLowering::
8604 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8605                         SelectionDAG &DAG, unsigned NewOp) const {
8606   EVT T = Node->getValueType(0);
8607   DebugLoc dl = Node->getDebugLoc();
8608   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8609
8610   SDValue Chain = Node->getOperand(0);
8611   SDValue In1 = Node->getOperand(1);
8612   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8613                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8614   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8615                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8616   SDValue Ops[] = { Chain, In1, In2L, In2H };
8617   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8618   SDValue Result =
8619     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8620                             cast<MemSDNode>(Node)->getMemOperand());
8621   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8622   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8623   Results.push_back(Result.getValue(2));
8624 }
8625
8626 /// ReplaceNodeResults - Replace a node with an illegal result type
8627 /// with a new node built out of custom code.
8628 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8629                                            SmallVectorImpl<SDValue>&Results,
8630                                            SelectionDAG &DAG) const {
8631   DebugLoc dl = N->getDebugLoc();
8632   switch (N->getOpcode()) {
8633   default:
8634     assert(false && "Do not know how to custom type legalize this operation!");
8635     return;
8636   case ISD::FP_TO_SINT: {
8637     std::pair<SDValue,SDValue> Vals =
8638         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8639     SDValue FIST = Vals.first, StackSlot = Vals.second;
8640     if (FIST.getNode() != 0) {
8641       EVT VT = N->getValueType(0);
8642       // Return a load from the stack slot.
8643       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8644                                     MachinePointerInfo(), false, false, 0));
8645     }
8646     return;
8647   }
8648   case ISD::READCYCLECOUNTER: {
8649     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8650     SDValue TheChain = N->getOperand(0);
8651     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8652     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8653                                      rd.getValue(1));
8654     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8655                                      eax.getValue(2));
8656     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8657     SDValue Ops[] = { eax, edx };
8658     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8659     Results.push_back(edx.getValue(1));
8660     return;
8661   }
8662   case ISD::ATOMIC_CMP_SWAP: {
8663     EVT T = N->getValueType(0);
8664     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8665     SDValue cpInL, cpInH;
8666     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8667                         DAG.getConstant(0, MVT::i32));
8668     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8669                         DAG.getConstant(1, MVT::i32));
8670     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8671     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8672                              cpInL.getValue(1));
8673     SDValue swapInL, swapInH;
8674     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8675                           DAG.getConstant(0, MVT::i32));
8676     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8677                           DAG.getConstant(1, MVT::i32));
8678     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8679                                cpInH.getValue(1));
8680     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8681                                swapInL.getValue(1));
8682     SDValue Ops[] = { swapInH.getValue(0),
8683                       N->getOperand(1),
8684                       swapInH.getValue(1) };
8685     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8686     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8687     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8688                                         MVT::i32, Result.getValue(1));
8689     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8690                                         MVT::i32, cpOutL.getValue(2));
8691     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8692     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8693     Results.push_back(cpOutH.getValue(1));
8694     return;
8695   }
8696   case ISD::ATOMIC_LOAD_ADD:
8697     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8698     return;
8699   case ISD::ATOMIC_LOAD_AND:
8700     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8701     return;
8702   case ISD::ATOMIC_LOAD_NAND:
8703     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8704     return;
8705   case ISD::ATOMIC_LOAD_OR:
8706     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8707     return;
8708   case ISD::ATOMIC_LOAD_SUB:
8709     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8710     return;
8711   case ISD::ATOMIC_LOAD_XOR:
8712     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8713     return;
8714   case ISD::ATOMIC_SWAP:
8715     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8716     return;
8717   }
8718 }
8719
8720 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8721   switch (Opcode) {
8722   default: return NULL;
8723   case X86ISD::BSF:                return "X86ISD::BSF";
8724   case X86ISD::BSR:                return "X86ISD::BSR";
8725   case X86ISD::SHLD:               return "X86ISD::SHLD";
8726   case X86ISD::SHRD:               return "X86ISD::SHRD";
8727   case X86ISD::FAND:               return "X86ISD::FAND";
8728   case X86ISD::FOR:                return "X86ISD::FOR";
8729   case X86ISD::FXOR:               return "X86ISD::FXOR";
8730   case X86ISD::FSRL:               return "X86ISD::FSRL";
8731   case X86ISD::FILD:               return "X86ISD::FILD";
8732   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8733   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8734   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8735   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8736   case X86ISD::FLD:                return "X86ISD::FLD";
8737   case X86ISD::FST:                return "X86ISD::FST";
8738   case X86ISD::CALL:               return "X86ISD::CALL";
8739   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8740   case X86ISD::BT:                 return "X86ISD::BT";
8741   case X86ISD::CMP:                return "X86ISD::CMP";
8742   case X86ISD::COMI:               return "X86ISD::COMI";
8743   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8744   case X86ISD::SETCC:              return "X86ISD::SETCC";
8745   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8746   case X86ISD::CMOV:               return "X86ISD::CMOV";
8747   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8748   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8749   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8750   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8751   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8752   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8753   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8754   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8755   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8756   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8757   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8758   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8759   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8760   case X86ISD::FMAX:               return "X86ISD::FMAX";
8761   case X86ISD::FMIN:               return "X86ISD::FMIN";
8762   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8763   case X86ISD::FRCP:               return "X86ISD::FRCP";
8764   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8765   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8766   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8767   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8768   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8769   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8770   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8771   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8772   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8773   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8774   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8775   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8776   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8777   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8778   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8779   case X86ISD::VSHL:               return "X86ISD::VSHL";
8780   case X86ISD::VSRL:               return "X86ISD::VSRL";
8781   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8782   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8783   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8784   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8785   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8786   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8787   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8788   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8789   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8790   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8791   case X86ISD::ADD:                return "X86ISD::ADD";
8792   case X86ISD::SUB:                return "X86ISD::SUB";
8793   case X86ISD::SMUL:               return "X86ISD::SMUL";
8794   case X86ISD::UMUL:               return "X86ISD::UMUL";
8795   case X86ISD::INC:                return "X86ISD::INC";
8796   case X86ISD::DEC:                return "X86ISD::DEC";
8797   case X86ISD::OR:                 return "X86ISD::OR";
8798   case X86ISD::XOR:                return "X86ISD::XOR";
8799   case X86ISD::AND:                return "X86ISD::AND";
8800   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8801   case X86ISD::PTEST:              return "X86ISD::PTEST";
8802   case X86ISD::TESTP:              return "X86ISD::TESTP";
8803   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8804   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8805   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8806   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8807   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8808   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8809   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8810   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8811   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8812   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8813   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8814   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8815   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8816   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8817   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8818   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8819   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8820   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8821   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8822   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8823   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8824   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8825   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8826   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8827   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8828   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8829   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8830   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8831   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8832   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8833   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8834   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8835   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8836   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8837   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
8838   }
8839 }
8840
8841 // isLegalAddressingMode - Return true if the addressing mode represented
8842 // by AM is legal for this target, for a load/store of the specified type.
8843 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8844                                               const Type *Ty) const {
8845   // X86 supports extremely general addressing modes.
8846   CodeModel::Model M = getTargetMachine().getCodeModel();
8847   Reloc::Model R = getTargetMachine().getRelocationModel();
8848
8849   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8850   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8851     return false;
8852
8853   if (AM.BaseGV) {
8854     unsigned GVFlags =
8855       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8856
8857     // If a reference to this global requires an extra load, we can't fold it.
8858     if (isGlobalStubReference(GVFlags))
8859       return false;
8860
8861     // If BaseGV requires a register for the PIC base, we cannot also have a
8862     // BaseReg specified.
8863     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8864       return false;
8865
8866     // If lower 4G is not available, then we must use rip-relative addressing.
8867     if ((M != CodeModel::Small || R != Reloc::Static) &&
8868         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8869       return false;
8870   }
8871
8872   switch (AM.Scale) {
8873   case 0:
8874   case 1:
8875   case 2:
8876   case 4:
8877   case 8:
8878     // These scales always work.
8879     break;
8880   case 3:
8881   case 5:
8882   case 9:
8883     // These scales are formed with basereg+scalereg.  Only accept if there is
8884     // no basereg yet.
8885     if (AM.HasBaseReg)
8886       return false;
8887     break;
8888   default:  // Other stuff never works.
8889     return false;
8890   }
8891
8892   return true;
8893 }
8894
8895
8896 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8897   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8898     return false;
8899   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8900   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8901   if (NumBits1 <= NumBits2)
8902     return false;
8903   return true;
8904 }
8905
8906 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8907   if (!VT1.isInteger() || !VT2.isInteger())
8908     return false;
8909   unsigned NumBits1 = VT1.getSizeInBits();
8910   unsigned NumBits2 = VT2.getSizeInBits();
8911   if (NumBits1 <= NumBits2)
8912     return false;
8913   return true;
8914 }
8915
8916 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8917   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8918   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8919 }
8920
8921 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8922   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8923   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8924 }
8925
8926 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8927   // i16 instructions are longer (0x66 prefix) and potentially slower.
8928   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8929 }
8930
8931 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8932 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8933 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8934 /// are assumed to be legal.
8935 bool
8936 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8937                                       EVT VT) const {
8938   // Very little shuffling can be done for 64-bit vectors right now.
8939   if (VT.getSizeInBits() == 64)
8940     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8941
8942   // FIXME: pshufb, blends, shifts.
8943   return (VT.getVectorNumElements() == 2 ||
8944           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8945           isMOVLMask(M, VT) ||
8946           isSHUFPMask(M, VT) ||
8947           isPSHUFDMask(M, VT) ||
8948           isPSHUFHWMask(M, VT) ||
8949           isPSHUFLWMask(M, VT) ||
8950           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8951           isUNPCKLMask(M, VT) ||
8952           isUNPCKHMask(M, VT) ||
8953           isUNPCKL_v_undef_Mask(M, VT) ||
8954           isUNPCKH_v_undef_Mask(M, VT));
8955 }
8956
8957 bool
8958 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8959                                           EVT VT) const {
8960   unsigned NumElts = VT.getVectorNumElements();
8961   // FIXME: This collection of masks seems suspect.
8962   if (NumElts == 2)
8963     return true;
8964   if (NumElts == 4 && VT.getSizeInBits() == 128) {
8965     return (isMOVLMask(Mask, VT)  ||
8966             isCommutedMOVLMask(Mask, VT, true) ||
8967             isSHUFPMask(Mask, VT) ||
8968             isCommutedSHUFPMask(Mask, VT));
8969   }
8970   return false;
8971 }
8972
8973 //===----------------------------------------------------------------------===//
8974 //                           X86 Scheduler Hooks
8975 //===----------------------------------------------------------------------===//
8976
8977 // private utility function
8978 MachineBasicBlock *
8979 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8980                                                        MachineBasicBlock *MBB,
8981                                                        unsigned regOpc,
8982                                                        unsigned immOpc,
8983                                                        unsigned LoadOpc,
8984                                                        unsigned CXchgOpc,
8985                                                        unsigned notOpc,
8986                                                        unsigned EAXreg,
8987                                                        TargetRegisterClass *RC,
8988                                                        bool invSrc) const {
8989   // For the atomic bitwise operator, we generate
8990   //   thisMBB:
8991   //   newMBB:
8992   //     ld  t1 = [bitinstr.addr]
8993   //     op  t2 = t1, [bitinstr.val]
8994   //     mov EAX = t1
8995   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8996   //     bz  newMBB
8997   //     fallthrough -->nextMBB
8998   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8999   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9000   MachineFunction::iterator MBBIter = MBB;
9001   ++MBBIter;
9002
9003   /// First build the CFG
9004   MachineFunction *F = MBB->getParent();
9005   MachineBasicBlock *thisMBB = MBB;
9006   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9007   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9008   F->insert(MBBIter, newMBB);
9009   F->insert(MBBIter, nextMBB);
9010
9011   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9012   nextMBB->splice(nextMBB->begin(), thisMBB,
9013                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9014                   thisMBB->end());
9015   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9016
9017   // Update thisMBB to fall through to newMBB
9018   thisMBB->addSuccessor(newMBB);
9019
9020   // newMBB jumps to itself and fall through to nextMBB
9021   newMBB->addSuccessor(nextMBB);
9022   newMBB->addSuccessor(newMBB);
9023
9024   // Insert instructions into newMBB based on incoming instruction
9025   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9026          "unexpected number of operands");
9027   DebugLoc dl = bInstr->getDebugLoc();
9028   MachineOperand& destOper = bInstr->getOperand(0);
9029   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9030   int numArgs = bInstr->getNumOperands() - 1;
9031   for (int i=0; i < numArgs; ++i)
9032     argOpers[i] = &bInstr->getOperand(i+1);
9033
9034   // x86 address has 4 operands: base, index, scale, and displacement
9035   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9036   int valArgIndx = lastAddrIndx + 1;
9037
9038   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9039   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9040   for (int i=0; i <= lastAddrIndx; ++i)
9041     (*MIB).addOperand(*argOpers[i]);
9042
9043   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9044   if (invSrc) {
9045     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9046   }
9047   else
9048     tt = t1;
9049
9050   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9051   assert((argOpers[valArgIndx]->isReg() ||
9052           argOpers[valArgIndx]->isImm()) &&
9053          "invalid operand");
9054   if (argOpers[valArgIndx]->isReg())
9055     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9056   else
9057     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9058   MIB.addReg(tt);
9059   (*MIB).addOperand(*argOpers[valArgIndx]);
9060
9061   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9062   MIB.addReg(t1);
9063
9064   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9065   for (int i=0; i <= lastAddrIndx; ++i)
9066     (*MIB).addOperand(*argOpers[i]);
9067   MIB.addReg(t2);
9068   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9069   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9070                     bInstr->memoperands_end());
9071
9072   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9073   MIB.addReg(EAXreg);
9074
9075   // insert branch
9076   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9077
9078   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9079   return nextMBB;
9080 }
9081
9082 // private utility function:  64 bit atomics on 32 bit host.
9083 MachineBasicBlock *
9084 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9085                                                        MachineBasicBlock *MBB,
9086                                                        unsigned regOpcL,
9087                                                        unsigned regOpcH,
9088                                                        unsigned immOpcL,
9089                                                        unsigned immOpcH,
9090                                                        bool invSrc) const {
9091   // For the atomic bitwise operator, we generate
9092   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9093   //     ld t1,t2 = [bitinstr.addr]
9094   //   newMBB:
9095   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9096   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9097   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9098   //     mov ECX, EBX <- t5, t6
9099   //     mov EAX, EDX <- t1, t2
9100   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9101   //     mov t3, t4 <- EAX, EDX
9102   //     bz  newMBB
9103   //     result in out1, out2
9104   //     fallthrough -->nextMBB
9105
9106   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9107   const unsigned LoadOpc = X86::MOV32rm;
9108   const unsigned NotOpc = X86::NOT32r;
9109   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9110   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9111   MachineFunction::iterator MBBIter = MBB;
9112   ++MBBIter;
9113
9114   /// First build the CFG
9115   MachineFunction *F = MBB->getParent();
9116   MachineBasicBlock *thisMBB = MBB;
9117   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9118   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9119   F->insert(MBBIter, newMBB);
9120   F->insert(MBBIter, nextMBB);
9121
9122   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9123   nextMBB->splice(nextMBB->begin(), thisMBB,
9124                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9125                   thisMBB->end());
9126   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9127
9128   // Update thisMBB to fall through to newMBB
9129   thisMBB->addSuccessor(newMBB);
9130
9131   // newMBB jumps to itself and fall through to nextMBB
9132   newMBB->addSuccessor(nextMBB);
9133   newMBB->addSuccessor(newMBB);
9134
9135   DebugLoc dl = bInstr->getDebugLoc();
9136   // Insert instructions into newMBB based on incoming instruction
9137   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9138   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9139          "unexpected number of operands");
9140   MachineOperand& dest1Oper = bInstr->getOperand(0);
9141   MachineOperand& dest2Oper = bInstr->getOperand(1);
9142   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9143   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9144     argOpers[i] = &bInstr->getOperand(i+2);
9145
9146     // We use some of the operands multiple times, so conservatively just
9147     // clear any kill flags that might be present.
9148     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9149       argOpers[i]->setIsKill(false);
9150   }
9151
9152   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9153   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9154
9155   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9156   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9157   for (int i=0; i <= lastAddrIndx; ++i)
9158     (*MIB).addOperand(*argOpers[i]);
9159   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9160   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9161   // add 4 to displacement.
9162   for (int i=0; i <= lastAddrIndx-2; ++i)
9163     (*MIB).addOperand(*argOpers[i]);
9164   MachineOperand newOp3 = *(argOpers[3]);
9165   if (newOp3.isImm())
9166     newOp3.setImm(newOp3.getImm()+4);
9167   else
9168     newOp3.setOffset(newOp3.getOffset()+4);
9169   (*MIB).addOperand(newOp3);
9170   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9171
9172   // t3/4 are defined later, at the bottom of the loop
9173   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9174   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9175   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9176     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9177   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9178     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9179
9180   // The subsequent operations should be using the destination registers of
9181   //the PHI instructions.
9182   if (invSrc) {
9183     t1 = F->getRegInfo().createVirtualRegister(RC);
9184     t2 = F->getRegInfo().createVirtualRegister(RC);
9185     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9186     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9187   } else {
9188     t1 = dest1Oper.getReg();
9189     t2 = dest2Oper.getReg();
9190   }
9191
9192   int valArgIndx = lastAddrIndx + 1;
9193   assert((argOpers[valArgIndx]->isReg() ||
9194           argOpers[valArgIndx]->isImm()) &&
9195          "invalid operand");
9196   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9197   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9198   if (argOpers[valArgIndx]->isReg())
9199     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9200   else
9201     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9202   if (regOpcL != X86::MOV32rr)
9203     MIB.addReg(t1);
9204   (*MIB).addOperand(*argOpers[valArgIndx]);
9205   assert(argOpers[valArgIndx + 1]->isReg() ==
9206          argOpers[valArgIndx]->isReg());
9207   assert(argOpers[valArgIndx + 1]->isImm() ==
9208          argOpers[valArgIndx]->isImm());
9209   if (argOpers[valArgIndx + 1]->isReg())
9210     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9211   else
9212     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9213   if (regOpcH != X86::MOV32rr)
9214     MIB.addReg(t2);
9215   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9216
9217   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9218   MIB.addReg(t1);
9219   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9220   MIB.addReg(t2);
9221
9222   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9223   MIB.addReg(t5);
9224   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9225   MIB.addReg(t6);
9226
9227   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9228   for (int i=0; i <= lastAddrIndx; ++i)
9229     (*MIB).addOperand(*argOpers[i]);
9230
9231   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9232   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9233                     bInstr->memoperands_end());
9234
9235   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9236   MIB.addReg(X86::EAX);
9237   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9238   MIB.addReg(X86::EDX);
9239
9240   // insert branch
9241   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9242
9243   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9244   return nextMBB;
9245 }
9246
9247 // private utility function
9248 MachineBasicBlock *
9249 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9250                                                       MachineBasicBlock *MBB,
9251                                                       unsigned cmovOpc) const {
9252   // For the atomic min/max operator, we generate
9253   //   thisMBB:
9254   //   newMBB:
9255   //     ld t1 = [min/max.addr]
9256   //     mov t2 = [min/max.val]
9257   //     cmp  t1, t2
9258   //     cmov[cond] t2 = t1
9259   //     mov EAX = t1
9260   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9261   //     bz   newMBB
9262   //     fallthrough -->nextMBB
9263   //
9264   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9265   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9266   MachineFunction::iterator MBBIter = MBB;
9267   ++MBBIter;
9268
9269   /// First build the CFG
9270   MachineFunction *F = MBB->getParent();
9271   MachineBasicBlock *thisMBB = MBB;
9272   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9273   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9274   F->insert(MBBIter, newMBB);
9275   F->insert(MBBIter, nextMBB);
9276
9277   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9278   nextMBB->splice(nextMBB->begin(), thisMBB,
9279                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9280                   thisMBB->end());
9281   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9282
9283   // Update thisMBB to fall through to newMBB
9284   thisMBB->addSuccessor(newMBB);
9285
9286   // newMBB jumps to newMBB and fall through to nextMBB
9287   newMBB->addSuccessor(nextMBB);
9288   newMBB->addSuccessor(newMBB);
9289
9290   DebugLoc dl = mInstr->getDebugLoc();
9291   // Insert instructions into newMBB based on incoming instruction
9292   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9293          "unexpected number of operands");
9294   MachineOperand& destOper = mInstr->getOperand(0);
9295   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9296   int numArgs = mInstr->getNumOperands() - 1;
9297   for (int i=0; i < numArgs; ++i)
9298     argOpers[i] = &mInstr->getOperand(i+1);
9299
9300   // x86 address has 4 operands: base, index, scale, and displacement
9301   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9302   int valArgIndx = lastAddrIndx + 1;
9303
9304   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9305   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9306   for (int i=0; i <= lastAddrIndx; ++i)
9307     (*MIB).addOperand(*argOpers[i]);
9308
9309   // We only support register and immediate values
9310   assert((argOpers[valArgIndx]->isReg() ||
9311           argOpers[valArgIndx]->isImm()) &&
9312          "invalid operand");
9313
9314   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9315   if (argOpers[valArgIndx]->isReg())
9316     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9317   else
9318     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9319   (*MIB).addOperand(*argOpers[valArgIndx]);
9320
9321   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9322   MIB.addReg(t1);
9323
9324   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9325   MIB.addReg(t1);
9326   MIB.addReg(t2);
9327
9328   // Generate movc
9329   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9330   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9331   MIB.addReg(t2);
9332   MIB.addReg(t1);
9333
9334   // Cmp and exchange if none has modified the memory location
9335   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9336   for (int i=0; i <= lastAddrIndx; ++i)
9337     (*MIB).addOperand(*argOpers[i]);
9338   MIB.addReg(t3);
9339   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9340   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9341                     mInstr->memoperands_end());
9342
9343   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9344   MIB.addReg(X86::EAX);
9345
9346   // insert branch
9347   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9348
9349   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9350   return nextMBB;
9351 }
9352
9353 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9354 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9355 // in the .td file.
9356 MachineBasicBlock *
9357 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9358                             unsigned numArgs, bool memArg) const {
9359
9360   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9361          "Target must have SSE4.2 or AVX features enabled");
9362
9363   DebugLoc dl = MI->getDebugLoc();
9364   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9365
9366   unsigned Opc;
9367
9368   if (!Subtarget->hasAVX()) {
9369     if (memArg)
9370       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9371     else
9372       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9373   } else {
9374     if (memArg)
9375       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9376     else
9377       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9378   }
9379
9380   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9381
9382   for (unsigned i = 0; i < numArgs; ++i) {
9383     MachineOperand &Op = MI->getOperand(i+1);
9384
9385     if (!(Op.isReg() && Op.isImplicit()))
9386       MIB.addOperand(Op);
9387   }
9388
9389   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9390     .addReg(X86::XMM0);
9391
9392   MI->eraseFromParent();
9393
9394   return BB;
9395 }
9396
9397 MachineBasicBlock *
9398 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9399                                                  MachineInstr *MI,
9400                                                  MachineBasicBlock *MBB) const {
9401   // Emit code to save XMM registers to the stack. The ABI says that the
9402   // number of registers to save is given in %al, so it's theoretically
9403   // possible to do an indirect jump trick to avoid saving all of them,
9404   // however this code takes a simpler approach and just executes all
9405   // of the stores if %al is non-zero. It's less code, and it's probably
9406   // easier on the hardware branch predictor, and stores aren't all that
9407   // expensive anyway.
9408
9409   // Create the new basic blocks. One block contains all the XMM stores,
9410   // and one block is the final destination regardless of whether any
9411   // stores were performed.
9412   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9413   MachineFunction *F = MBB->getParent();
9414   MachineFunction::iterator MBBIter = MBB;
9415   ++MBBIter;
9416   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9417   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9418   F->insert(MBBIter, XMMSaveMBB);
9419   F->insert(MBBIter, EndMBB);
9420
9421   // Transfer the remainder of MBB and its successor edges to EndMBB.
9422   EndMBB->splice(EndMBB->begin(), MBB,
9423                  llvm::next(MachineBasicBlock::iterator(MI)),
9424                  MBB->end());
9425   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9426
9427   // The original block will now fall through to the XMM save block.
9428   MBB->addSuccessor(XMMSaveMBB);
9429   // The XMMSaveMBB will fall through to the end block.
9430   XMMSaveMBB->addSuccessor(EndMBB);
9431
9432   // Now add the instructions.
9433   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9434   DebugLoc DL = MI->getDebugLoc();
9435
9436   unsigned CountReg = MI->getOperand(0).getReg();
9437   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9438   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9439
9440   if (!Subtarget->isTargetWin64()) {
9441     // If %al is 0, branch around the XMM save block.
9442     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9443     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9444     MBB->addSuccessor(EndMBB);
9445   }
9446
9447   // In the XMM save block, save all the XMM argument registers.
9448   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9449     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9450     MachineMemOperand *MMO =
9451       F->getMachineMemOperand(
9452           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9453         MachineMemOperand::MOStore,
9454         /*Size=*/16, /*Align=*/16);
9455     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9456       .addFrameIndex(RegSaveFrameIndex)
9457       .addImm(/*Scale=*/1)
9458       .addReg(/*IndexReg=*/0)
9459       .addImm(/*Disp=*/Offset)
9460       .addReg(/*Segment=*/0)
9461       .addReg(MI->getOperand(i).getReg())
9462       .addMemOperand(MMO);
9463   }
9464
9465   MI->eraseFromParent();   // The pseudo instruction is gone now.
9466
9467   return EndMBB;
9468 }
9469
9470 MachineBasicBlock *
9471 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9472                                      MachineBasicBlock *BB) const {
9473   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9474   DebugLoc DL = MI->getDebugLoc();
9475
9476   // To "insert" a SELECT_CC instruction, we actually have to insert the
9477   // diamond control-flow pattern.  The incoming instruction knows the
9478   // destination vreg to set, the condition code register to branch on, the
9479   // true/false values to select between, and a branch opcode to use.
9480   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9481   MachineFunction::iterator It = BB;
9482   ++It;
9483
9484   //  thisMBB:
9485   //  ...
9486   //   TrueVal = ...
9487   //   cmpTY ccX, r1, r2
9488   //   bCC copy1MBB
9489   //   fallthrough --> copy0MBB
9490   MachineBasicBlock *thisMBB = BB;
9491   MachineFunction *F = BB->getParent();
9492   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9493   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9494   F->insert(It, copy0MBB);
9495   F->insert(It, sinkMBB);
9496
9497   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9498   // live into the sink and copy blocks.
9499   const MachineFunction *MF = BB->getParent();
9500   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9501   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9502
9503   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9504     const MachineOperand &MO = MI->getOperand(I);
9505     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9506     unsigned Reg = MO.getReg();
9507     if (Reg != X86::EFLAGS) continue;
9508     copy0MBB->addLiveIn(Reg);
9509     sinkMBB->addLiveIn(Reg);
9510   }
9511
9512   // Transfer the remainder of BB and its successor edges to sinkMBB.
9513   sinkMBB->splice(sinkMBB->begin(), BB,
9514                   llvm::next(MachineBasicBlock::iterator(MI)),
9515                   BB->end());
9516   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9517
9518   // Add the true and fallthrough blocks as its successors.
9519   BB->addSuccessor(copy0MBB);
9520   BB->addSuccessor(sinkMBB);
9521
9522   // Create the conditional branch instruction.
9523   unsigned Opc =
9524     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9525   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9526
9527   //  copy0MBB:
9528   //   %FalseValue = ...
9529   //   # fallthrough to sinkMBB
9530   copy0MBB->addSuccessor(sinkMBB);
9531
9532   //  sinkMBB:
9533   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9534   //  ...
9535   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9536           TII->get(X86::PHI), MI->getOperand(0).getReg())
9537     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9538     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9539
9540   MI->eraseFromParent();   // The pseudo instruction is gone now.
9541   return sinkMBB;
9542 }
9543
9544 MachineBasicBlock *
9545 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9546                                           MachineBasicBlock *BB) const {
9547   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9548   DebugLoc DL = MI->getDebugLoc();
9549
9550   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9551   // non-trivial part is impdef of ESP.
9552   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9553   // mingw-w64.
9554
9555   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9556     .addExternalSymbol("_alloca")
9557     .addReg(X86::EAX, RegState::Implicit)
9558     .addReg(X86::ESP, RegState::Implicit)
9559     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9560     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9561     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9562
9563   MI->eraseFromParent();   // The pseudo instruction is gone now.
9564   return BB;
9565 }
9566
9567 MachineBasicBlock *
9568 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9569                                       MachineBasicBlock *BB) const {
9570   // This is pretty easy.  We're taking the value that we received from
9571   // our load from the relocation, sticking it in either RDI (x86-64)
9572   // or EAX and doing an indirect call.  The return value will then
9573   // be in the normal return register.
9574   const X86InstrInfo *TII 
9575     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9576   DebugLoc DL = MI->getDebugLoc();
9577   MachineFunction *F = BB->getParent();
9578
9579   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9580   assert(MI->getOperand(3).isGlobal() && "This should be a global");
9581   
9582   if (Subtarget->is64Bit()) {
9583     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9584                                       TII->get(X86::MOV64rm), X86::RDI)
9585     .addReg(X86::RIP)
9586     .addImm(0).addReg(0)
9587     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9588                       MI->getOperand(3).getTargetFlags())
9589     .addReg(0);
9590     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
9591     addDirectMem(MIB, X86::RDI);
9592   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9593     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9594                                       TII->get(X86::MOV32rm), X86::EAX)
9595     .addReg(0)
9596     .addImm(0).addReg(0)
9597     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9598                       MI->getOperand(3).getTargetFlags())
9599     .addReg(0);
9600     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9601     addDirectMem(MIB, X86::EAX);
9602   } else {
9603     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9604                                       TII->get(X86::MOV32rm), X86::EAX)
9605     .addReg(TII->getGlobalBaseReg(F))
9606     .addImm(0).addReg(0)
9607     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9608                       MI->getOperand(3).getTargetFlags())
9609     .addReg(0);
9610     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9611     addDirectMem(MIB, X86::EAX);
9612   }
9613   
9614   MI->eraseFromParent(); // The pseudo instruction is gone now.
9615   return BB;
9616 }
9617
9618 MachineBasicBlock *
9619 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9620                                                MachineBasicBlock *BB) const {
9621   switch (MI->getOpcode()) {
9622   default: assert(false && "Unexpected instr type to insert");
9623   case X86::MINGW_ALLOCA:
9624     return EmitLoweredMingwAlloca(MI, BB);
9625   case X86::TLSCall_32:
9626   case X86::TLSCall_64:
9627     return EmitLoweredTLSCall(MI, BB);
9628   case X86::CMOV_GR8:
9629   case X86::CMOV_FR32:
9630   case X86::CMOV_FR64:
9631   case X86::CMOV_V4F32:
9632   case X86::CMOV_V2F64:
9633   case X86::CMOV_V2I64:
9634   case X86::CMOV_GR16:
9635   case X86::CMOV_GR32:
9636   case X86::CMOV_RFP32:
9637   case X86::CMOV_RFP64:
9638   case X86::CMOV_RFP80:
9639     return EmitLoweredSelect(MI, BB);
9640
9641   case X86::FP32_TO_INT16_IN_MEM:
9642   case X86::FP32_TO_INT32_IN_MEM:
9643   case X86::FP32_TO_INT64_IN_MEM:
9644   case X86::FP64_TO_INT16_IN_MEM:
9645   case X86::FP64_TO_INT32_IN_MEM:
9646   case X86::FP64_TO_INT64_IN_MEM:
9647   case X86::FP80_TO_INT16_IN_MEM:
9648   case X86::FP80_TO_INT32_IN_MEM:
9649   case X86::FP80_TO_INT64_IN_MEM: {
9650     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9651     DebugLoc DL = MI->getDebugLoc();
9652
9653     // Change the floating point control register to use "round towards zero"
9654     // mode when truncating to an integer value.
9655     MachineFunction *F = BB->getParent();
9656     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9657     addFrameReference(BuildMI(*BB, MI, DL,
9658                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
9659
9660     // Load the old value of the high byte of the control word...
9661     unsigned OldCW =
9662       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9663     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9664                       CWFrameIdx);
9665
9666     // Set the high part to be round to zero...
9667     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9668       .addImm(0xC7F);
9669
9670     // Reload the modified control word now...
9671     addFrameReference(BuildMI(*BB, MI, DL,
9672                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9673
9674     // Restore the memory image of control word to original value
9675     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9676       .addReg(OldCW);
9677
9678     // Get the X86 opcode to use.
9679     unsigned Opc;
9680     switch (MI->getOpcode()) {
9681     default: llvm_unreachable("illegal opcode!");
9682     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9683     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9684     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9685     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9686     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9687     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9688     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9689     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9690     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9691     }
9692
9693     X86AddressMode AM;
9694     MachineOperand &Op = MI->getOperand(0);
9695     if (Op.isReg()) {
9696       AM.BaseType = X86AddressMode::RegBase;
9697       AM.Base.Reg = Op.getReg();
9698     } else {
9699       AM.BaseType = X86AddressMode::FrameIndexBase;
9700       AM.Base.FrameIndex = Op.getIndex();
9701     }
9702     Op = MI->getOperand(1);
9703     if (Op.isImm())
9704       AM.Scale = Op.getImm();
9705     Op = MI->getOperand(2);
9706     if (Op.isImm())
9707       AM.IndexReg = Op.getImm();
9708     Op = MI->getOperand(3);
9709     if (Op.isGlobal()) {
9710       AM.GV = Op.getGlobal();
9711     } else {
9712       AM.Disp = Op.getImm();
9713     }
9714     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9715                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9716
9717     // Reload the original control word now.
9718     addFrameReference(BuildMI(*BB, MI, DL,
9719                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9720
9721     MI->eraseFromParent();   // The pseudo instruction is gone now.
9722     return BB;
9723   }
9724     // String/text processing lowering.
9725   case X86::PCMPISTRM128REG:
9726   case X86::VPCMPISTRM128REG:
9727     return EmitPCMP(MI, BB, 3, false /* in-mem */);
9728   case X86::PCMPISTRM128MEM:
9729   case X86::VPCMPISTRM128MEM:
9730     return EmitPCMP(MI, BB, 3, true /* in-mem */);
9731   case X86::PCMPESTRM128REG:
9732   case X86::VPCMPESTRM128REG:
9733     return EmitPCMP(MI, BB, 5, false /* in mem */);
9734   case X86::PCMPESTRM128MEM:
9735   case X86::VPCMPESTRM128MEM:
9736     return EmitPCMP(MI, BB, 5, true /* in mem */);
9737
9738     // Atomic Lowering.
9739   case X86::ATOMAND32:
9740     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9741                                                X86::AND32ri, X86::MOV32rm,
9742                                                X86::LCMPXCHG32,
9743                                                X86::NOT32r, X86::EAX,
9744                                                X86::GR32RegisterClass);
9745   case X86::ATOMOR32:
9746     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9747                                                X86::OR32ri, X86::MOV32rm,
9748                                                X86::LCMPXCHG32,
9749                                                X86::NOT32r, X86::EAX,
9750                                                X86::GR32RegisterClass);
9751   case X86::ATOMXOR32:
9752     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9753                                                X86::XOR32ri, X86::MOV32rm,
9754                                                X86::LCMPXCHG32,
9755                                                X86::NOT32r, X86::EAX,
9756                                                X86::GR32RegisterClass);
9757   case X86::ATOMNAND32:
9758     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9759                                                X86::AND32ri, X86::MOV32rm,
9760                                                X86::LCMPXCHG32,
9761                                                X86::NOT32r, X86::EAX,
9762                                                X86::GR32RegisterClass, true);
9763   case X86::ATOMMIN32:
9764     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9765   case X86::ATOMMAX32:
9766     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9767   case X86::ATOMUMIN32:
9768     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9769   case X86::ATOMUMAX32:
9770     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9771
9772   case X86::ATOMAND16:
9773     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9774                                                X86::AND16ri, X86::MOV16rm,
9775                                                X86::LCMPXCHG16,
9776                                                X86::NOT16r, X86::AX,
9777                                                X86::GR16RegisterClass);
9778   case X86::ATOMOR16:
9779     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9780                                                X86::OR16ri, X86::MOV16rm,
9781                                                X86::LCMPXCHG16,
9782                                                X86::NOT16r, X86::AX,
9783                                                X86::GR16RegisterClass);
9784   case X86::ATOMXOR16:
9785     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9786                                                X86::XOR16ri, X86::MOV16rm,
9787                                                X86::LCMPXCHG16,
9788                                                X86::NOT16r, X86::AX,
9789                                                X86::GR16RegisterClass);
9790   case X86::ATOMNAND16:
9791     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9792                                                X86::AND16ri, X86::MOV16rm,
9793                                                X86::LCMPXCHG16,
9794                                                X86::NOT16r, X86::AX,
9795                                                X86::GR16RegisterClass, true);
9796   case X86::ATOMMIN16:
9797     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9798   case X86::ATOMMAX16:
9799     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9800   case X86::ATOMUMIN16:
9801     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9802   case X86::ATOMUMAX16:
9803     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9804
9805   case X86::ATOMAND8:
9806     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9807                                                X86::AND8ri, X86::MOV8rm,
9808                                                X86::LCMPXCHG8,
9809                                                X86::NOT8r, X86::AL,
9810                                                X86::GR8RegisterClass);
9811   case X86::ATOMOR8:
9812     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9813                                                X86::OR8ri, X86::MOV8rm,
9814                                                X86::LCMPXCHG8,
9815                                                X86::NOT8r, X86::AL,
9816                                                X86::GR8RegisterClass);
9817   case X86::ATOMXOR8:
9818     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9819                                                X86::XOR8ri, X86::MOV8rm,
9820                                                X86::LCMPXCHG8,
9821                                                X86::NOT8r, X86::AL,
9822                                                X86::GR8RegisterClass);
9823   case X86::ATOMNAND8:
9824     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9825                                                X86::AND8ri, X86::MOV8rm,
9826                                                X86::LCMPXCHG8,
9827                                                X86::NOT8r, X86::AL,
9828                                                X86::GR8RegisterClass, true);
9829   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9830   // This group is for 64-bit host.
9831   case X86::ATOMAND64:
9832     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9833                                                X86::AND64ri32, X86::MOV64rm,
9834                                                X86::LCMPXCHG64,
9835                                                X86::NOT64r, X86::RAX,
9836                                                X86::GR64RegisterClass);
9837   case X86::ATOMOR64:
9838     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9839                                                X86::OR64ri32, X86::MOV64rm,
9840                                                X86::LCMPXCHG64,
9841                                                X86::NOT64r, X86::RAX,
9842                                                X86::GR64RegisterClass);
9843   case X86::ATOMXOR64:
9844     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9845                                                X86::XOR64ri32, X86::MOV64rm,
9846                                                X86::LCMPXCHG64,
9847                                                X86::NOT64r, X86::RAX,
9848                                                X86::GR64RegisterClass);
9849   case X86::ATOMNAND64:
9850     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9851                                                X86::AND64ri32, X86::MOV64rm,
9852                                                X86::LCMPXCHG64,
9853                                                X86::NOT64r, X86::RAX,
9854                                                X86::GR64RegisterClass, true);
9855   case X86::ATOMMIN64:
9856     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9857   case X86::ATOMMAX64:
9858     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9859   case X86::ATOMUMIN64:
9860     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9861   case X86::ATOMUMAX64:
9862     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9863
9864   // This group does 64-bit operations on a 32-bit host.
9865   case X86::ATOMAND6432:
9866     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9867                                                X86::AND32rr, X86::AND32rr,
9868                                                X86::AND32ri, X86::AND32ri,
9869                                                false);
9870   case X86::ATOMOR6432:
9871     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9872                                                X86::OR32rr, X86::OR32rr,
9873                                                X86::OR32ri, X86::OR32ri,
9874                                                false);
9875   case X86::ATOMXOR6432:
9876     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9877                                                X86::XOR32rr, X86::XOR32rr,
9878                                                X86::XOR32ri, X86::XOR32ri,
9879                                                false);
9880   case X86::ATOMNAND6432:
9881     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9882                                                X86::AND32rr, X86::AND32rr,
9883                                                X86::AND32ri, X86::AND32ri,
9884                                                true);
9885   case X86::ATOMADD6432:
9886     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9887                                                X86::ADD32rr, X86::ADC32rr,
9888                                                X86::ADD32ri, X86::ADC32ri,
9889                                                false);
9890   case X86::ATOMSUB6432:
9891     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9892                                                X86::SUB32rr, X86::SBB32rr,
9893                                                X86::SUB32ri, X86::SBB32ri,
9894                                                false);
9895   case X86::ATOMSWAP6432:
9896     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9897                                                X86::MOV32rr, X86::MOV32rr,
9898                                                X86::MOV32ri, X86::MOV32ri,
9899                                                false);
9900   case X86::VASTART_SAVE_XMM_REGS:
9901     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9902   }
9903 }
9904
9905 //===----------------------------------------------------------------------===//
9906 //                           X86 Optimization Hooks
9907 //===----------------------------------------------------------------------===//
9908
9909 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9910                                                        const APInt &Mask,
9911                                                        APInt &KnownZero,
9912                                                        APInt &KnownOne,
9913                                                        const SelectionDAG &DAG,
9914                                                        unsigned Depth) const {
9915   unsigned Opc = Op.getOpcode();
9916   assert((Opc >= ISD::BUILTIN_OP_END ||
9917           Opc == ISD::INTRINSIC_WO_CHAIN ||
9918           Opc == ISD::INTRINSIC_W_CHAIN ||
9919           Opc == ISD::INTRINSIC_VOID) &&
9920          "Should use MaskedValueIsZero if you don't know whether Op"
9921          " is a target node!");
9922
9923   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
9924   switch (Opc) {
9925   default: break;
9926   case X86ISD::ADD:
9927   case X86ISD::SUB:
9928   case X86ISD::SMUL:
9929   case X86ISD::UMUL:
9930   case X86ISD::INC:
9931   case X86ISD::DEC:
9932   case X86ISD::OR:
9933   case X86ISD::XOR:
9934   case X86ISD::AND:
9935     // These nodes' second result is a boolean.
9936     if (Op.getResNo() == 0)
9937       break;
9938     // Fallthrough
9939   case X86ISD::SETCC:
9940     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9941                                        Mask.getBitWidth() - 1);
9942     break;
9943   }
9944 }
9945
9946 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
9947                                                          unsigned Depth) const {
9948   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
9949   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
9950     return Op.getValueType().getScalarType().getSizeInBits();
9951   
9952   // Fallback case.
9953   return 1;
9954 }
9955
9956 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9957 /// node is a GlobalAddress + offset.
9958 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9959                                        const GlobalValue* &GA,
9960                                        int64_t &Offset) const {
9961   if (N->getOpcode() == X86ISD::Wrapper) {
9962     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9963       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9964       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9965       return true;
9966     }
9967   }
9968   return TargetLowering::isGAPlusOffset(N, GA, Offset);
9969 }
9970
9971 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9972 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9973 /// if the load addresses are consecutive, non-overlapping, and in the right
9974 /// order.
9975 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9976                                      const TargetLowering &TLI) {
9977   DebugLoc dl = N->getDebugLoc();
9978   EVT VT = N->getValueType(0);
9979
9980   if (VT.getSizeInBits() != 128)
9981     return SDValue();
9982
9983   SmallVector<SDValue, 16> Elts;
9984   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9985     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
9986
9987   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9988 }
9989
9990 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
9991 /// generation and convert it from being a bunch of shuffles and extracts
9992 /// to a simple store and scalar loads to extract the elements.
9993 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
9994                                                 const TargetLowering &TLI) {
9995   SDValue InputVector = N->getOperand(0);
9996
9997   // Only operate on vectors of 4 elements, where the alternative shuffling
9998   // gets to be more expensive.
9999   if (InputVector.getValueType() != MVT::v4i32)
10000     return SDValue();
10001
10002   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10003   // single use which is a sign-extend or zero-extend, and all elements are
10004   // used.
10005   SmallVector<SDNode *, 4> Uses;
10006   unsigned ExtractedElements = 0;
10007   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10008        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10009     if (UI.getUse().getResNo() != InputVector.getResNo())
10010       return SDValue();
10011
10012     SDNode *Extract = *UI;
10013     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10014       return SDValue();
10015
10016     if (Extract->getValueType(0) != MVT::i32)
10017       return SDValue();
10018     if (!Extract->hasOneUse())
10019       return SDValue();
10020     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10021         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10022       return SDValue();
10023     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10024       return SDValue();
10025
10026     // Record which element was extracted.
10027     ExtractedElements |=
10028       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10029
10030     Uses.push_back(Extract);
10031   }
10032
10033   // If not all the elements were used, this may not be worthwhile.
10034   if (ExtractedElements != 15)
10035     return SDValue();
10036
10037   // Ok, we've now decided to do the transformation.
10038   DebugLoc dl = InputVector.getDebugLoc();
10039
10040   // Store the value to a temporary stack slot.
10041   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10042   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10043                             MachinePointerInfo(), false, false, 0);
10044
10045   // Replace each use (extract) with a load of the appropriate element.
10046   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10047        UE = Uses.end(); UI != UE; ++UI) {
10048     SDNode *Extract = *UI;
10049
10050     // Compute the element's address.
10051     SDValue Idx = Extract->getOperand(1);
10052     unsigned EltSize =
10053         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10054     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10055     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10056
10057     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10058                                      StackPtr, OffsetVal);
10059
10060     // Load the scalar.
10061     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10062                                      ScalarAddr, MachinePointerInfo(),
10063                                      false, false, 0);
10064
10065     // Replace the exact with the load.
10066     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10067   }
10068
10069   // The replacement was made in place; don't return anything.
10070   return SDValue();
10071 }
10072
10073 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10074 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10075                                     const X86Subtarget *Subtarget) {
10076   DebugLoc DL = N->getDebugLoc();
10077   SDValue Cond = N->getOperand(0);
10078   // Get the LHS/RHS of the select.
10079   SDValue LHS = N->getOperand(1);
10080   SDValue RHS = N->getOperand(2);
10081
10082   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10083   // instructions match the semantics of the common C idiom x<y?x:y but not
10084   // x<=y?x:y, because of how they handle negative zero (which can be
10085   // ignored in unsafe-math mode).
10086   if (Subtarget->hasSSE2() &&
10087       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10088       Cond.getOpcode() == ISD::SETCC) {
10089     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10090
10091     unsigned Opcode = 0;
10092     // Check for x CC y ? x : y.
10093     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10094         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10095       switch (CC) {
10096       default: break;
10097       case ISD::SETULT:
10098         // Converting this to a min would handle NaNs incorrectly, and swapping
10099         // the operands would cause it to handle comparisons between positive
10100         // and negative zero incorrectly.
10101         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10102           if (!UnsafeFPMath &&
10103               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10104             break;
10105           std::swap(LHS, RHS);
10106         }
10107         Opcode = X86ISD::FMIN;
10108         break;
10109       case ISD::SETOLE:
10110         // Converting this to a min would handle comparisons between positive
10111         // and negative zero incorrectly.
10112         if (!UnsafeFPMath &&
10113             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10114           break;
10115         Opcode = X86ISD::FMIN;
10116         break;
10117       case ISD::SETULE:
10118         // Converting this to a min would handle both negative zeros and NaNs
10119         // incorrectly, but we can swap the operands to fix both.
10120         std::swap(LHS, RHS);
10121       case ISD::SETOLT:
10122       case ISD::SETLT:
10123       case ISD::SETLE:
10124         Opcode = X86ISD::FMIN;
10125         break;
10126
10127       case ISD::SETOGE:
10128         // Converting this to a max would handle comparisons between positive
10129         // and negative zero incorrectly.
10130         if (!UnsafeFPMath &&
10131             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10132           break;
10133         Opcode = X86ISD::FMAX;
10134         break;
10135       case ISD::SETUGT:
10136         // Converting this to a max would handle NaNs incorrectly, and swapping
10137         // the operands would cause it to handle comparisons between positive
10138         // and negative zero incorrectly.
10139         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10140           if (!UnsafeFPMath &&
10141               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10142             break;
10143           std::swap(LHS, RHS);
10144         }
10145         Opcode = X86ISD::FMAX;
10146         break;
10147       case ISD::SETUGE:
10148         // Converting this to a max would handle both negative zeros and NaNs
10149         // incorrectly, but we can swap the operands to fix both.
10150         std::swap(LHS, RHS);
10151       case ISD::SETOGT:
10152       case ISD::SETGT:
10153       case ISD::SETGE:
10154         Opcode = X86ISD::FMAX;
10155         break;
10156       }
10157     // Check for x CC y ? y : x -- a min/max with reversed arms.
10158     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10159                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10160       switch (CC) {
10161       default: break;
10162       case ISD::SETOGE:
10163         // Converting this to a min would handle comparisons between positive
10164         // and negative zero incorrectly, and swapping the operands would
10165         // cause it to handle NaNs incorrectly.
10166         if (!UnsafeFPMath &&
10167             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10168           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10169             break;
10170           std::swap(LHS, RHS);
10171         }
10172         Opcode = X86ISD::FMIN;
10173         break;
10174       case ISD::SETUGT:
10175         // Converting this to a min would handle NaNs incorrectly.
10176         if (!UnsafeFPMath &&
10177             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10178           break;
10179         Opcode = X86ISD::FMIN;
10180         break;
10181       case ISD::SETUGE:
10182         // Converting this to a min would handle both negative zeros and NaNs
10183         // incorrectly, but we can swap the operands to fix both.
10184         std::swap(LHS, RHS);
10185       case ISD::SETOGT:
10186       case ISD::SETGT:
10187       case ISD::SETGE:
10188         Opcode = X86ISD::FMIN;
10189         break;
10190
10191       case ISD::SETULT:
10192         // Converting this to a max would handle NaNs incorrectly.
10193         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10194           break;
10195         Opcode = X86ISD::FMAX;
10196         break;
10197       case ISD::SETOLE:
10198         // Converting this to a max would handle comparisons between positive
10199         // and negative zero incorrectly, and swapping the operands would
10200         // cause it to handle NaNs incorrectly.
10201         if (!UnsafeFPMath &&
10202             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10203           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10204             break;
10205           std::swap(LHS, RHS);
10206         }
10207         Opcode = X86ISD::FMAX;
10208         break;
10209       case ISD::SETULE:
10210         // Converting this to a max would handle both negative zeros and NaNs
10211         // incorrectly, but we can swap the operands to fix both.
10212         std::swap(LHS, RHS);
10213       case ISD::SETOLT:
10214       case ISD::SETLT:
10215       case ISD::SETLE:
10216         Opcode = X86ISD::FMAX;
10217         break;
10218       }
10219     }
10220
10221     if (Opcode)
10222       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10223   }
10224
10225   // If this is a select between two integer constants, try to do some
10226   // optimizations.
10227   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10228     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10229       // Don't do this for crazy integer types.
10230       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10231         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10232         // so that TrueC (the true value) is larger than FalseC.
10233         bool NeedsCondInvert = false;
10234
10235         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10236             // Efficiently invertible.
10237             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10238              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10239               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10240           NeedsCondInvert = true;
10241           std::swap(TrueC, FalseC);
10242         }
10243
10244         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10245         if (FalseC->getAPIntValue() == 0 &&
10246             TrueC->getAPIntValue().isPowerOf2()) {
10247           if (NeedsCondInvert) // Invert the condition if needed.
10248             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10249                                DAG.getConstant(1, Cond.getValueType()));
10250
10251           // Zero extend the condition if needed.
10252           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10253
10254           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10255           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10256                              DAG.getConstant(ShAmt, MVT::i8));
10257         }
10258
10259         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10260         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10261           if (NeedsCondInvert) // Invert the condition if needed.
10262             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10263                                DAG.getConstant(1, Cond.getValueType()));
10264
10265           // Zero extend the condition if needed.
10266           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10267                              FalseC->getValueType(0), Cond);
10268           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10269                              SDValue(FalseC, 0));
10270         }
10271
10272         // Optimize cases that will turn into an LEA instruction.  This requires
10273         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10274         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10275           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10276           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10277
10278           bool isFastMultiplier = false;
10279           if (Diff < 10) {
10280             switch ((unsigned char)Diff) {
10281               default: break;
10282               case 1:  // result = add base, cond
10283               case 2:  // result = lea base(    , cond*2)
10284               case 3:  // result = lea base(cond, cond*2)
10285               case 4:  // result = lea base(    , cond*4)
10286               case 5:  // result = lea base(cond, cond*4)
10287               case 8:  // result = lea base(    , cond*8)
10288               case 9:  // result = lea base(cond, cond*8)
10289                 isFastMultiplier = true;
10290                 break;
10291             }
10292           }
10293
10294           if (isFastMultiplier) {
10295             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10296             if (NeedsCondInvert) // Invert the condition if needed.
10297               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10298                                  DAG.getConstant(1, Cond.getValueType()));
10299
10300             // Zero extend the condition if needed.
10301             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10302                                Cond);
10303             // Scale the condition by the difference.
10304             if (Diff != 1)
10305               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10306                                  DAG.getConstant(Diff, Cond.getValueType()));
10307
10308             // Add the base if non-zero.
10309             if (FalseC->getAPIntValue() != 0)
10310               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10311                                  SDValue(FalseC, 0));
10312             return Cond;
10313           }
10314         }
10315       }
10316   }
10317
10318   return SDValue();
10319 }
10320
10321 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10322 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10323                                   TargetLowering::DAGCombinerInfo &DCI) {
10324   DebugLoc DL = N->getDebugLoc();
10325
10326   // If the flag operand isn't dead, don't touch this CMOV.
10327   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10328     return SDValue();
10329
10330   // If this is a select between two integer constants, try to do some
10331   // optimizations.  Note that the operands are ordered the opposite of SELECT
10332   // operands.
10333   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10334     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10335       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10336       // larger than FalseC (the false value).
10337       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10338
10339       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10340         CC = X86::GetOppositeBranchCondition(CC);
10341         std::swap(TrueC, FalseC);
10342       }
10343
10344       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10345       // This is efficient for any integer data type (including i8/i16) and
10346       // shift amount.
10347       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10348         SDValue Cond = N->getOperand(3);
10349         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10350                            DAG.getConstant(CC, MVT::i8), Cond);
10351
10352         // Zero extend the condition if needed.
10353         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10354
10355         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10356         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10357                            DAG.getConstant(ShAmt, MVT::i8));
10358         if (N->getNumValues() == 2)  // Dead flag value?
10359           return DCI.CombineTo(N, Cond, SDValue());
10360         return Cond;
10361       }
10362
10363       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10364       // for any integer data type, including i8/i16.
10365       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10366         SDValue Cond = N->getOperand(3);
10367         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10368                            DAG.getConstant(CC, MVT::i8), Cond);
10369
10370         // Zero extend the condition if needed.
10371         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10372                            FalseC->getValueType(0), Cond);
10373         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10374                            SDValue(FalseC, 0));
10375
10376         if (N->getNumValues() == 2)  // Dead flag value?
10377           return DCI.CombineTo(N, Cond, SDValue());
10378         return Cond;
10379       }
10380
10381       // Optimize cases that will turn into an LEA instruction.  This requires
10382       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10383       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10384         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10385         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10386
10387         bool isFastMultiplier = false;
10388         if (Diff < 10) {
10389           switch ((unsigned char)Diff) {
10390           default: break;
10391           case 1:  // result = add base, cond
10392           case 2:  // result = lea base(    , cond*2)
10393           case 3:  // result = lea base(cond, cond*2)
10394           case 4:  // result = lea base(    , cond*4)
10395           case 5:  // result = lea base(cond, cond*4)
10396           case 8:  // result = lea base(    , cond*8)
10397           case 9:  // result = lea base(cond, cond*8)
10398             isFastMultiplier = true;
10399             break;
10400           }
10401         }
10402
10403         if (isFastMultiplier) {
10404           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10405           SDValue Cond = N->getOperand(3);
10406           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10407                              DAG.getConstant(CC, MVT::i8), Cond);
10408           // Zero extend the condition if needed.
10409           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10410                              Cond);
10411           // Scale the condition by the difference.
10412           if (Diff != 1)
10413             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10414                                DAG.getConstant(Diff, Cond.getValueType()));
10415
10416           // Add the base if non-zero.
10417           if (FalseC->getAPIntValue() != 0)
10418             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10419                                SDValue(FalseC, 0));
10420           if (N->getNumValues() == 2)  // Dead flag value?
10421             return DCI.CombineTo(N, Cond, SDValue());
10422           return Cond;
10423         }
10424       }
10425     }
10426   }
10427   return SDValue();
10428 }
10429
10430
10431 /// PerformMulCombine - Optimize a single multiply with constant into two
10432 /// in order to implement it with two cheaper instructions, e.g.
10433 /// LEA + SHL, LEA + LEA.
10434 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10435                                  TargetLowering::DAGCombinerInfo &DCI) {
10436   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10437     return SDValue();
10438
10439   EVT VT = N->getValueType(0);
10440   if (VT != MVT::i64)
10441     return SDValue();
10442
10443   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10444   if (!C)
10445     return SDValue();
10446   uint64_t MulAmt = C->getZExtValue();
10447   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10448     return SDValue();
10449
10450   uint64_t MulAmt1 = 0;
10451   uint64_t MulAmt2 = 0;
10452   if ((MulAmt % 9) == 0) {
10453     MulAmt1 = 9;
10454     MulAmt2 = MulAmt / 9;
10455   } else if ((MulAmt % 5) == 0) {
10456     MulAmt1 = 5;
10457     MulAmt2 = MulAmt / 5;
10458   } else if ((MulAmt % 3) == 0) {
10459     MulAmt1 = 3;
10460     MulAmt2 = MulAmt / 3;
10461   }
10462   if (MulAmt2 &&
10463       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10464     DebugLoc DL = N->getDebugLoc();
10465
10466     if (isPowerOf2_64(MulAmt2) &&
10467         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10468       // If second multiplifer is pow2, issue it first. We want the multiply by
10469       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10470       // is an add.
10471       std::swap(MulAmt1, MulAmt2);
10472
10473     SDValue NewMul;
10474     if (isPowerOf2_64(MulAmt1))
10475       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10476                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10477     else
10478       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10479                            DAG.getConstant(MulAmt1, VT));
10480
10481     if (isPowerOf2_64(MulAmt2))
10482       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10483                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10484     else
10485       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10486                            DAG.getConstant(MulAmt2, VT));
10487
10488     // Do not add new nodes to DAG combiner worklist.
10489     DCI.CombineTo(N, NewMul, false);
10490   }
10491   return SDValue();
10492 }
10493
10494 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10495   SDValue N0 = N->getOperand(0);
10496   SDValue N1 = N->getOperand(1);
10497   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10498   EVT VT = N0.getValueType();
10499
10500   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10501   // since the result of setcc_c is all zero's or all ones.
10502   if (N1C && N0.getOpcode() == ISD::AND &&
10503       N0.getOperand(1).getOpcode() == ISD::Constant) {
10504     SDValue N00 = N0.getOperand(0);
10505     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10506         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10507           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10508          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10509       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10510       APInt ShAmt = N1C->getAPIntValue();
10511       Mask = Mask.shl(ShAmt);
10512       if (Mask != 0)
10513         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10514                            N00, DAG.getConstant(Mask, VT));
10515     }
10516   }
10517
10518   return SDValue();
10519 }
10520
10521 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10522 ///                       when possible.
10523 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10524                                    const X86Subtarget *Subtarget) {
10525   EVT VT = N->getValueType(0);
10526   if (!VT.isVector() && VT.isInteger() &&
10527       N->getOpcode() == ISD::SHL)
10528     return PerformSHLCombine(N, DAG);
10529
10530   // On X86 with SSE2 support, we can transform this to a vector shift if
10531   // all elements are shifted by the same amount.  We can't do this in legalize
10532   // because the a constant vector is typically transformed to a constant pool
10533   // so we have no knowledge of the shift amount.
10534   if (!Subtarget->hasSSE2())
10535     return SDValue();
10536
10537   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10538     return SDValue();
10539
10540   SDValue ShAmtOp = N->getOperand(1);
10541   EVT EltVT = VT.getVectorElementType();
10542   DebugLoc DL = N->getDebugLoc();
10543   SDValue BaseShAmt = SDValue();
10544   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10545     unsigned NumElts = VT.getVectorNumElements();
10546     unsigned i = 0;
10547     for (; i != NumElts; ++i) {
10548       SDValue Arg = ShAmtOp.getOperand(i);
10549       if (Arg.getOpcode() == ISD::UNDEF) continue;
10550       BaseShAmt = Arg;
10551       break;
10552     }
10553     for (; i != NumElts; ++i) {
10554       SDValue Arg = ShAmtOp.getOperand(i);
10555       if (Arg.getOpcode() == ISD::UNDEF) continue;
10556       if (Arg != BaseShAmt) {
10557         return SDValue();
10558       }
10559     }
10560   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10561              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10562     SDValue InVec = ShAmtOp.getOperand(0);
10563     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10564       unsigned NumElts = InVec.getValueType().getVectorNumElements();
10565       unsigned i = 0;
10566       for (; i != NumElts; ++i) {
10567         SDValue Arg = InVec.getOperand(i);
10568         if (Arg.getOpcode() == ISD::UNDEF) continue;
10569         BaseShAmt = Arg;
10570         break;
10571       }
10572     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10573        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10574          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10575          if (C->getZExtValue() == SplatIdx)
10576            BaseShAmt = InVec.getOperand(1);
10577        }
10578     }
10579     if (BaseShAmt.getNode() == 0)
10580       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10581                               DAG.getIntPtrConstant(0));
10582   } else
10583     return SDValue();
10584
10585   // The shift amount is an i32.
10586   if (EltVT.bitsGT(MVT::i32))
10587     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10588   else if (EltVT.bitsLT(MVT::i32))
10589     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10590
10591   // The shift amount is identical so we can do a vector shift.
10592   SDValue  ValOp = N->getOperand(0);
10593   switch (N->getOpcode()) {
10594   default:
10595     llvm_unreachable("Unknown shift opcode!");
10596     break;
10597   case ISD::SHL:
10598     if (VT == MVT::v2i64)
10599       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10600                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10601                          ValOp, BaseShAmt);
10602     if (VT == MVT::v4i32)
10603       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10604                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10605                          ValOp, BaseShAmt);
10606     if (VT == MVT::v8i16)
10607       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10608                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10609                          ValOp, BaseShAmt);
10610     break;
10611   case ISD::SRA:
10612     if (VT == MVT::v4i32)
10613       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10614                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10615                          ValOp, BaseShAmt);
10616     if (VT == MVT::v8i16)
10617       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10618                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10619                          ValOp, BaseShAmt);
10620     break;
10621   case ISD::SRL:
10622     if (VT == MVT::v2i64)
10623       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10624                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10625                          ValOp, BaseShAmt);
10626     if (VT == MVT::v4i32)
10627       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10628                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10629                          ValOp, BaseShAmt);
10630     if (VT ==  MVT::v8i16)
10631       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10632                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10633                          ValOp, BaseShAmt);
10634     break;
10635   }
10636   return SDValue();
10637 }
10638
10639 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10640                                 TargetLowering::DAGCombinerInfo &DCI,
10641                                 const X86Subtarget *Subtarget) {
10642   if (DCI.isBeforeLegalizeOps())
10643     return SDValue();
10644
10645   EVT VT = N->getValueType(0);
10646   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10647     return SDValue();
10648
10649   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10650   SDValue N0 = N->getOperand(0);
10651   SDValue N1 = N->getOperand(1);
10652   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10653     std::swap(N0, N1);
10654   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10655     return SDValue();
10656   if (!N0.hasOneUse() || !N1.hasOneUse())
10657     return SDValue();
10658
10659   SDValue ShAmt0 = N0.getOperand(1);
10660   if (ShAmt0.getValueType() != MVT::i8)
10661     return SDValue();
10662   SDValue ShAmt1 = N1.getOperand(1);
10663   if (ShAmt1.getValueType() != MVT::i8)
10664     return SDValue();
10665   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10666     ShAmt0 = ShAmt0.getOperand(0);
10667   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10668     ShAmt1 = ShAmt1.getOperand(0);
10669
10670   DebugLoc DL = N->getDebugLoc();
10671   unsigned Opc = X86ISD::SHLD;
10672   SDValue Op0 = N0.getOperand(0);
10673   SDValue Op1 = N1.getOperand(0);
10674   if (ShAmt0.getOpcode() == ISD::SUB) {
10675     Opc = X86ISD::SHRD;
10676     std::swap(Op0, Op1);
10677     std::swap(ShAmt0, ShAmt1);
10678   }
10679
10680   unsigned Bits = VT.getSizeInBits();
10681   if (ShAmt1.getOpcode() == ISD::SUB) {
10682     SDValue Sum = ShAmt1.getOperand(0);
10683     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10684       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10685       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10686         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10687       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10688         return DAG.getNode(Opc, DL, VT,
10689                            Op0, Op1,
10690                            DAG.getNode(ISD::TRUNCATE, DL,
10691                                        MVT::i8, ShAmt0));
10692     }
10693   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10694     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10695     if (ShAmt0C &&
10696         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10697       return DAG.getNode(Opc, DL, VT,
10698                          N0.getOperand(0), N1.getOperand(0),
10699                          DAG.getNode(ISD::TRUNCATE, DL,
10700                                        MVT::i8, ShAmt0));
10701   }
10702
10703   return SDValue();
10704 }
10705
10706 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10707 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10708                                    const X86Subtarget *Subtarget) {
10709   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
10710   // the FP state in cases where an emms may be missing.
10711   // A preferable solution to the general problem is to figure out the right
10712   // places to insert EMMS.  This qualifies as a quick hack.
10713
10714   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10715   StoreSDNode *St = cast<StoreSDNode>(N);
10716   EVT VT = St->getValue().getValueType();
10717   if (VT.getSizeInBits() != 64)
10718     return SDValue();
10719
10720   const Function *F = DAG.getMachineFunction().getFunction();
10721   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10722   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10723     && Subtarget->hasSSE2();
10724   if ((VT.isVector() ||
10725        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10726       isa<LoadSDNode>(St->getValue()) &&
10727       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10728       St->getChain().hasOneUse() && !St->isVolatile()) {
10729     SDNode* LdVal = St->getValue().getNode();
10730     LoadSDNode *Ld = 0;
10731     int TokenFactorIndex = -1;
10732     SmallVector<SDValue, 8> Ops;
10733     SDNode* ChainVal = St->getChain().getNode();
10734     // Must be a store of a load.  We currently handle two cases:  the load
10735     // is a direct child, and it's under an intervening TokenFactor.  It is
10736     // possible to dig deeper under nested TokenFactors.
10737     if (ChainVal == LdVal)
10738       Ld = cast<LoadSDNode>(St->getChain());
10739     else if (St->getValue().hasOneUse() &&
10740              ChainVal->getOpcode() == ISD::TokenFactor) {
10741       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10742         if (ChainVal->getOperand(i).getNode() == LdVal) {
10743           TokenFactorIndex = i;
10744           Ld = cast<LoadSDNode>(St->getValue());
10745         } else
10746           Ops.push_back(ChainVal->getOperand(i));
10747       }
10748     }
10749
10750     if (!Ld || !ISD::isNormalLoad(Ld))
10751       return SDValue();
10752
10753     // If this is not the MMX case, i.e. we are just turning i64 load/store
10754     // into f64 load/store, avoid the transformation if there are multiple
10755     // uses of the loaded value.
10756     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10757       return SDValue();
10758
10759     DebugLoc LdDL = Ld->getDebugLoc();
10760     DebugLoc StDL = N->getDebugLoc();
10761     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10762     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10763     // pair instead.
10764     if (Subtarget->is64Bit() || F64IsLegal) {
10765       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10766       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
10767                                   Ld->getPointerInfo(), Ld->isVolatile(),
10768                                   Ld->isNonTemporal(), Ld->getAlignment());
10769       SDValue NewChain = NewLd.getValue(1);
10770       if (TokenFactorIndex != -1) {
10771         Ops.push_back(NewChain);
10772         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10773                                Ops.size());
10774       }
10775       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10776                           St->getPointerInfo(),
10777                           St->isVolatile(), St->isNonTemporal(),
10778                           St->getAlignment());
10779     }
10780
10781     // Otherwise, lower to two pairs of 32-bit loads / stores.
10782     SDValue LoAddr = Ld->getBasePtr();
10783     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10784                                  DAG.getConstant(4, MVT::i32));
10785
10786     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10787                                Ld->getPointerInfo(),
10788                                Ld->isVolatile(), Ld->isNonTemporal(),
10789                                Ld->getAlignment());
10790     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10791                                Ld->getPointerInfo().getWithOffset(4),
10792                                Ld->isVolatile(), Ld->isNonTemporal(),
10793                                MinAlign(Ld->getAlignment(), 4));
10794
10795     SDValue NewChain = LoLd.getValue(1);
10796     if (TokenFactorIndex != -1) {
10797       Ops.push_back(LoLd);
10798       Ops.push_back(HiLd);
10799       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10800                              Ops.size());
10801     }
10802
10803     LoAddr = St->getBasePtr();
10804     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10805                          DAG.getConstant(4, MVT::i32));
10806
10807     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10808                                 St->getPointerInfo(),
10809                                 St->isVolatile(), St->isNonTemporal(),
10810                                 St->getAlignment());
10811     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10812                                 St->getPointerInfo().getWithOffset(4),
10813                                 St->isVolatile(),
10814                                 St->isNonTemporal(),
10815                                 MinAlign(St->getAlignment(), 4));
10816     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10817   }
10818   return SDValue();
10819 }
10820
10821 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10822 /// X86ISD::FXOR nodes.
10823 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10824   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10825   // F[X]OR(0.0, x) -> x
10826   // F[X]OR(x, 0.0) -> x
10827   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10828     if (C->getValueAPF().isPosZero())
10829       return N->getOperand(1);
10830   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10831     if (C->getValueAPF().isPosZero())
10832       return N->getOperand(0);
10833   return SDValue();
10834 }
10835
10836 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10837 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10838   // FAND(0.0, x) -> 0.0
10839   // FAND(x, 0.0) -> 0.0
10840   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10841     if (C->getValueAPF().isPosZero())
10842       return N->getOperand(0);
10843   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10844     if (C->getValueAPF().isPosZero())
10845       return N->getOperand(1);
10846   return SDValue();
10847 }
10848
10849 static SDValue PerformBTCombine(SDNode *N,
10850                                 SelectionDAG &DAG,
10851                                 TargetLowering::DAGCombinerInfo &DCI) {
10852   // BT ignores high bits in the bit index operand.
10853   SDValue Op1 = N->getOperand(1);
10854   if (Op1.hasOneUse()) {
10855     unsigned BitWidth = Op1.getValueSizeInBits();
10856     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10857     APInt KnownZero, KnownOne;
10858     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10859                                           !DCI.isBeforeLegalizeOps());
10860     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10861     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10862         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10863       DCI.CommitTargetLoweringOpt(TLO);
10864   }
10865   return SDValue();
10866 }
10867
10868 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10869   SDValue Op = N->getOperand(0);
10870   if (Op.getOpcode() == ISD::BIT_CONVERT)
10871     Op = Op.getOperand(0);
10872   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10873   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10874       VT.getVectorElementType().getSizeInBits() ==
10875       OpVT.getVectorElementType().getSizeInBits()) {
10876     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10877   }
10878   return SDValue();
10879 }
10880
10881 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10882   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
10883   //           (and (i32 x86isd::setcc_carry), 1)
10884   // This eliminates the zext. This transformation is necessary because
10885   // ISD::SETCC is always legalized to i8.
10886   DebugLoc dl = N->getDebugLoc();
10887   SDValue N0 = N->getOperand(0);
10888   EVT VT = N->getValueType(0);
10889   if (N0.getOpcode() == ISD::AND &&
10890       N0.hasOneUse() &&
10891       N0.getOperand(0).hasOneUse()) {
10892     SDValue N00 = N0.getOperand(0);
10893     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10894       return SDValue();
10895     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10896     if (!C || C->getZExtValue() != 1)
10897       return SDValue();
10898     return DAG.getNode(ISD::AND, dl, VT,
10899                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10900                                    N00.getOperand(0), N00.getOperand(1)),
10901                        DAG.getConstant(1, VT));
10902   }
10903
10904   return SDValue();
10905 }
10906
10907 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10908                                              DAGCombinerInfo &DCI) const {
10909   SelectionDAG &DAG = DCI.DAG;
10910   switch (N->getOpcode()) {
10911   default: break;
10912   case ISD::EXTRACT_VECTOR_ELT:
10913                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10914   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
10915   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
10916   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
10917   case ISD::SHL:
10918   case ISD::SRA:
10919   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
10920   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
10921   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
10922   case X86ISD::FXOR:
10923   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
10924   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
10925   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
10926   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
10927   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
10928   case X86ISD::SHUFPS:      // Handle all target specific shuffles
10929   case X86ISD::SHUFPD:
10930   case X86ISD::PALIGN:
10931   case X86ISD::PUNPCKHBW:
10932   case X86ISD::PUNPCKHWD:
10933   case X86ISD::PUNPCKHDQ:
10934   case X86ISD::PUNPCKHQDQ:
10935   case X86ISD::UNPCKHPS:
10936   case X86ISD::UNPCKHPD:
10937   case X86ISD::PUNPCKLBW:
10938   case X86ISD::PUNPCKLWD:
10939   case X86ISD::PUNPCKLDQ:
10940   case X86ISD::PUNPCKLQDQ:
10941   case X86ISD::UNPCKLPS:
10942   case X86ISD::UNPCKLPD:
10943   case X86ISD::MOVHLPS:
10944   case X86ISD::MOVLHPS:
10945   case X86ISD::PSHUFD:
10946   case X86ISD::PSHUFHW:
10947   case X86ISD::PSHUFLW:
10948   case X86ISD::MOVSS:
10949   case X86ISD::MOVSD:
10950   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10951   }
10952
10953   return SDValue();
10954 }
10955
10956 /// isTypeDesirableForOp - Return true if the target has native support for
10957 /// the specified value type and it is 'desirable' to use the type for the
10958 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10959 /// instruction encodings are longer and some i16 instructions are slow.
10960 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10961   if (!isTypeLegal(VT))
10962     return false;
10963   if (VT != MVT::i16)
10964     return true;
10965
10966   switch (Opc) {
10967   default:
10968     return true;
10969   case ISD::LOAD:
10970   case ISD::SIGN_EXTEND:
10971   case ISD::ZERO_EXTEND:
10972   case ISD::ANY_EXTEND:
10973   case ISD::SHL:
10974   case ISD::SRL:
10975   case ISD::SUB:
10976   case ISD::ADD:
10977   case ISD::MUL:
10978   case ISD::AND:
10979   case ISD::OR:
10980   case ISD::XOR:
10981     return false;
10982   }
10983 }
10984
10985 /// IsDesirableToPromoteOp - This method query the target whether it is
10986 /// beneficial for dag combiner to promote the specified node. If true, it
10987 /// should return the desired promotion type by reference.
10988 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10989   EVT VT = Op.getValueType();
10990   if (VT != MVT::i16)
10991     return false;
10992
10993   bool Promote = false;
10994   bool Commute = false;
10995   switch (Op.getOpcode()) {
10996   default: break;
10997   case ISD::LOAD: {
10998     LoadSDNode *LD = cast<LoadSDNode>(Op);
10999     // If the non-extending load has a single use and it's not live out, then it
11000     // might be folded.
11001     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11002                                                      Op.hasOneUse()*/) {
11003       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11004              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11005         // The only case where we'd want to promote LOAD (rather then it being
11006         // promoted as an operand is when it's only use is liveout.
11007         if (UI->getOpcode() != ISD::CopyToReg)
11008           return false;
11009       }
11010     }
11011     Promote = true;
11012     break;
11013   }
11014   case ISD::SIGN_EXTEND:
11015   case ISD::ZERO_EXTEND:
11016   case ISD::ANY_EXTEND:
11017     Promote = true;
11018     break;
11019   case ISD::SHL:
11020   case ISD::SRL: {
11021     SDValue N0 = Op.getOperand(0);
11022     // Look out for (store (shl (load), x)).
11023     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11024       return false;
11025     Promote = true;
11026     break;
11027   }
11028   case ISD::ADD:
11029   case ISD::MUL:
11030   case ISD::AND:
11031   case ISD::OR:
11032   case ISD::XOR:
11033     Commute = true;
11034     // fallthrough
11035   case ISD::SUB: {
11036     SDValue N0 = Op.getOperand(0);
11037     SDValue N1 = Op.getOperand(1);
11038     if (!Commute && MayFoldLoad(N1))
11039       return false;
11040     // Avoid disabling potential load folding opportunities.
11041     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11042       return false;
11043     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11044       return false;
11045     Promote = true;
11046   }
11047   }
11048
11049   PVT = MVT::i32;
11050   return Promote;
11051 }
11052
11053 //===----------------------------------------------------------------------===//
11054 //                           X86 Inline Assembly Support
11055 //===----------------------------------------------------------------------===//
11056
11057 static bool LowerToBSwap(CallInst *CI) {
11058   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11059   // we will turn this bswap into something that will be lowered to logical ops
11060   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11061   // so don't worry about this.
11062
11063   // Verify this is a simple bswap.
11064   if (CI->getNumArgOperands() != 1 ||
11065       CI->getType() != CI->getArgOperand(0)->getType() ||
11066       !CI->getType()->isIntegerTy())
11067     return false;
11068
11069   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11070   if (!Ty || Ty->getBitWidth() % 16 != 0)
11071     return false;
11072
11073   // Okay, we can do this xform, do so now.
11074   const Type *Tys[] = { Ty };
11075   Module *M = CI->getParent()->getParent()->getParent();
11076   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11077
11078   Value *Op = CI->getArgOperand(0);
11079   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11080
11081   CI->replaceAllUsesWith(Op);
11082   CI->eraseFromParent();
11083   return true;
11084 }
11085
11086 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11087   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11088   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11089
11090   std::string AsmStr = IA->getAsmString();
11091
11092   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11093   SmallVector<StringRef, 4> AsmPieces;
11094   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
11095
11096   switch (AsmPieces.size()) {
11097   default: return false;
11098   case 1:
11099     AsmStr = AsmPieces[0];
11100     AsmPieces.clear();
11101     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11102
11103     // bswap $0
11104     if (AsmPieces.size() == 2 &&
11105         (AsmPieces[0] == "bswap" ||
11106          AsmPieces[0] == "bswapq" ||
11107          AsmPieces[0] == "bswapl") &&
11108         (AsmPieces[1] == "$0" ||
11109          AsmPieces[1] == "${0:q}")) {
11110       // No need to check constraints, nothing other than the equivalent of
11111       // "=r,0" would be valid here.
11112       return LowerToBSwap(CI);
11113     }
11114     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11115     if (CI->getType()->isIntegerTy(16) &&
11116         AsmPieces.size() == 3 &&
11117         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11118         AsmPieces[1] == "$$8," &&
11119         AsmPieces[2] == "${0:w}" &&
11120         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11121       AsmPieces.clear();
11122       const std::string &Constraints = IA->getConstraintString();
11123       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11124       std::sort(AsmPieces.begin(), AsmPieces.end());
11125       if (AsmPieces.size() == 4 &&
11126           AsmPieces[0] == "~{cc}" &&
11127           AsmPieces[1] == "~{dirflag}" &&
11128           AsmPieces[2] == "~{flags}" &&
11129           AsmPieces[3] == "~{fpsr}") {
11130         return LowerToBSwap(CI);
11131       }
11132     }
11133     break;
11134   case 3:
11135     if (CI->getType()->isIntegerTy(64) &&
11136         Constraints.size() >= 2 &&
11137         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11138         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11139       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11140       SmallVector<StringRef, 4> Words;
11141       SplitString(AsmPieces[0], Words, " \t");
11142       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11143         Words.clear();
11144         SplitString(AsmPieces[1], Words, " \t");
11145         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11146           Words.clear();
11147           SplitString(AsmPieces[2], Words, " \t,");
11148           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11149               Words[2] == "%edx") {
11150             return LowerToBSwap(CI);
11151           }
11152         }
11153       }
11154     }
11155     break;
11156   }
11157   return false;
11158 }
11159
11160
11161
11162 /// getConstraintType - Given a constraint letter, return the type of
11163 /// constraint it is for this target.
11164 X86TargetLowering::ConstraintType
11165 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11166   if (Constraint.size() == 1) {
11167     switch (Constraint[0]) {
11168     case 'A':
11169       return C_Register;
11170     case 'f':
11171     case 'r':
11172     case 'R':
11173     case 'l':
11174     case 'q':
11175     case 'Q':
11176     case 'x':
11177     case 'y':
11178     case 'Y':
11179       return C_RegisterClass;
11180     case 'e':
11181     case 'Z':
11182       return C_Other;
11183     default:
11184       break;
11185     }
11186   }
11187   return TargetLowering::getConstraintType(Constraint);
11188 }
11189
11190 /// Examine constraint type and operand type and determine a weight value,
11191 /// where: -1 = invalid match, and 0 = so-so match to 3 = good match.
11192 /// This object must already have been set up with the operand type
11193 /// and the current alternative constraint selected.
11194 int X86TargetLowering::getSingleConstraintMatchWeight(
11195     AsmOperandInfo &info, const char *constraint) const {
11196   int weight = -1;
11197   Value *CallOperandVal = info.CallOperandVal;
11198     // If we don't have a value, we can't do a match,
11199     // but allow it at the lowest weight.
11200   if (CallOperandVal == NULL)
11201     return 0;
11202   // Look at the constraint type.
11203   switch (*constraint) {
11204   default:
11205     return TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11206     break;
11207   case 'I':
11208     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11209       if (C->getZExtValue() <= 31)
11210         weight = 3;
11211     }
11212     break;
11213   // etc.
11214   }
11215   return weight;
11216 }
11217
11218 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11219 /// with another that has more specific requirements based on the type of the
11220 /// corresponding operand.
11221 const char *X86TargetLowering::
11222 LowerXConstraint(EVT ConstraintVT) const {
11223   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11224   // 'f' like normal targets.
11225   if (ConstraintVT.isFloatingPoint()) {
11226     if (Subtarget->hasSSE2())
11227       return "Y";
11228     if (Subtarget->hasSSE1())
11229       return "x";
11230   }
11231
11232   return TargetLowering::LowerXConstraint(ConstraintVT);
11233 }
11234
11235 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11236 /// vector.  If it is invalid, don't add anything to Ops.
11237 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11238                                                      char Constraint,
11239                                                      std::vector<SDValue>&Ops,
11240                                                      SelectionDAG &DAG) const {
11241   SDValue Result(0, 0);
11242
11243   switch (Constraint) {
11244   default: break;
11245   case 'I':
11246     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11247       if (C->getZExtValue() <= 31) {
11248         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11249         break;
11250       }
11251     }
11252     return;
11253   case 'J':
11254     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11255       if (C->getZExtValue() <= 63) {
11256         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11257         break;
11258       }
11259     }
11260     return;
11261   case 'K':
11262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11263       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11264         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11265         break;
11266       }
11267     }
11268     return;
11269   case 'N':
11270     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11271       if (C->getZExtValue() <= 255) {
11272         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11273         break;
11274       }
11275     }
11276     return;
11277   case 'e': {
11278     // 32-bit signed value
11279     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11280       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11281                                            C->getSExtValue())) {
11282         // Widen to 64 bits here to get it sign extended.
11283         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11284         break;
11285       }
11286     // FIXME gcc accepts some relocatable values here too, but only in certain
11287     // memory models; it's complicated.
11288     }
11289     return;
11290   }
11291   case 'Z': {
11292     // 32-bit unsigned value
11293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11294       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11295                                            C->getZExtValue())) {
11296         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11297         break;
11298       }
11299     }
11300     // FIXME gcc accepts some relocatable values here too, but only in certain
11301     // memory models; it's complicated.
11302     return;
11303   }
11304   case 'i': {
11305     // Literal immediates are always ok.
11306     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11307       // Widen to 64 bits here to get it sign extended.
11308       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11309       break;
11310     }
11311
11312     // In any sort of PIC mode addresses need to be computed at runtime by
11313     // adding in a register or some sort of table lookup.  These can't
11314     // be used as immediates.
11315     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11316       return;
11317
11318     // If we are in non-pic codegen mode, we allow the address of a global (with
11319     // an optional displacement) to be used with 'i'.
11320     GlobalAddressSDNode *GA = 0;
11321     int64_t Offset = 0;
11322
11323     // Match either (GA), (GA+C), (GA+C1+C2), etc.
11324     while (1) {
11325       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11326         Offset += GA->getOffset();
11327         break;
11328       } else if (Op.getOpcode() == ISD::ADD) {
11329         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11330           Offset += C->getZExtValue();
11331           Op = Op.getOperand(0);
11332           continue;
11333         }
11334       } else if (Op.getOpcode() == ISD::SUB) {
11335         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11336           Offset += -C->getZExtValue();
11337           Op = Op.getOperand(0);
11338           continue;
11339         }
11340       }
11341
11342       // Otherwise, this isn't something we can handle, reject it.
11343       return;
11344     }
11345
11346     const GlobalValue *GV = GA->getGlobal();
11347     // If we require an extra load to get this address, as in PIC mode, we
11348     // can't accept it.
11349     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11350                                                         getTargetMachine())))
11351       return;
11352
11353     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11354                                         GA->getValueType(0), Offset);
11355     break;
11356   }
11357   }
11358
11359   if (Result.getNode()) {
11360     Ops.push_back(Result);
11361     return;
11362   }
11363   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11364 }
11365
11366 std::vector<unsigned> X86TargetLowering::
11367 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11368                                   EVT VT) const {
11369   if (Constraint.size() == 1) {
11370     // FIXME: not handling fp-stack yet!
11371     switch (Constraint[0]) {      // GCC X86 Constraint Letters
11372     default: break;  // Unknown constraint letter
11373     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11374       if (Subtarget->is64Bit()) {
11375         if (VT == MVT::i32)
11376           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11377                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11378                                        X86::R10D,X86::R11D,X86::R12D,
11379                                        X86::R13D,X86::R14D,X86::R15D,
11380                                        X86::EBP, X86::ESP, 0);
11381         else if (VT == MVT::i16)
11382           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
11383                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
11384                                        X86::R10W,X86::R11W,X86::R12W,
11385                                        X86::R13W,X86::R14W,X86::R15W,
11386                                        X86::BP,  X86::SP, 0);
11387         else if (VT == MVT::i8)
11388           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
11389                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11390                                        X86::R10B,X86::R11B,X86::R12B,
11391                                        X86::R13B,X86::R14B,X86::R15B,
11392                                        X86::BPL, X86::SPL, 0);
11393
11394         else if (VT == MVT::i64)
11395           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11396                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
11397                                        X86::R10, X86::R11, X86::R12,
11398                                        X86::R13, X86::R14, X86::R15,
11399                                        X86::RBP, X86::RSP, 0);
11400
11401         break;
11402       }
11403       // 32-bit fallthrough
11404     case 'Q':   // Q_REGS
11405       if (VT == MVT::i32)
11406         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11407       else if (VT == MVT::i16)
11408         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11409       else if (VT == MVT::i8)
11410         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11411       else if (VT == MVT::i64)
11412         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11413       break;
11414     }
11415   }
11416
11417   return std::vector<unsigned>();
11418 }
11419
11420 std::pair<unsigned, const TargetRegisterClass*>
11421 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11422                                                 EVT VT) const {
11423   // First, see if this is a constraint that directly corresponds to an LLVM
11424   // register class.
11425   if (Constraint.size() == 1) {
11426     // GCC Constraint Letters
11427     switch (Constraint[0]) {
11428     default: break;
11429     case 'r':   // GENERAL_REGS
11430     case 'l':   // INDEX_REGS
11431       if (VT == MVT::i8)
11432         return std::make_pair(0U, X86::GR8RegisterClass);
11433       if (VT == MVT::i16)
11434         return std::make_pair(0U, X86::GR16RegisterClass);
11435       if (VT == MVT::i32 || !Subtarget->is64Bit())
11436         return std::make_pair(0U, X86::GR32RegisterClass);
11437       return std::make_pair(0U, X86::GR64RegisterClass);
11438     case 'R':   // LEGACY_REGS
11439       if (VT == MVT::i8)
11440         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11441       if (VT == MVT::i16)
11442         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11443       if (VT == MVT::i32 || !Subtarget->is64Bit())
11444         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11445       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11446     case 'f':  // FP Stack registers.
11447       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11448       // value to the correct fpstack register class.
11449       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11450         return std::make_pair(0U, X86::RFP32RegisterClass);
11451       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11452         return std::make_pair(0U, X86::RFP64RegisterClass);
11453       return std::make_pair(0U, X86::RFP80RegisterClass);
11454     case 'y':   // MMX_REGS if MMX allowed.
11455       if (!Subtarget->hasMMX()) break;
11456       return std::make_pair(0U, X86::VR64RegisterClass);
11457     case 'Y':   // SSE_REGS if SSE2 allowed
11458       if (!Subtarget->hasSSE2()) break;
11459       // FALL THROUGH.
11460     case 'x':   // SSE_REGS if SSE1 allowed
11461       if (!Subtarget->hasSSE1()) break;
11462
11463       switch (VT.getSimpleVT().SimpleTy) {
11464       default: break;
11465       // Scalar SSE types.
11466       case MVT::f32:
11467       case MVT::i32:
11468         return std::make_pair(0U, X86::FR32RegisterClass);
11469       case MVT::f64:
11470       case MVT::i64:
11471         return std::make_pair(0U, X86::FR64RegisterClass);
11472       // Vector types.
11473       case MVT::v16i8:
11474       case MVT::v8i16:
11475       case MVT::v4i32:
11476       case MVT::v2i64:
11477       case MVT::v4f32:
11478       case MVT::v2f64:
11479         return std::make_pair(0U, X86::VR128RegisterClass);
11480       }
11481       break;
11482     }
11483   }
11484
11485   // Use the default implementation in TargetLowering to convert the register
11486   // constraint into a member of a register class.
11487   std::pair<unsigned, const TargetRegisterClass*> Res;
11488   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11489
11490   // Not found as a standard register?
11491   if (Res.second == 0) {
11492     // Map st(0) -> st(7) -> ST0
11493     if (Constraint.size() == 7 && Constraint[0] == '{' &&
11494         tolower(Constraint[1]) == 's' &&
11495         tolower(Constraint[2]) == 't' &&
11496         Constraint[3] == '(' &&
11497         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11498         Constraint[5] == ')' &&
11499         Constraint[6] == '}') {
11500
11501       Res.first = X86::ST0+Constraint[4]-'0';
11502       Res.second = X86::RFP80RegisterClass;
11503       return Res;
11504     }
11505
11506     // GCC allows "st(0)" to be called just plain "st".
11507     if (StringRef("{st}").equals_lower(Constraint)) {
11508       Res.first = X86::ST0;
11509       Res.second = X86::RFP80RegisterClass;
11510       return Res;
11511     }
11512
11513     // flags -> EFLAGS
11514     if (StringRef("{flags}").equals_lower(Constraint)) {
11515       Res.first = X86::EFLAGS;
11516       Res.second = X86::CCRRegisterClass;
11517       return Res;
11518     }
11519
11520     // 'A' means EAX + EDX.
11521     if (Constraint == "A") {
11522       Res.first = X86::EAX;
11523       Res.second = X86::GR32_ADRegisterClass;
11524       return Res;
11525     }
11526     return Res;
11527   }
11528
11529   // Otherwise, check to see if this is a register class of the wrong value
11530   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11531   // turn into {ax},{dx}.
11532   if (Res.second->hasType(VT))
11533     return Res;   // Correct type already, nothing to do.
11534
11535   // All of the single-register GCC register classes map their values onto
11536   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
11537   // really want an 8-bit or 32-bit register, map to the appropriate register
11538   // class and return the appropriate register.
11539   if (Res.second == X86::GR16RegisterClass) {
11540     if (VT == MVT::i8) {
11541       unsigned DestReg = 0;
11542       switch (Res.first) {
11543       default: break;
11544       case X86::AX: DestReg = X86::AL; break;
11545       case X86::DX: DestReg = X86::DL; break;
11546       case X86::CX: DestReg = X86::CL; break;
11547       case X86::BX: DestReg = X86::BL; break;
11548       }
11549       if (DestReg) {
11550         Res.first = DestReg;
11551         Res.second = X86::GR8RegisterClass;
11552       }
11553     } else if (VT == MVT::i32) {
11554       unsigned DestReg = 0;
11555       switch (Res.first) {
11556       default: break;
11557       case X86::AX: DestReg = X86::EAX; break;
11558       case X86::DX: DestReg = X86::EDX; break;
11559       case X86::CX: DestReg = X86::ECX; break;
11560       case X86::BX: DestReg = X86::EBX; break;
11561       case X86::SI: DestReg = X86::ESI; break;
11562       case X86::DI: DestReg = X86::EDI; break;
11563       case X86::BP: DestReg = X86::EBP; break;
11564       case X86::SP: DestReg = X86::ESP; break;
11565       }
11566       if (DestReg) {
11567         Res.first = DestReg;
11568         Res.second = X86::GR32RegisterClass;
11569       }
11570     } else if (VT == MVT::i64) {
11571       unsigned DestReg = 0;
11572       switch (Res.first) {
11573       default: break;
11574       case X86::AX: DestReg = X86::RAX; break;
11575       case X86::DX: DestReg = X86::RDX; break;
11576       case X86::CX: DestReg = X86::RCX; break;
11577       case X86::BX: DestReg = X86::RBX; break;
11578       case X86::SI: DestReg = X86::RSI; break;
11579       case X86::DI: DestReg = X86::RDI; break;
11580       case X86::BP: DestReg = X86::RBP; break;
11581       case X86::SP: DestReg = X86::RSP; break;
11582       }
11583       if (DestReg) {
11584         Res.first = DestReg;
11585         Res.second = X86::GR64RegisterClass;
11586       }
11587     }
11588   } else if (Res.second == X86::FR32RegisterClass ||
11589              Res.second == X86::FR64RegisterClass ||
11590              Res.second == X86::VR128RegisterClass) {
11591     // Handle references to XMM physical registers that got mapped into the
11592     // wrong class.  This can happen with constraints like {xmm0} where the
11593     // target independent register mapper will just pick the first match it can
11594     // find, ignoring the required type.
11595     if (VT == MVT::f32)
11596       Res.second = X86::FR32RegisterClass;
11597     else if (VT == MVT::f64)
11598       Res.second = X86::FR64RegisterClass;
11599     else if (X86::VR128RegisterClass->hasType(VT))
11600       Res.second = X86::VR128RegisterClass;
11601   }
11602
11603   return Res;
11604 }