27226d885d7841f0d893ec9740a7968081bff7f3
[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         const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1705         // Get to the caller-allocated home save location.  Add 8 to account
1706         // for the return address.
1707         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1708         FuncInfo->setRegSaveFrameIndex(
1709           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1710         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1711       } else {
1712         // For X86-64, if there are vararg parameters that are passed via
1713         // registers, then we must store them to their spots on the stack so they
1714         // may be loaded by deferencing the result of va_next.
1715         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1716         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1717         FuncInfo->setRegSaveFrameIndex(
1718           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1719                                false));
1720       }
1721
1722       // Store the integer parameter registers.
1723       SmallVector<SDValue, 8> MemOps;
1724       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1725                                         getPointerTy());
1726       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1727       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1728         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1729                                   DAG.getIntPtrConstant(Offset));
1730         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1731                                      X86::GR64RegisterClass);
1732         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1733         SDValue Store =
1734           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1735                        MachinePointerInfo::getFixedStack(
1736                          FuncInfo->getRegSaveFrameIndex(), Offset),
1737                        false, false, 0);
1738         MemOps.push_back(Store);
1739         Offset += 8;
1740       }
1741
1742       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1743         // Now store the XMM (fp + vector) parameter registers.
1744         SmallVector<SDValue, 11> SaveXMMOps;
1745         SaveXMMOps.push_back(Chain);
1746
1747         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1748         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1749         SaveXMMOps.push_back(ALVal);
1750
1751         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1752                                FuncInfo->getRegSaveFrameIndex()));
1753         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1754                                FuncInfo->getVarArgsFPOffset()));
1755
1756         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1757           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1758                                        X86::VR128RegisterClass);
1759           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1760           SaveXMMOps.push_back(Val);
1761         }
1762         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1763                                      MVT::Other,
1764                                      &SaveXMMOps[0], SaveXMMOps.size()));
1765       }
1766
1767       if (!MemOps.empty())
1768         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1769                             &MemOps[0], MemOps.size());
1770     }
1771   }
1772
1773   // Some CCs need callee pop.
1774   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1775     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1776   } else {
1777     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1778     // If this is an sret function, the return should pop the hidden pointer.
1779     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1780       FuncInfo->setBytesToPopOnReturn(4);
1781   }
1782
1783   if (!Is64Bit) {
1784     // RegSaveFrameIndex is X86-64 only.
1785     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1786     if (CallConv == CallingConv::X86_FastCall ||
1787         CallConv == CallingConv::X86_ThisCall)
1788       // fastcc functions can't have varargs.
1789       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1790   }
1791
1792   return Chain;
1793 }
1794
1795 SDValue
1796 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1797                                     SDValue StackPtr, SDValue Arg,
1798                                     DebugLoc dl, SelectionDAG &DAG,
1799                                     const CCValAssign &VA,
1800                                     ISD::ArgFlagsTy Flags) const {
1801   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1802   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1803   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1804   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1805   if (Flags.isByVal())
1806     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1807
1808   return DAG.getStore(Chain, dl, Arg, PtrOff,
1809                       MachinePointerInfo::getStack(LocMemOffset),
1810                       false, false, 0);
1811 }
1812
1813 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1814 /// optimization is performed and it is required.
1815 SDValue
1816 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1817                                            SDValue &OutRetAddr, SDValue Chain,
1818                                            bool IsTailCall, bool Is64Bit,
1819                                            int FPDiff, DebugLoc dl) const {
1820   // Adjust the Return address stack slot.
1821   EVT VT = getPointerTy();
1822   OutRetAddr = getReturnAddressFrameIndex(DAG);
1823
1824   // Load the "old" Return address.
1825   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1826                            false, false, 0);
1827   return SDValue(OutRetAddr.getNode(), 1);
1828 }
1829
1830 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1831 /// optimization is performed and it is required (FPDiff!=0).
1832 static SDValue
1833 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1834                          SDValue Chain, SDValue RetAddrFrIdx,
1835                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1836   // Store the return address to the appropriate stack slot.
1837   if (!FPDiff) return Chain;
1838   // Calculate the new stack slot for the return address.
1839   int SlotSize = Is64Bit ? 8 : 4;
1840   int NewReturnAddrFI =
1841     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1842   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1843   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1844   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1845                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1846                        false, false, 0);
1847   return Chain;
1848 }
1849
1850 SDValue
1851 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1852                              CallingConv::ID CallConv, bool isVarArg,
1853                              bool &isTailCall,
1854                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1855                              const SmallVectorImpl<SDValue> &OutVals,
1856                              const SmallVectorImpl<ISD::InputArg> &Ins,
1857                              DebugLoc dl, SelectionDAG &DAG,
1858                              SmallVectorImpl<SDValue> &InVals) const {
1859   MachineFunction &MF = DAG.getMachineFunction();
1860   bool Is64Bit        = Subtarget->is64Bit();
1861   bool IsStructRet    = CallIsStructReturn(Outs);
1862   bool IsSibcall      = false;
1863
1864   if (isTailCall) {
1865     // Check if it's really possible to do a tail call.
1866     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1867                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1868                                                    Outs, OutVals, Ins, DAG);
1869
1870     // Sibcalls are automatically detected tailcalls which do not require
1871     // ABI changes.
1872     if (!GuaranteedTailCallOpt && isTailCall)
1873       IsSibcall = true;
1874
1875     if (isTailCall)
1876       ++NumTailCalls;
1877   }
1878
1879   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1880          "Var args not supported with calling convention fastcc or ghc");
1881
1882   // Analyze operands of the call, assigning locations to each operand.
1883   SmallVector<CCValAssign, 16> ArgLocs;
1884   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1885                  ArgLocs, *DAG.getContext());
1886   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1887
1888   // Get a count of how many bytes are to be pushed on the stack.
1889   unsigned NumBytes = CCInfo.getNextStackOffset();
1890   if (IsSibcall)
1891     // This is a sibcall. The memory operands are available in caller's
1892     // own caller's stack.
1893     NumBytes = 0;
1894   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1895     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1896
1897   int FPDiff = 0;
1898   if (isTailCall && !IsSibcall) {
1899     // Lower arguments at fp - stackoffset + fpdiff.
1900     unsigned NumBytesCallerPushed =
1901       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1902     FPDiff = NumBytesCallerPushed - NumBytes;
1903
1904     // Set the delta of movement of the returnaddr stackslot.
1905     // But only set if delta is greater than previous delta.
1906     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1907       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1908   }
1909
1910   if (!IsSibcall)
1911     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1912
1913   SDValue RetAddrFrIdx;
1914   // Load return adress for tail calls.
1915   if (isTailCall && FPDiff)
1916     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1917                                     Is64Bit, FPDiff, dl);
1918
1919   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1920   SmallVector<SDValue, 8> MemOpChains;
1921   SDValue StackPtr;
1922
1923   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1924   // of tail call optimization arguments are handle later.
1925   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1926     CCValAssign &VA = ArgLocs[i];
1927     EVT RegVT = VA.getLocVT();
1928     SDValue Arg = OutVals[i];
1929     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1930     bool isByVal = Flags.isByVal();
1931
1932     // Promote the value if needed.
1933     switch (VA.getLocInfo()) {
1934     default: llvm_unreachable("Unknown loc info!");
1935     case CCValAssign::Full: break;
1936     case CCValAssign::SExt:
1937       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1938       break;
1939     case CCValAssign::ZExt:
1940       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1941       break;
1942     case CCValAssign::AExt:
1943       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1944         // Special case: passing MMX values in XMM registers.
1945         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1946         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1947         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1948       } else
1949         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1950       break;
1951     case CCValAssign::BCvt:
1952       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1953       break;
1954     case CCValAssign::Indirect: {
1955       // Store the argument.
1956       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1957       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1958       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1959                            MachinePointerInfo::getFixedStack(FI),
1960                            false, false, 0);
1961       Arg = SpillSlot;
1962       break;
1963     }
1964     }
1965
1966     if (VA.isRegLoc()) {
1967       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1968       if (isVarArg && Subtarget->isTargetWin64()) {
1969         // Win64 ABI requires argument XMM reg to be copied to the corresponding
1970         // shadow reg if callee is a varargs function.
1971         unsigned ShadowReg = 0;
1972         switch (VA.getLocReg()) {
1973         case X86::XMM0: ShadowReg = X86::RCX; break;
1974         case X86::XMM1: ShadowReg = X86::RDX; break;
1975         case X86::XMM2: ShadowReg = X86::R8; break;
1976         case X86::XMM3: ShadowReg = X86::R9; break;
1977         }
1978         if (ShadowReg)
1979           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1980       }
1981     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1982       assert(VA.isMemLoc());
1983       if (StackPtr.getNode() == 0)
1984         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1985       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1986                                              dl, DAG, VA, Flags));
1987     }
1988   }
1989
1990   if (!MemOpChains.empty())
1991     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1992                         &MemOpChains[0], MemOpChains.size());
1993
1994   // Build a sequence of copy-to-reg nodes chained together with token chain
1995   // and flag operands which copy the outgoing args into registers.
1996   SDValue InFlag;
1997   // Tail call byval lowering might overwrite argument registers so in case of
1998   // tail call optimization the copies to registers are lowered later.
1999   if (!isTailCall)
2000     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2001       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2002                                RegsToPass[i].second, InFlag);
2003       InFlag = Chain.getValue(1);
2004     }
2005
2006   if (Subtarget->isPICStyleGOT()) {
2007     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2008     // GOT pointer.
2009     if (!isTailCall) {
2010       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2011                                DAG.getNode(X86ISD::GlobalBaseReg,
2012                                            DebugLoc(), getPointerTy()),
2013                                InFlag);
2014       InFlag = Chain.getValue(1);
2015     } else {
2016       // If we are tail calling and generating PIC/GOT style code load the
2017       // address of the callee into ECX. The value in ecx is used as target of
2018       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2019       // for tail calls on PIC/GOT architectures. Normally we would just put the
2020       // address of GOT into ebx and then call target@PLT. But for tail calls
2021       // ebx would be restored (since ebx is callee saved) before jumping to the
2022       // target@PLT.
2023
2024       // Note: The actual moving to ECX is done further down.
2025       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2026       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2027           !G->getGlobal()->hasProtectedVisibility())
2028         Callee = LowerGlobalAddress(Callee, DAG);
2029       else if (isa<ExternalSymbolSDNode>(Callee))
2030         Callee = LowerExternalSymbol(Callee, DAG);
2031     }
2032   }
2033
2034   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2035     // From AMD64 ABI document:
2036     // For calls that may call functions that use varargs or stdargs
2037     // (prototype-less calls or calls to functions containing ellipsis (...) in
2038     // the declaration) %al is used as hidden argument to specify the number
2039     // of SSE registers used. The contents of %al do not need to match exactly
2040     // the number of registers, but must be an ubound on the number of SSE
2041     // registers used and is in the range 0 - 8 inclusive.
2042
2043     // Count the number of XMM registers allocated.
2044     static const unsigned XMMArgRegs[] = {
2045       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2046       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2047     };
2048     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2049     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2050            && "SSE registers cannot be used when SSE is disabled");
2051
2052     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2053                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2054     InFlag = Chain.getValue(1);
2055   }
2056
2057
2058   // For tail calls lower the arguments to the 'real' stack slot.
2059   if (isTailCall) {
2060     // Force all the incoming stack arguments to be loaded from the stack
2061     // before any new outgoing arguments are stored to the stack, because the
2062     // outgoing stack slots may alias the incoming argument stack slots, and
2063     // the alias isn't otherwise explicit. This is slightly more conservative
2064     // than necessary, because it means that each store effectively depends
2065     // on every argument instead of just those arguments it would clobber.
2066     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2067
2068     SmallVector<SDValue, 8> MemOpChains2;
2069     SDValue FIN;
2070     int FI = 0;
2071     // Do not flag preceeding copytoreg stuff together with the following stuff.
2072     InFlag = SDValue();
2073     if (GuaranteedTailCallOpt) {
2074       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2075         CCValAssign &VA = ArgLocs[i];
2076         if (VA.isRegLoc())
2077           continue;
2078         assert(VA.isMemLoc());
2079         SDValue Arg = OutVals[i];
2080         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2081         // Create frame index.
2082         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2083         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2084         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2085         FIN = DAG.getFrameIndex(FI, getPointerTy());
2086
2087         if (Flags.isByVal()) {
2088           // Copy relative to framepointer.
2089           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2090           if (StackPtr.getNode() == 0)
2091             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2092                                           getPointerTy());
2093           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2094
2095           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2096                                                            ArgChain,
2097                                                            Flags, DAG, dl));
2098         } else {
2099           // Store relative to framepointer.
2100           MemOpChains2.push_back(
2101             DAG.getStore(ArgChain, dl, Arg, FIN,
2102                          MachinePointerInfo::getFixedStack(FI),
2103                          false, false, 0));
2104         }
2105       }
2106     }
2107
2108     if (!MemOpChains2.empty())
2109       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2110                           &MemOpChains2[0], MemOpChains2.size());
2111
2112     // Copy arguments to their registers.
2113     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2114       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2115                                RegsToPass[i].second, InFlag);
2116       InFlag = Chain.getValue(1);
2117     }
2118     InFlag =SDValue();
2119
2120     // Store the return address to the appropriate stack slot.
2121     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2122                                      FPDiff, dl);
2123   }
2124
2125   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2126     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2127     // In the 64-bit large code model, we have to make all calls
2128     // through a register, since the call instruction's 32-bit
2129     // pc-relative offset may not be large enough to hold the whole
2130     // address.
2131   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2132     // If the callee is a GlobalAddress node (quite common, every direct call
2133     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2134     // it.
2135
2136     // We should use extra load for direct calls to dllimported functions in
2137     // non-JIT mode.
2138     const GlobalValue *GV = G->getGlobal();
2139     if (!GV->hasDLLImportLinkage()) {
2140       unsigned char OpFlags = 0;
2141
2142       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2143       // external symbols most go through the PLT in PIC mode.  If the symbol
2144       // has hidden or protected visibility, or if it is static or local, then
2145       // we don't need to use the PLT - we can directly call it.
2146       if (Subtarget->isTargetELF() &&
2147           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2148           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2149         OpFlags = X86II::MO_PLT;
2150       } else if (Subtarget->isPICStyleStubAny() &&
2151                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2152                  Subtarget->getDarwinVers() < 9) {
2153         // PC-relative references to external symbols should go through $stub,
2154         // unless we're building with the leopard linker or later, which
2155         // automatically synthesizes these stubs.
2156         OpFlags = X86II::MO_DARWIN_STUB;
2157       }
2158
2159       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2160                                           G->getOffset(), OpFlags);
2161     }
2162   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2163     unsigned char OpFlags = 0;
2164
2165     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2166     // symbols should go through the PLT.
2167     if (Subtarget->isTargetELF() &&
2168         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2169       OpFlags = X86II::MO_PLT;
2170     } else if (Subtarget->isPICStyleStubAny() &&
2171                Subtarget->getDarwinVers() < 9) {
2172       // PC-relative references to external symbols should go through $stub,
2173       // unless we're building with the leopard linker or later, which
2174       // automatically synthesizes these stubs.
2175       OpFlags = X86II::MO_DARWIN_STUB;
2176     }
2177
2178     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2179                                          OpFlags);
2180   }
2181
2182   // Returns a chain & a flag for retval copy to use.
2183   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2184   SmallVector<SDValue, 8> Ops;
2185
2186   if (!IsSibcall && isTailCall) {
2187     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2188                            DAG.getIntPtrConstant(0, true), InFlag);
2189     InFlag = Chain.getValue(1);
2190   }
2191
2192   Ops.push_back(Chain);
2193   Ops.push_back(Callee);
2194
2195   if (isTailCall)
2196     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2197
2198   // Add argument registers to the end of the list so that they are known live
2199   // into the call.
2200   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2201     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2202                                   RegsToPass[i].second.getValueType()));
2203
2204   // Add an implicit use GOT pointer in EBX.
2205   if (!isTailCall && Subtarget->isPICStyleGOT())
2206     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2207
2208   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2209   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2210     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2211
2212   if (InFlag.getNode())
2213     Ops.push_back(InFlag);
2214
2215   if (isTailCall) {
2216     // We used to do:
2217     //// If this is the first return lowered for this function, add the regs
2218     //// to the liveout set for the function.
2219     // This isn't right, although it's probably harmless on x86; liveouts
2220     // should be computed from returns not tail calls.  Consider a void
2221     // function making a tail call to a function returning int.
2222     return DAG.getNode(X86ISD::TC_RETURN, dl,
2223                        NodeTys, &Ops[0], Ops.size());
2224   }
2225
2226   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2227   InFlag = Chain.getValue(1);
2228
2229   // Create the CALLSEQ_END node.
2230   unsigned NumBytesForCalleeToPush;
2231   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2232     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2233   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2234     // If this is a call to a struct-return function, the callee
2235     // pops the hidden struct pointer, so we have to push it back.
2236     // This is common for Darwin/X86, Linux & Mingw32 targets.
2237     NumBytesForCalleeToPush = 4;
2238   else
2239     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2240
2241   // Returns a flag for retval copy to use.
2242   if (!IsSibcall) {
2243     Chain = DAG.getCALLSEQ_END(Chain,
2244                                DAG.getIntPtrConstant(NumBytes, true),
2245                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2246                                                      true),
2247                                InFlag);
2248     InFlag = Chain.getValue(1);
2249   }
2250
2251   // Handle result values, copying them out of physregs into vregs that we
2252   // return.
2253   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2254                          Ins, dl, DAG, InVals);
2255 }
2256
2257
2258 //===----------------------------------------------------------------------===//
2259 //                Fast Calling Convention (tail call) implementation
2260 //===----------------------------------------------------------------------===//
2261
2262 //  Like std call, callee cleans arguments, convention except that ECX is
2263 //  reserved for storing the tail called function address. Only 2 registers are
2264 //  free for argument passing (inreg). Tail call optimization is performed
2265 //  provided:
2266 //                * tailcallopt is enabled
2267 //                * caller/callee are fastcc
2268 //  On X86_64 architecture with GOT-style position independent code only local
2269 //  (within module) calls are supported at the moment.
2270 //  To keep the stack aligned according to platform abi the function
2271 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2272 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2273 //  If a tail called function callee has more arguments than the caller the
2274 //  caller needs to make sure that there is room to move the RETADDR to. This is
2275 //  achieved by reserving an area the size of the argument delta right after the
2276 //  original REtADDR, but before the saved framepointer or the spilled registers
2277 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2278 //  stack layout:
2279 //    arg1
2280 //    arg2
2281 //    RETADDR
2282 //    [ new RETADDR
2283 //      move area ]
2284 //    (possible EBP)
2285 //    ESI
2286 //    EDI
2287 //    local1 ..
2288
2289 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2290 /// for a 16 byte align requirement.
2291 unsigned
2292 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2293                                                SelectionDAG& DAG) const {
2294   MachineFunction &MF = DAG.getMachineFunction();
2295   const TargetMachine &TM = MF.getTarget();
2296   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2297   unsigned StackAlignment = TFI.getStackAlignment();
2298   uint64_t AlignMask = StackAlignment - 1;
2299   int64_t Offset = StackSize;
2300   uint64_t SlotSize = TD->getPointerSize();
2301   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2302     // Number smaller than 12 so just add the difference.
2303     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2304   } else {
2305     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2306     Offset = ((~AlignMask) & Offset) + StackAlignment +
2307       (StackAlignment-SlotSize);
2308   }
2309   return Offset;
2310 }
2311
2312 /// MatchingStackOffset - Return true if the given stack call argument is
2313 /// already available in the same position (relatively) of the caller's
2314 /// incoming argument stack.
2315 static
2316 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2317                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2318                          const X86InstrInfo *TII) {
2319   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2320   int FI = INT_MAX;
2321   if (Arg.getOpcode() == ISD::CopyFromReg) {
2322     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2323     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2324       return false;
2325     MachineInstr *Def = MRI->getVRegDef(VR);
2326     if (!Def)
2327       return false;
2328     if (!Flags.isByVal()) {
2329       if (!TII->isLoadFromStackSlot(Def, FI))
2330         return false;
2331     } else {
2332       unsigned Opcode = Def->getOpcode();
2333       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2334           Def->getOperand(1).isFI()) {
2335         FI = Def->getOperand(1).getIndex();
2336         Bytes = Flags.getByValSize();
2337       } else
2338         return false;
2339     }
2340   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2341     if (Flags.isByVal())
2342       // ByVal argument is passed in as a pointer but it's now being
2343       // dereferenced. e.g.
2344       // define @foo(%struct.X* %A) {
2345       //   tail call @bar(%struct.X* byval %A)
2346       // }
2347       return false;
2348     SDValue Ptr = Ld->getBasePtr();
2349     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2350     if (!FINode)
2351       return false;
2352     FI = FINode->getIndex();
2353   } else
2354     return false;
2355
2356   assert(FI != INT_MAX);
2357   if (!MFI->isFixedObjectIndex(FI))
2358     return false;
2359   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2360 }
2361
2362 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2363 /// for tail call optimization. Targets which want to do tail call
2364 /// optimization should implement this function.
2365 bool
2366 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2367                                                      CallingConv::ID CalleeCC,
2368                                                      bool isVarArg,
2369                                                      bool isCalleeStructRet,
2370                                                      bool isCallerStructRet,
2371                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2372                                     const SmallVectorImpl<SDValue> &OutVals,
2373                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2374                                                      SelectionDAG& DAG) const {
2375   if (!IsTailCallConvention(CalleeCC) &&
2376       CalleeCC != CallingConv::C)
2377     return false;
2378
2379   // If -tailcallopt is specified, make fastcc functions tail-callable.
2380   const MachineFunction &MF = DAG.getMachineFunction();
2381   const Function *CallerF = DAG.getMachineFunction().getFunction();
2382   CallingConv::ID CallerCC = CallerF->getCallingConv();
2383   bool CCMatch = CallerCC == CalleeCC;
2384
2385   if (GuaranteedTailCallOpt) {
2386     if (IsTailCallConvention(CalleeCC) && CCMatch)
2387       return true;
2388     return false;
2389   }
2390
2391   // Look for obvious safe cases to perform tail call optimization that do not
2392   // require ABI changes. This is what gcc calls sibcall.
2393
2394   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2395   // emit a special epilogue.
2396   if (RegInfo->needsStackRealignment(MF))
2397     return false;
2398
2399   // Do not sibcall optimize vararg calls unless the call site is not passing
2400   // any arguments.
2401   if (isVarArg && !Outs.empty())
2402     return false;
2403
2404   // Also avoid sibcall optimization if either caller or callee uses struct
2405   // return semantics.
2406   if (isCalleeStructRet || isCallerStructRet)
2407     return false;
2408
2409   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2410   // Therefore if it's not used by the call it is not safe to optimize this into
2411   // a sibcall.
2412   bool Unused = false;
2413   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2414     if (!Ins[i].Used) {
2415       Unused = true;
2416       break;
2417     }
2418   }
2419   if (Unused) {
2420     SmallVector<CCValAssign, 16> RVLocs;
2421     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2422                    RVLocs, *DAG.getContext());
2423     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2424     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2425       CCValAssign &VA = RVLocs[i];
2426       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2427         return false;
2428     }
2429   }
2430
2431   // If the calling conventions do not match, then we'd better make sure the
2432   // results are returned in the same way as what the caller expects.
2433   if (!CCMatch) {
2434     SmallVector<CCValAssign, 16> RVLocs1;
2435     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2436                     RVLocs1, *DAG.getContext());
2437     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2438
2439     SmallVector<CCValAssign, 16> RVLocs2;
2440     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2441                     RVLocs2, *DAG.getContext());
2442     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2443
2444     if (RVLocs1.size() != RVLocs2.size())
2445       return false;
2446     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2447       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2448         return false;
2449       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2450         return false;
2451       if (RVLocs1[i].isRegLoc()) {
2452         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2453           return false;
2454       } else {
2455         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2456           return false;
2457       }
2458     }
2459   }
2460
2461   // If the callee takes no arguments then go on to check the results of the
2462   // call.
2463   if (!Outs.empty()) {
2464     // Check if stack adjustment is needed. For now, do not do this if any
2465     // argument is passed on the stack.
2466     SmallVector<CCValAssign, 16> ArgLocs;
2467     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2468                    ArgLocs, *DAG.getContext());
2469     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2470     if (CCInfo.getNextStackOffset()) {
2471       MachineFunction &MF = DAG.getMachineFunction();
2472       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2473         return false;
2474       if (Subtarget->isTargetWin64())
2475         // Win64 ABI has additional complications.
2476         return false;
2477
2478       // Check if the arguments are already laid out in the right way as
2479       // the caller's fixed stack objects.
2480       MachineFrameInfo *MFI = MF.getFrameInfo();
2481       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2482       const X86InstrInfo *TII =
2483         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2484       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2485         CCValAssign &VA = ArgLocs[i];
2486         SDValue Arg = OutVals[i];
2487         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2488         if (VA.getLocInfo() == CCValAssign::Indirect)
2489           return false;
2490         if (!VA.isRegLoc()) {
2491           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2492                                    MFI, MRI, TII))
2493             return false;
2494         }
2495       }
2496     }
2497
2498     // If the tailcall address may be in a register, then make sure it's
2499     // possible to register allocate for it. In 32-bit, the call address can
2500     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2501     // callee-saved registers are restored. These happen to be the same
2502     // registers used to pass 'inreg' arguments so watch out for those.
2503     if (!Subtarget->is64Bit() &&
2504         !isa<GlobalAddressSDNode>(Callee) &&
2505         !isa<ExternalSymbolSDNode>(Callee)) {
2506       unsigned NumInRegs = 0;
2507       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2508         CCValAssign &VA = ArgLocs[i];
2509         if (!VA.isRegLoc())
2510           continue;
2511         unsigned Reg = VA.getLocReg();
2512         switch (Reg) {
2513         default: break;
2514         case X86::EAX: case X86::EDX: case X86::ECX:
2515           if (++NumInRegs == 3)
2516             return false;
2517           break;
2518         }
2519       }
2520     }
2521   }
2522
2523   return true;
2524 }
2525
2526 FastISel *
2527 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2528   return X86::createFastISel(funcInfo);
2529 }
2530
2531
2532 //===----------------------------------------------------------------------===//
2533 //                           Other Lowering Hooks
2534 //===----------------------------------------------------------------------===//
2535
2536 static bool MayFoldLoad(SDValue Op) {
2537   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2538 }
2539
2540 static bool MayFoldIntoStore(SDValue Op) {
2541   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2542 }
2543
2544 static bool isTargetShuffle(unsigned Opcode) {
2545   switch(Opcode) {
2546   default: return false;
2547   case X86ISD::PSHUFD:
2548   case X86ISD::PSHUFHW:
2549   case X86ISD::PSHUFLW:
2550   case X86ISD::SHUFPD:
2551   case X86ISD::PALIGN:
2552   case X86ISD::SHUFPS:
2553   case X86ISD::MOVLHPS:
2554   case X86ISD::MOVLHPD:
2555   case X86ISD::MOVHLPS:
2556   case X86ISD::MOVLPS:
2557   case X86ISD::MOVLPD:
2558   case X86ISD::MOVSHDUP:
2559   case X86ISD::MOVSLDUP:
2560   case X86ISD::MOVDDUP:
2561   case X86ISD::MOVSS:
2562   case X86ISD::MOVSD:
2563   case X86ISD::UNPCKLPS:
2564   case X86ISD::UNPCKLPD:
2565   case X86ISD::PUNPCKLWD:
2566   case X86ISD::PUNPCKLBW:
2567   case X86ISD::PUNPCKLDQ:
2568   case X86ISD::PUNPCKLQDQ:
2569   case X86ISD::UNPCKHPS:
2570   case X86ISD::UNPCKHPD:
2571   case X86ISD::PUNPCKHWD:
2572   case X86ISD::PUNPCKHBW:
2573   case X86ISD::PUNPCKHDQ:
2574   case X86ISD::PUNPCKHQDQ:
2575     return true;
2576   }
2577   return false;
2578 }
2579
2580 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2581                                                SDValue V1, SelectionDAG &DAG) {
2582   switch(Opc) {
2583   default: llvm_unreachable("Unknown x86 shuffle node");
2584   case X86ISD::MOVSHDUP:
2585   case X86ISD::MOVSLDUP:
2586   case X86ISD::MOVDDUP:
2587     return DAG.getNode(Opc, dl, VT, V1);
2588   }
2589
2590   return SDValue();
2591 }
2592
2593 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2594                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2595   switch(Opc) {
2596   default: llvm_unreachable("Unknown x86 shuffle node");
2597   case X86ISD::PSHUFD:
2598   case X86ISD::PSHUFHW:
2599   case X86ISD::PSHUFLW:
2600     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2601   }
2602
2603   return SDValue();
2604 }
2605
2606 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2607                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2608   switch(Opc) {
2609   default: llvm_unreachable("Unknown x86 shuffle node");
2610   case X86ISD::PALIGN:
2611   case X86ISD::SHUFPD:
2612   case X86ISD::SHUFPS:
2613     return DAG.getNode(Opc, dl, VT, V1, V2,
2614                        DAG.getConstant(TargetMask, MVT::i8));
2615   }
2616   return SDValue();
2617 }
2618
2619 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2620                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2621   switch(Opc) {
2622   default: llvm_unreachable("Unknown x86 shuffle node");
2623   case X86ISD::MOVLHPS:
2624   case X86ISD::MOVLHPD:
2625   case X86ISD::MOVHLPS:
2626   case X86ISD::MOVLPS:
2627   case X86ISD::MOVLPD:
2628   case X86ISD::MOVSS:
2629   case X86ISD::MOVSD:
2630   case X86ISD::UNPCKLPS:
2631   case X86ISD::UNPCKLPD:
2632   case X86ISD::PUNPCKLWD:
2633   case X86ISD::PUNPCKLBW:
2634   case X86ISD::PUNPCKLDQ:
2635   case X86ISD::PUNPCKLQDQ:
2636   case X86ISD::UNPCKHPS:
2637   case X86ISD::UNPCKHPD:
2638   case X86ISD::PUNPCKHWD:
2639   case X86ISD::PUNPCKHBW:
2640   case X86ISD::PUNPCKHDQ:
2641   case X86ISD::PUNPCKHQDQ:
2642     return DAG.getNode(Opc, dl, VT, V1, V2);
2643   }
2644   return SDValue();
2645 }
2646
2647 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2648   MachineFunction &MF = DAG.getMachineFunction();
2649   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2650   int ReturnAddrIndex = FuncInfo->getRAIndex();
2651
2652   if (ReturnAddrIndex == 0) {
2653     // Set up a frame object for the return address.
2654     uint64_t SlotSize = TD->getPointerSize();
2655     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2656                                                            false);
2657     FuncInfo->setRAIndex(ReturnAddrIndex);
2658   }
2659
2660   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2661 }
2662
2663
2664 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2665                                        bool hasSymbolicDisplacement) {
2666   // Offset should fit into 32 bit immediate field.
2667   if (!isInt<32>(Offset))
2668     return false;
2669
2670   // If we don't have a symbolic displacement - we don't have any extra
2671   // restrictions.
2672   if (!hasSymbolicDisplacement)
2673     return true;
2674
2675   // FIXME: Some tweaks might be needed for medium code model.
2676   if (M != CodeModel::Small && M != CodeModel::Kernel)
2677     return false;
2678
2679   // For small code model we assume that latest object is 16MB before end of 31
2680   // bits boundary. We may also accept pretty large negative constants knowing
2681   // that all objects are in the positive half of address space.
2682   if (M == CodeModel::Small && Offset < 16*1024*1024)
2683     return true;
2684
2685   // For kernel code model we know that all object resist in the negative half
2686   // of 32bits address space. We may not accept negative offsets, since they may
2687   // be just off and we may accept pretty large positive ones.
2688   if (M == CodeModel::Kernel && Offset > 0)
2689     return true;
2690
2691   return false;
2692 }
2693
2694 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2695 /// specific condition code, returning the condition code and the LHS/RHS of the
2696 /// comparison to make.
2697 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2698                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2699   if (!isFP) {
2700     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2701       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2702         // X > -1   -> X == 0, jump !sign.
2703         RHS = DAG.getConstant(0, RHS.getValueType());
2704         return X86::COND_NS;
2705       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2706         // X < 0   -> X == 0, jump on sign.
2707         return X86::COND_S;
2708       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2709         // X < 1   -> X <= 0
2710         RHS = DAG.getConstant(0, RHS.getValueType());
2711         return X86::COND_LE;
2712       }
2713     }
2714
2715     switch (SetCCOpcode) {
2716     default: llvm_unreachable("Invalid integer condition!");
2717     case ISD::SETEQ:  return X86::COND_E;
2718     case ISD::SETGT:  return X86::COND_G;
2719     case ISD::SETGE:  return X86::COND_GE;
2720     case ISD::SETLT:  return X86::COND_L;
2721     case ISD::SETLE:  return X86::COND_LE;
2722     case ISD::SETNE:  return X86::COND_NE;
2723     case ISD::SETULT: return X86::COND_B;
2724     case ISD::SETUGT: return X86::COND_A;
2725     case ISD::SETULE: return X86::COND_BE;
2726     case ISD::SETUGE: return X86::COND_AE;
2727     }
2728   }
2729
2730   // First determine if it is required or is profitable to flip the operands.
2731
2732   // If LHS is a foldable load, but RHS is not, flip the condition.
2733   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2734       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2735     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2736     std::swap(LHS, RHS);
2737   }
2738
2739   switch (SetCCOpcode) {
2740   default: break;
2741   case ISD::SETOLT:
2742   case ISD::SETOLE:
2743   case ISD::SETUGT:
2744   case ISD::SETUGE:
2745     std::swap(LHS, RHS);
2746     break;
2747   }
2748
2749   // On a floating point condition, the flags are set as follows:
2750   // ZF  PF  CF   op
2751   //  0 | 0 | 0 | X > Y
2752   //  0 | 0 | 1 | X < Y
2753   //  1 | 0 | 0 | X == Y
2754   //  1 | 1 | 1 | unordered
2755   switch (SetCCOpcode) {
2756   default: llvm_unreachable("Condcode should be pre-legalized away");
2757   case ISD::SETUEQ:
2758   case ISD::SETEQ:   return X86::COND_E;
2759   case ISD::SETOLT:              // flipped
2760   case ISD::SETOGT:
2761   case ISD::SETGT:   return X86::COND_A;
2762   case ISD::SETOLE:              // flipped
2763   case ISD::SETOGE:
2764   case ISD::SETGE:   return X86::COND_AE;
2765   case ISD::SETUGT:              // flipped
2766   case ISD::SETULT:
2767   case ISD::SETLT:   return X86::COND_B;
2768   case ISD::SETUGE:              // flipped
2769   case ISD::SETULE:
2770   case ISD::SETLE:   return X86::COND_BE;
2771   case ISD::SETONE:
2772   case ISD::SETNE:   return X86::COND_NE;
2773   case ISD::SETUO:   return X86::COND_P;
2774   case ISD::SETO:    return X86::COND_NP;
2775   case ISD::SETOEQ:
2776   case ISD::SETUNE:  return X86::COND_INVALID;
2777   }
2778 }
2779
2780 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2781 /// code. Current x86 isa includes the following FP cmov instructions:
2782 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2783 static bool hasFPCMov(unsigned X86CC) {
2784   switch (X86CC) {
2785   default:
2786     return false;
2787   case X86::COND_B:
2788   case X86::COND_BE:
2789   case X86::COND_E:
2790   case X86::COND_P:
2791   case X86::COND_A:
2792   case X86::COND_AE:
2793   case X86::COND_NE:
2794   case X86::COND_NP:
2795     return true;
2796   }
2797 }
2798
2799 /// isFPImmLegal - Returns true if the target can instruction select the
2800 /// specified FP immediate natively. If false, the legalizer will
2801 /// materialize the FP immediate as a load from a constant pool.
2802 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2803   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2804     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2805       return true;
2806   }
2807   return false;
2808 }
2809
2810 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2811 /// the specified range (L, H].
2812 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2813   return (Val < 0) || (Val >= Low && Val < Hi);
2814 }
2815
2816 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2817 /// specified value.
2818 static bool isUndefOrEqual(int Val, int CmpVal) {
2819   if (Val < 0 || Val == CmpVal)
2820     return true;
2821   return false;
2822 }
2823
2824 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2825 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2826 /// the second operand.
2827 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2828   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2829     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2830   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2831     return (Mask[0] < 2 && Mask[1] < 2);
2832   return false;
2833 }
2834
2835 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2836   SmallVector<int, 8> M;
2837   N->getMask(M);
2838   return ::isPSHUFDMask(M, N->getValueType(0));
2839 }
2840
2841 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2842 /// is suitable for input to PSHUFHW.
2843 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2844   if (VT != MVT::v8i16)
2845     return false;
2846
2847   // Lower quadword copied in order or undef.
2848   for (int i = 0; i != 4; ++i)
2849     if (Mask[i] >= 0 && Mask[i] != i)
2850       return false;
2851
2852   // Upper quadword shuffled.
2853   for (int i = 4; i != 8; ++i)
2854     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2855       return false;
2856
2857   return true;
2858 }
2859
2860 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2861   SmallVector<int, 8> M;
2862   N->getMask(M);
2863   return ::isPSHUFHWMask(M, N->getValueType(0));
2864 }
2865
2866 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2867 /// is suitable for input to PSHUFLW.
2868 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2869   if (VT != MVT::v8i16)
2870     return false;
2871
2872   // Upper quadword copied in order.
2873   for (int i = 4; i != 8; ++i)
2874     if (Mask[i] >= 0 && Mask[i] != i)
2875       return false;
2876
2877   // Lower quadword shuffled.
2878   for (int i = 0; i != 4; ++i)
2879     if (Mask[i] >= 4)
2880       return false;
2881
2882   return true;
2883 }
2884
2885 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2886   SmallVector<int, 8> M;
2887   N->getMask(M);
2888   return ::isPSHUFLWMask(M, N->getValueType(0));
2889 }
2890
2891 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2892 /// is suitable for input to PALIGNR.
2893 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2894                           bool hasSSSE3) {
2895   int i, e = VT.getVectorNumElements();
2896   
2897   // Do not handle v2i64 / v2f64 shuffles with palignr.
2898   if (e < 4 || !hasSSSE3)
2899     return false;
2900   
2901   for (i = 0; i != e; ++i)
2902     if (Mask[i] >= 0)
2903       break;
2904   
2905   // All undef, not a palignr.
2906   if (i == e)
2907     return false;
2908
2909   // Determine if it's ok to perform a palignr with only the LHS, since we
2910   // don't have access to the actual shuffle elements to see if RHS is undef.
2911   bool Unary = Mask[i] < (int)e;
2912   bool NeedsUnary = false;
2913
2914   int s = Mask[i] - i;
2915   
2916   // Check the rest of the elements to see if they are consecutive.
2917   for (++i; i != e; ++i) {
2918     int m = Mask[i];
2919     if (m < 0) 
2920       continue;
2921     
2922     Unary = Unary && (m < (int)e);
2923     NeedsUnary = NeedsUnary || (m < s);
2924
2925     if (NeedsUnary && !Unary)
2926       return false;
2927     if (Unary && m != ((s+i) & (e-1)))
2928       return false;
2929     if (!Unary && m != (s+i))
2930       return false;
2931   }
2932   return true;
2933 }
2934
2935 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2936   SmallVector<int, 8> M;
2937   N->getMask(M);
2938   return ::isPALIGNRMask(M, N->getValueType(0), true);
2939 }
2940
2941 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2942 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2943 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2944   int NumElems = VT.getVectorNumElements();
2945   if (NumElems != 2 && NumElems != 4)
2946     return false;
2947
2948   int Half = NumElems / 2;
2949   for (int i = 0; i < Half; ++i)
2950     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2951       return false;
2952   for (int i = Half; i < NumElems; ++i)
2953     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2954       return false;
2955
2956   return true;
2957 }
2958
2959 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2960   SmallVector<int, 8> M;
2961   N->getMask(M);
2962   return ::isSHUFPMask(M, N->getValueType(0));
2963 }
2964
2965 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2966 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2967 /// half elements to come from vector 1 (which would equal the dest.) and
2968 /// the upper half to come from vector 2.
2969 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2970   int NumElems = VT.getVectorNumElements();
2971
2972   if (NumElems != 2 && NumElems != 4)
2973     return false;
2974
2975   int Half = NumElems / 2;
2976   for (int i = 0; i < Half; ++i)
2977     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2978       return false;
2979   for (int i = Half; i < NumElems; ++i)
2980     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2981       return false;
2982   return true;
2983 }
2984
2985 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2986   SmallVector<int, 8> M;
2987   N->getMask(M);
2988   return isCommutedSHUFPMask(M, N->getValueType(0));
2989 }
2990
2991 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2992 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2993 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2994   if (N->getValueType(0).getVectorNumElements() != 4)
2995     return false;
2996
2997   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2998   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2999          isUndefOrEqual(N->getMaskElt(1), 7) &&
3000          isUndefOrEqual(N->getMaskElt(2), 2) &&
3001          isUndefOrEqual(N->getMaskElt(3), 3);
3002 }
3003
3004 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3005 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3006 /// <2, 3, 2, 3>
3007 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3008   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3009   
3010   if (NumElems != 4)
3011     return false;
3012   
3013   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3014   isUndefOrEqual(N->getMaskElt(1), 3) &&
3015   isUndefOrEqual(N->getMaskElt(2), 2) &&
3016   isUndefOrEqual(N->getMaskElt(3), 3);
3017 }
3018
3019 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3020 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3021 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3022   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3023
3024   if (NumElems != 2 && NumElems != 4)
3025     return false;
3026
3027   for (unsigned i = 0; i < NumElems/2; ++i)
3028     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3029       return false;
3030
3031   for (unsigned i = NumElems/2; i < NumElems; ++i)
3032     if (!isUndefOrEqual(N->getMaskElt(i), i))
3033       return false;
3034
3035   return true;
3036 }
3037
3038 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3039 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3040 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3041   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3042
3043   if (NumElems != 2 && NumElems != 4)
3044     return false;
3045
3046   for (unsigned i = 0; i < NumElems/2; ++i)
3047     if (!isUndefOrEqual(N->getMaskElt(i), i))
3048       return false;
3049
3050   for (unsigned i = 0; i < NumElems/2; ++i)
3051     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3052       return false;
3053
3054   return true;
3055 }
3056
3057 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3058 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3059 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3060                          bool V2IsSplat = false) {
3061   int NumElts = VT.getVectorNumElements();
3062   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3063     return false;
3064
3065   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3066     int BitI  = Mask[i];
3067     int BitI1 = Mask[i+1];
3068     if (!isUndefOrEqual(BitI, j))
3069       return false;
3070     if (V2IsSplat) {
3071       if (!isUndefOrEqual(BitI1, NumElts))
3072         return false;
3073     } else {
3074       if (!isUndefOrEqual(BitI1, j + NumElts))
3075         return false;
3076     }
3077   }
3078   return true;
3079 }
3080
3081 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3082   SmallVector<int, 8> M;
3083   N->getMask(M);
3084   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3085 }
3086
3087 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3088 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3089 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3090                          bool V2IsSplat = false) {
3091   int NumElts = VT.getVectorNumElements();
3092   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3093     return false;
3094
3095   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3096     int BitI  = Mask[i];
3097     int BitI1 = Mask[i+1];
3098     if (!isUndefOrEqual(BitI, j + NumElts/2))
3099       return false;
3100     if (V2IsSplat) {
3101       if (isUndefOrEqual(BitI1, NumElts))
3102         return false;
3103     } else {
3104       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3105         return false;
3106     }
3107   }
3108   return true;
3109 }
3110
3111 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3112   SmallVector<int, 8> M;
3113   N->getMask(M);
3114   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3115 }
3116
3117 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3118 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3119 /// <0, 0, 1, 1>
3120 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3121   int NumElems = VT.getVectorNumElements();
3122   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3123     return false;
3124
3125   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3126     int BitI  = Mask[i];
3127     int BitI1 = Mask[i+1];
3128     if (!isUndefOrEqual(BitI, j))
3129       return false;
3130     if (!isUndefOrEqual(BitI1, j))
3131       return false;
3132   }
3133   return true;
3134 }
3135
3136 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3137   SmallVector<int, 8> M;
3138   N->getMask(M);
3139   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3140 }
3141
3142 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3143 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3144 /// <2, 2, 3, 3>
3145 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3146   int NumElems = VT.getVectorNumElements();
3147   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3148     return false;
3149
3150   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3151     int BitI  = Mask[i];
3152     int BitI1 = Mask[i+1];
3153     if (!isUndefOrEqual(BitI, j))
3154       return false;
3155     if (!isUndefOrEqual(BitI1, j))
3156       return false;
3157   }
3158   return true;
3159 }
3160
3161 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3162   SmallVector<int, 8> M;
3163   N->getMask(M);
3164   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3165 }
3166
3167 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3168 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3169 /// MOVSD, and MOVD, i.e. setting the lowest element.
3170 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3171   if (VT.getVectorElementType().getSizeInBits() < 32)
3172     return false;
3173
3174   int NumElts = VT.getVectorNumElements();
3175
3176   if (!isUndefOrEqual(Mask[0], NumElts))
3177     return false;
3178
3179   for (int i = 1; i < NumElts; ++i)
3180     if (!isUndefOrEqual(Mask[i], i))
3181       return false;
3182
3183   return true;
3184 }
3185
3186 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3187   SmallVector<int, 8> M;
3188   N->getMask(M);
3189   return ::isMOVLMask(M, N->getValueType(0));
3190 }
3191
3192 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3193 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3194 /// element of vector 2 and the other elements to come from vector 1 in order.
3195 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3196                                bool V2IsSplat = false, bool V2IsUndef = false) {
3197   int NumOps = VT.getVectorNumElements();
3198   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3199     return false;
3200
3201   if (!isUndefOrEqual(Mask[0], 0))
3202     return false;
3203
3204   for (int i = 1; i < NumOps; ++i)
3205     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3206           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3207           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3208       return false;
3209
3210   return true;
3211 }
3212
3213 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3214                            bool V2IsUndef = false) {
3215   SmallVector<int, 8> M;
3216   N->getMask(M);
3217   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3218 }
3219
3220 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3221 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3222 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3223   if (N->getValueType(0).getVectorNumElements() != 4)
3224     return false;
3225
3226   // Expect 1, 1, 3, 3
3227   for (unsigned i = 0; i < 2; ++i) {
3228     int Elt = N->getMaskElt(i);
3229     if (Elt >= 0 && Elt != 1)
3230       return false;
3231   }
3232
3233   bool HasHi = false;
3234   for (unsigned i = 2; i < 4; ++i) {
3235     int Elt = N->getMaskElt(i);
3236     if (Elt >= 0 && Elt != 3)
3237       return false;
3238     if (Elt == 3)
3239       HasHi = true;
3240   }
3241   // Don't use movshdup if it can be done with a shufps.
3242   // FIXME: verify that matching u, u, 3, 3 is what we want.
3243   return HasHi;
3244 }
3245
3246 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3247 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3248 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3249   if (N->getValueType(0).getVectorNumElements() != 4)
3250     return false;
3251
3252   // Expect 0, 0, 2, 2
3253   for (unsigned i = 0; i < 2; ++i)
3254     if (N->getMaskElt(i) > 0)
3255       return false;
3256
3257   bool HasHi = false;
3258   for (unsigned i = 2; i < 4; ++i) {
3259     int Elt = N->getMaskElt(i);
3260     if (Elt >= 0 && Elt != 2)
3261       return false;
3262     if (Elt == 2)
3263       HasHi = true;
3264   }
3265   // Don't use movsldup if it can be done with a shufps.
3266   return HasHi;
3267 }
3268
3269 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3270 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3271 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3272   int e = N->getValueType(0).getVectorNumElements() / 2;
3273
3274   for (int i = 0; i < e; ++i)
3275     if (!isUndefOrEqual(N->getMaskElt(i), i))
3276       return false;
3277   for (int i = 0; i < e; ++i)
3278     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3279       return false;
3280   return true;
3281 }
3282
3283 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3284 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3285 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3286   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3287   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3288
3289   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3290   unsigned Mask = 0;
3291   for (int i = 0; i < NumOperands; ++i) {
3292     int Val = SVOp->getMaskElt(NumOperands-i-1);
3293     if (Val < 0) Val = 0;
3294     if (Val >= NumOperands) Val -= NumOperands;
3295     Mask |= Val;
3296     if (i != NumOperands - 1)
3297       Mask <<= Shift;
3298   }
3299   return Mask;
3300 }
3301
3302 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3303 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3304 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3305   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3306   unsigned Mask = 0;
3307   // 8 nodes, but we only care about the last 4.
3308   for (unsigned i = 7; i >= 4; --i) {
3309     int Val = SVOp->getMaskElt(i);
3310     if (Val >= 0)
3311       Mask |= (Val - 4);
3312     if (i != 4)
3313       Mask <<= 2;
3314   }
3315   return Mask;
3316 }
3317
3318 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3319 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3320 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3321   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3322   unsigned Mask = 0;
3323   // 8 nodes, but we only care about the first 4.
3324   for (int i = 3; i >= 0; --i) {
3325     int Val = SVOp->getMaskElt(i);
3326     if (Val >= 0)
3327       Mask |= Val;
3328     if (i != 0)
3329       Mask <<= 2;
3330   }
3331   return Mask;
3332 }
3333
3334 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3335 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3336 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3337   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3338   EVT VVT = N->getValueType(0);
3339   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3340   int Val = 0;
3341
3342   unsigned i, e;
3343   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3344     Val = SVOp->getMaskElt(i);
3345     if (Val >= 0)
3346       break;
3347   }
3348   return (Val - i) * EltSize;
3349 }
3350
3351 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3352 /// constant +0.0.
3353 bool X86::isZeroNode(SDValue Elt) {
3354   return ((isa<ConstantSDNode>(Elt) &&
3355            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3356           (isa<ConstantFPSDNode>(Elt) &&
3357            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3358 }
3359
3360 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3361 /// their permute mask.
3362 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3363                                     SelectionDAG &DAG) {
3364   EVT VT = SVOp->getValueType(0);
3365   unsigned NumElems = VT.getVectorNumElements();
3366   SmallVector<int, 8> MaskVec;
3367
3368   for (unsigned i = 0; i != NumElems; ++i) {
3369     int idx = SVOp->getMaskElt(i);
3370     if (idx < 0)
3371       MaskVec.push_back(idx);
3372     else if (idx < (int)NumElems)
3373       MaskVec.push_back(idx + NumElems);
3374     else
3375       MaskVec.push_back(idx - NumElems);
3376   }
3377   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3378                               SVOp->getOperand(0), &MaskVec[0]);
3379 }
3380
3381 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3382 /// the two vector operands have swapped position.
3383 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3384   unsigned NumElems = VT.getVectorNumElements();
3385   for (unsigned i = 0; i != NumElems; ++i) {
3386     int idx = Mask[i];
3387     if (idx < 0)
3388       continue;
3389     else if (idx < (int)NumElems)
3390       Mask[i] = idx + NumElems;
3391     else
3392       Mask[i] = idx - NumElems;
3393   }
3394 }
3395
3396 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3397 /// match movhlps. The lower half elements should come from upper half of
3398 /// V1 (and in order), and the upper half elements should come from the upper
3399 /// half of V2 (and in order).
3400 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3401   if (Op->getValueType(0).getVectorNumElements() != 4)
3402     return false;
3403   for (unsigned i = 0, e = 2; i != e; ++i)
3404     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3405       return false;
3406   for (unsigned i = 2; i != 4; ++i)
3407     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3408       return false;
3409   return true;
3410 }
3411
3412 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3413 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3414 /// required.
3415 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3416   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3417     return false;
3418   N = N->getOperand(0).getNode();
3419   if (!ISD::isNON_EXTLoad(N))
3420     return false;
3421   if (LD)
3422     *LD = cast<LoadSDNode>(N);
3423   return true;
3424 }
3425
3426 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3427 /// match movlp{s|d}. The lower half elements should come from lower half of
3428 /// V1 (and in order), and the upper half elements should come from the upper
3429 /// half of V2 (and in order). And since V1 will become the source of the
3430 /// MOVLP, it must be either a vector load or a scalar load to vector.
3431 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3432                                ShuffleVectorSDNode *Op) {
3433   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3434     return false;
3435   // Is V2 is a vector load, don't do this transformation. We will try to use
3436   // load folding shufps op.
3437   if (ISD::isNON_EXTLoad(V2))
3438     return false;
3439
3440   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3441
3442   if (NumElems != 2 && NumElems != 4)
3443     return false;
3444   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3445     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3446       return false;
3447   for (unsigned i = NumElems/2; i != NumElems; ++i)
3448     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3449       return false;
3450   return true;
3451 }
3452
3453 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3454 /// all the same.
3455 static bool isSplatVector(SDNode *N) {
3456   if (N->getOpcode() != ISD::BUILD_VECTOR)
3457     return false;
3458
3459   SDValue SplatValue = N->getOperand(0);
3460   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3461     if (N->getOperand(i) != SplatValue)
3462       return false;
3463   return true;
3464 }
3465
3466 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3467 /// to an zero vector.
3468 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3469 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3470   SDValue V1 = N->getOperand(0);
3471   SDValue V2 = N->getOperand(1);
3472   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3473   for (unsigned i = 0; i != NumElems; ++i) {
3474     int Idx = N->getMaskElt(i);
3475     if (Idx >= (int)NumElems) {
3476       unsigned Opc = V2.getOpcode();
3477       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3478         continue;
3479       if (Opc != ISD::BUILD_VECTOR ||
3480           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3481         return false;
3482     } else if (Idx >= 0) {
3483       unsigned Opc = V1.getOpcode();
3484       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3485         continue;
3486       if (Opc != ISD::BUILD_VECTOR ||
3487           !X86::isZeroNode(V1.getOperand(Idx)))
3488         return false;
3489     }
3490   }
3491   return true;
3492 }
3493
3494 /// getZeroVector - Returns a vector of specified type with all zero elements.
3495 ///
3496 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3497                              DebugLoc dl) {
3498   assert(VT.isVector() && "Expected a vector type");
3499
3500   // Always build SSE zero vectors as <4 x i32> bitcasted
3501   // to their dest type. This ensures they get CSE'd.
3502   SDValue Vec;
3503   if (VT.getSizeInBits() == 128) {  // SSE
3504     if (HasSSE2) {  // SSE2
3505       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3506       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3507     } else { // SSE1
3508       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3509       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3510     }
3511   } else if (VT.getSizeInBits() == 256) { // AVX
3512     // 256-bit logic and arithmetic instructions in AVX are
3513     // all floating-point, no support for integer ops. Default
3514     // to emitting fp zeroed vectors then.
3515     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3516     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3517     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3518   }
3519   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3520 }
3521
3522 /// getOnesVector - Returns a vector of specified type with all bits set.
3523 ///
3524 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3525   assert(VT.isVector() && "Expected a vector type");
3526
3527   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3528   // type.  This ensures they get CSE'd.
3529   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3530   SDValue Vec;
3531   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3532   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3533 }
3534
3535
3536 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3537 /// that point to V2 points to its first element.
3538 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3539   EVT VT = SVOp->getValueType(0);
3540   unsigned NumElems = VT.getVectorNumElements();
3541
3542   bool Changed = false;
3543   SmallVector<int, 8> MaskVec;
3544   SVOp->getMask(MaskVec);
3545
3546   for (unsigned i = 0; i != NumElems; ++i) {
3547     if (MaskVec[i] > (int)NumElems) {
3548       MaskVec[i] = NumElems;
3549       Changed = true;
3550     }
3551   }
3552   if (Changed)
3553     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3554                                 SVOp->getOperand(1), &MaskVec[0]);
3555   return SDValue(SVOp, 0);
3556 }
3557
3558 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3559 /// operation of specified width.
3560 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3561                        SDValue V2) {
3562   unsigned NumElems = VT.getVectorNumElements();
3563   SmallVector<int, 8> Mask;
3564   Mask.push_back(NumElems);
3565   for (unsigned i = 1; i != NumElems; ++i)
3566     Mask.push_back(i);
3567   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3568 }
3569
3570 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3571 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3572                           SDValue V2) {
3573   unsigned NumElems = VT.getVectorNumElements();
3574   SmallVector<int, 8> Mask;
3575   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3576     Mask.push_back(i);
3577     Mask.push_back(i + NumElems);
3578   }
3579   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3580 }
3581
3582 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3583 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3584                           SDValue V2) {
3585   unsigned NumElems = VT.getVectorNumElements();
3586   unsigned Half = NumElems/2;
3587   SmallVector<int, 8> Mask;
3588   for (unsigned i = 0; i != Half; ++i) {
3589     Mask.push_back(i + Half);
3590     Mask.push_back(i + NumElems + Half);
3591   }
3592   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3593 }
3594
3595 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3596 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3597   EVT PVT = MVT::v4f32;
3598   EVT VT = SV->getValueType(0);
3599   DebugLoc dl = SV->getDebugLoc();
3600   SDValue V1 = SV->getOperand(0);
3601   int NumElems = VT.getVectorNumElements();
3602   int EltNo = SV->getSplatIndex();
3603
3604   // unpack elements to the correct location
3605   while (NumElems > 4) {
3606     if (EltNo < NumElems/2) {
3607       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3608     } else {
3609       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3610       EltNo -= NumElems/2;
3611     }
3612     NumElems >>= 1;
3613   }
3614
3615   // Perform the splat.
3616   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3617   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3618   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3619   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3620 }
3621
3622 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3623 /// vector of zero or undef vector.  This produces a shuffle where the low
3624 /// element of V2 is swizzled into the zero/undef vector, landing at element
3625 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3626 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3627                                              bool isZero, bool HasSSE2,
3628                                              SelectionDAG &DAG) {
3629   EVT VT = V2.getValueType();
3630   SDValue V1 = isZero
3631     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3632   unsigned NumElems = VT.getVectorNumElements();
3633   SmallVector<int, 16> MaskVec;
3634   for (unsigned i = 0; i != NumElems; ++i)
3635     // If this is the insertion idx, put the low elt of V2 here.
3636     MaskVec.push_back(i == Idx ? NumElems : i);
3637   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3638 }
3639
3640 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3641 /// element of the result of the vector shuffle.
3642 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3643                             unsigned Depth) {
3644   if (Depth == 6)
3645     return SDValue();  // Limit search depth.
3646
3647   SDValue V = SDValue(N, 0);
3648   EVT VT = V.getValueType();
3649   unsigned Opcode = V.getOpcode();
3650
3651   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3652   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3653     Index = SV->getMaskElt(Index);
3654
3655     if (Index < 0)
3656       return DAG.getUNDEF(VT.getVectorElementType());
3657
3658     int NumElems = VT.getVectorNumElements();
3659     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3660     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3661   }
3662
3663   // Recurse into target specific vector shuffles to find scalars.
3664   if (isTargetShuffle(Opcode)) {
3665     int NumElems = VT.getVectorNumElements();
3666     SmallVector<unsigned, 16> ShuffleMask;
3667     SDValue ImmN;
3668
3669     switch(Opcode) {
3670     case X86ISD::SHUFPS:
3671     case X86ISD::SHUFPD:
3672       ImmN = N->getOperand(N->getNumOperands()-1);
3673       DecodeSHUFPSMask(NumElems,
3674                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3675                        ShuffleMask);
3676       break;
3677     case X86ISD::PUNPCKHBW:
3678     case X86ISD::PUNPCKHWD:
3679     case X86ISD::PUNPCKHDQ:
3680     case X86ISD::PUNPCKHQDQ:
3681       DecodePUNPCKHMask(NumElems, ShuffleMask);
3682       break;
3683     case X86ISD::UNPCKHPS:
3684     case X86ISD::UNPCKHPD:
3685       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3686       break;
3687     case X86ISD::PUNPCKLBW:
3688     case X86ISD::PUNPCKLWD:
3689     case X86ISD::PUNPCKLDQ:
3690     case X86ISD::PUNPCKLQDQ:
3691       DecodePUNPCKLMask(NumElems, ShuffleMask);
3692       break;
3693     case X86ISD::UNPCKLPS:
3694     case X86ISD::UNPCKLPD:
3695       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3696       break;
3697     case X86ISD::MOVHLPS:
3698       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3699       break;
3700     case X86ISD::MOVLHPS:
3701       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3702       break;
3703     case X86ISD::PSHUFD:
3704       ImmN = N->getOperand(N->getNumOperands()-1);
3705       DecodePSHUFMask(NumElems,
3706                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3707                       ShuffleMask);
3708       break;
3709     case X86ISD::PSHUFHW:
3710       ImmN = N->getOperand(N->getNumOperands()-1);
3711       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3712                         ShuffleMask);
3713       break;
3714     case X86ISD::PSHUFLW:
3715       ImmN = N->getOperand(N->getNumOperands()-1);
3716       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3717                         ShuffleMask);
3718       break;
3719     case X86ISD::MOVSS:
3720     case X86ISD::MOVSD: {
3721       // The index 0 always comes from the first element of the second source,
3722       // this is why MOVSS and MOVSD are used in the first place. The other
3723       // elements come from the other positions of the first source vector.
3724       unsigned OpNum = (Index == 0) ? 1 : 0;
3725       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3726                                  Depth+1);
3727     }
3728     default:
3729       assert("not implemented for target shuffle node");
3730       return SDValue();
3731     }
3732
3733     Index = ShuffleMask[Index];
3734     if (Index < 0)
3735       return DAG.getUNDEF(VT.getVectorElementType());
3736
3737     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3738     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3739                                Depth+1);
3740   }
3741
3742   // Actual nodes that may contain scalar elements
3743   if (Opcode == ISD::BIT_CONVERT) {
3744     V = V.getOperand(0);
3745     EVT SrcVT = V.getValueType();
3746     unsigned NumElems = VT.getVectorNumElements();
3747
3748     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3749       return SDValue();
3750   }
3751
3752   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3753     return (Index == 0) ? V.getOperand(0)
3754                           : DAG.getUNDEF(VT.getVectorElementType());
3755
3756   if (V.getOpcode() == ISD::BUILD_VECTOR)
3757     return V.getOperand(Index);
3758
3759   return SDValue();
3760 }
3761
3762 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3763 /// shuffle operation which come from a consecutively from a zero. The
3764 /// search can start in two diferent directions, from left or right.
3765 static
3766 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3767                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3768   int i = 0;
3769
3770   while (i < NumElems) {
3771     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3772     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3773     if (!(Elt.getNode() &&
3774          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3775       break;
3776     ++i;
3777   }
3778
3779   return i;
3780 }
3781
3782 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3783 /// MaskE correspond consecutively to elements from one of the vector operands,
3784 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3785 static
3786 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3787                               int OpIdx, int NumElems, unsigned &OpNum) {
3788   bool SeenV1 = false;
3789   bool SeenV2 = false;
3790
3791   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3792     int Idx = SVOp->getMaskElt(i);
3793     // Ignore undef indicies
3794     if (Idx < 0)
3795       continue;
3796
3797     if (Idx < NumElems)
3798       SeenV1 = true;
3799     else
3800       SeenV2 = true;
3801
3802     // Only accept consecutive elements from the same vector
3803     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3804       return false;
3805   }
3806
3807   OpNum = SeenV1 ? 0 : 1;
3808   return true;
3809 }
3810
3811 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3812 /// logical left shift of a vector.
3813 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3814                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3815   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3816   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3817               false /* check zeros from right */, DAG);
3818   unsigned OpSrc;
3819
3820   if (!NumZeros)
3821     return false;
3822
3823   // Considering the elements in the mask that are not consecutive zeros,
3824   // check if they consecutively come from only one of the source vectors.
3825   //
3826   //               V1 = {X, A, B, C}     0
3827   //                         \  \  \    /
3828   //   vector_shuffle V1, V2 <1, 2, 3, X>
3829   //
3830   if (!isShuffleMaskConsecutive(SVOp,
3831             0,                   // Mask Start Index
3832             NumElems-NumZeros-1, // Mask End Index
3833             NumZeros,            // Where to start looking in the src vector
3834             NumElems,            // Number of elements in vector
3835             OpSrc))              // Which source operand ?
3836     return false;
3837
3838   isLeft = false;
3839   ShAmt = NumZeros;
3840   ShVal = SVOp->getOperand(OpSrc);
3841   return true;
3842 }
3843
3844 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3845 /// logical left shift of a vector.
3846 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3847                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3848   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3849   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3850               true /* check zeros from left */, DAG);
3851   unsigned OpSrc;
3852
3853   if (!NumZeros)
3854     return false;
3855
3856   // Considering the elements in the mask that are not consecutive zeros,
3857   // check if they consecutively come from only one of the source vectors.
3858   //
3859   //                           0    { A, B, X, X } = V2
3860   //                          / \    /  /
3861   //   vector_shuffle V1, V2 <X, X, 4, 5>
3862   //
3863   if (!isShuffleMaskConsecutive(SVOp,
3864             NumZeros,     // Mask Start Index
3865             NumElems-1,   // Mask End Index
3866             0,            // Where to start looking in the src vector
3867             NumElems,     // Number of elements in vector
3868             OpSrc))       // Which source operand ?
3869     return false;
3870
3871   isLeft = true;
3872   ShAmt = NumZeros;
3873   ShVal = SVOp->getOperand(OpSrc);
3874   return true;
3875 }
3876
3877 /// isVectorShift - Returns true if the shuffle can be implemented as a
3878 /// logical left or right shift of a vector.
3879 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3880                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3881   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3882       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3883     return true;
3884
3885   return false;
3886 }
3887
3888 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3889 ///
3890 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3891                                        unsigned NumNonZero, unsigned NumZero,
3892                                        SelectionDAG &DAG,
3893                                        const TargetLowering &TLI) {
3894   if (NumNonZero > 8)
3895     return SDValue();
3896
3897   DebugLoc dl = Op.getDebugLoc();
3898   SDValue V(0, 0);
3899   bool First = true;
3900   for (unsigned i = 0; i < 16; ++i) {
3901     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3902     if (ThisIsNonZero && First) {
3903       if (NumZero)
3904         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3905       else
3906         V = DAG.getUNDEF(MVT::v8i16);
3907       First = false;
3908     }
3909
3910     if ((i & 1) != 0) {
3911       SDValue ThisElt(0, 0), LastElt(0, 0);
3912       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3913       if (LastIsNonZero) {
3914         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3915                               MVT::i16, Op.getOperand(i-1));
3916       }
3917       if (ThisIsNonZero) {
3918         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3919         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3920                               ThisElt, DAG.getConstant(8, MVT::i8));
3921         if (LastIsNonZero)
3922           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3923       } else
3924         ThisElt = LastElt;
3925
3926       if (ThisElt.getNode())
3927         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3928                         DAG.getIntPtrConstant(i/2));
3929     }
3930   }
3931
3932   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3933 }
3934
3935 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3936 ///
3937 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3938                                      unsigned NumNonZero, unsigned NumZero,
3939                                      SelectionDAG &DAG,
3940                                      const TargetLowering &TLI) {
3941   if (NumNonZero > 4)
3942     return SDValue();
3943
3944   DebugLoc dl = Op.getDebugLoc();
3945   SDValue V(0, 0);
3946   bool First = true;
3947   for (unsigned i = 0; i < 8; ++i) {
3948     bool isNonZero = (NonZeros & (1 << i)) != 0;
3949     if (isNonZero) {
3950       if (First) {
3951         if (NumZero)
3952           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3953         else
3954           V = DAG.getUNDEF(MVT::v8i16);
3955         First = false;
3956       }
3957       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3958                       MVT::v8i16, V, Op.getOperand(i),
3959                       DAG.getIntPtrConstant(i));
3960     }
3961   }
3962
3963   return V;
3964 }
3965
3966 /// getVShift - Return a vector logical shift node.
3967 ///
3968 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3969                          unsigned NumBits, SelectionDAG &DAG,
3970                          const TargetLowering &TLI, DebugLoc dl) {
3971   EVT ShVT = MVT::v2i64;
3972   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3973   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3974   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3975                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3976                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3977 }
3978
3979 SDValue
3980 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3981                                           SelectionDAG &DAG) const {
3982   
3983   // Check if the scalar load can be widened into a vector load. And if
3984   // the address is "base + cst" see if the cst can be "absorbed" into
3985   // the shuffle mask.
3986   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3987     SDValue Ptr = LD->getBasePtr();
3988     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3989       return SDValue();
3990     EVT PVT = LD->getValueType(0);
3991     if (PVT != MVT::i32 && PVT != MVT::f32)
3992       return SDValue();
3993
3994     int FI = -1;
3995     int64_t Offset = 0;
3996     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3997       FI = FINode->getIndex();
3998       Offset = 0;
3999     } else if (Ptr.getOpcode() == ISD::ADD &&
4000                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4001                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4002       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4003       Offset = Ptr.getConstantOperandVal(1);
4004       Ptr = Ptr.getOperand(0);
4005     } else {
4006       return SDValue();
4007     }
4008
4009     SDValue Chain = LD->getChain();
4010     // Make sure the stack object alignment is at least 16.
4011     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4012     if (DAG.InferPtrAlignment(Ptr) < 16) {
4013       if (MFI->isFixedObjectIndex(FI)) {
4014         // Can't change the alignment. FIXME: It's possible to compute
4015         // the exact stack offset and reference FI + adjust offset instead.
4016         // If someone *really* cares about this. That's the way to implement it.
4017         return SDValue();
4018       } else {
4019         MFI->setObjectAlignment(FI, 16);
4020       }
4021     }
4022
4023     // (Offset % 16) must be multiple of 4. Then address is then
4024     // Ptr + (Offset & ~15).
4025     if (Offset < 0)
4026       return SDValue();
4027     if ((Offset % 16) & 3)
4028       return SDValue();
4029     int64_t StartOffset = Offset & ~15;
4030     if (StartOffset)
4031       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4032                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4033
4034     int EltNo = (Offset - StartOffset) >> 2;
4035     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4036     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4037     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4038                              LD->getPointerInfo().getWithOffset(StartOffset),
4039                              false, false, 0);
4040     // Canonicalize it to a v4i32 shuffle.
4041     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4042     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4043                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4044                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4045   }
4046
4047   return SDValue();
4048 }
4049
4050 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
4051 /// vector of type 'VT', see if the elements can be replaced by a single large 
4052 /// load which has the same value as a build_vector whose operands are 'elts'.
4053 ///
4054 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4055 /// 
4056 /// FIXME: we'd also like to handle the case where the last elements are zero
4057 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4058 /// There's even a handy isZeroNode for that purpose.
4059 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4060                                         DebugLoc &DL, SelectionDAG &DAG) {
4061   EVT EltVT = VT.getVectorElementType();
4062   unsigned NumElems = Elts.size();
4063   
4064   LoadSDNode *LDBase = NULL;
4065   unsigned LastLoadedElt = -1U;
4066   
4067   // For each element in the initializer, see if we've found a load or an undef.
4068   // If we don't find an initial load element, or later load elements are 
4069   // non-consecutive, bail out.
4070   for (unsigned i = 0; i < NumElems; ++i) {
4071     SDValue Elt = Elts[i];
4072     
4073     if (!Elt.getNode() ||
4074         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4075       return SDValue();
4076     if (!LDBase) {
4077       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4078         return SDValue();
4079       LDBase = cast<LoadSDNode>(Elt.getNode());
4080       LastLoadedElt = i;
4081       continue;
4082     }
4083     if (Elt.getOpcode() == ISD::UNDEF)
4084       continue;
4085
4086     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4087     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4088       return SDValue();
4089     LastLoadedElt = i;
4090   }
4091
4092   // If we have found an entire vector of loads and undefs, then return a large
4093   // load of the entire vector width starting at the base pointer.  If we found
4094   // consecutive loads for the low half, generate a vzext_load node.
4095   if (LastLoadedElt == NumElems - 1) {
4096     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4097       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4098                          LDBase->getPointerInfo(),
4099                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4100     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4101                        LDBase->getPointerInfo(),
4102                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4103                        LDBase->getAlignment());
4104   } else if (NumElems == 4 && LastLoadedElt == 1) {
4105     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4106     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4107     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4108                                               Ops, 2, MVT::i32,
4109                                               LDBase->getMemOperand());
4110     return DAG.getNode(ISD::BIT_CONVERT, DL, VT, ResNode);
4111   }
4112   return SDValue();
4113 }
4114
4115 SDValue
4116 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4117   DebugLoc dl = Op.getDebugLoc();
4118   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4119   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4120   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4121   // is present, so AllOnes is ignored.
4122   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4123       (Op.getValueType().getSizeInBits() != 256 &&
4124        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4125     // Canonicalize this to <4 x i32> (SSE) to
4126     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4127     // eliminated on x86-32 hosts.
4128     if (Op.getValueType() == MVT::v4i32)
4129       return Op;
4130
4131     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4132       return getOnesVector(Op.getValueType(), DAG, dl);
4133     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4134   }
4135
4136   EVT VT = Op.getValueType();
4137   EVT ExtVT = VT.getVectorElementType();
4138   unsigned EVTBits = ExtVT.getSizeInBits();
4139
4140   unsigned NumElems = Op.getNumOperands();
4141   unsigned NumZero  = 0;
4142   unsigned NumNonZero = 0;
4143   unsigned NonZeros = 0;
4144   bool IsAllConstants = true;
4145   SmallSet<SDValue, 8> Values;
4146   for (unsigned i = 0; i < NumElems; ++i) {
4147     SDValue Elt = Op.getOperand(i);
4148     if (Elt.getOpcode() == ISD::UNDEF)
4149       continue;
4150     Values.insert(Elt);
4151     if (Elt.getOpcode() != ISD::Constant &&
4152         Elt.getOpcode() != ISD::ConstantFP)
4153       IsAllConstants = false;
4154     if (X86::isZeroNode(Elt))
4155       NumZero++;
4156     else {
4157       NonZeros |= (1 << i);
4158       NumNonZero++;
4159     }
4160   }
4161
4162   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4163   if (NumNonZero == 0)
4164     return DAG.getUNDEF(VT);
4165
4166   // Special case for single non-zero, non-undef, element.
4167   if (NumNonZero == 1) {
4168     unsigned Idx = CountTrailingZeros_32(NonZeros);
4169     SDValue Item = Op.getOperand(Idx);
4170
4171     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4172     // the value are obviously zero, truncate the value to i32 and do the
4173     // insertion that way.  Only do this if the value is non-constant or if the
4174     // value is a constant being inserted into element 0.  It is cheaper to do
4175     // a constant pool load than it is to do a movd + shuffle.
4176     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4177         (!IsAllConstants || Idx == 0)) {
4178       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4179         // Handle SSE only.
4180         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4181         EVT VecVT = MVT::v4i32;
4182         unsigned VecElts = 4;
4183
4184         // Truncate the value (which may itself be a constant) to i32, and
4185         // convert it to a vector with movd (S2V+shuffle to zero extend).
4186         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4187         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4188         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4189                                            Subtarget->hasSSE2(), DAG);
4190
4191         // Now we have our 32-bit value zero extended in the low element of
4192         // a vector.  If Idx != 0, swizzle it into place.
4193         if (Idx != 0) {
4194           SmallVector<int, 4> Mask;
4195           Mask.push_back(Idx);
4196           for (unsigned i = 1; i != VecElts; ++i)
4197             Mask.push_back(i);
4198           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4199                                       DAG.getUNDEF(Item.getValueType()),
4200                                       &Mask[0]);
4201         }
4202         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4203       }
4204     }
4205
4206     // If we have a constant or non-constant insertion into the low element of
4207     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4208     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4209     // depending on what the source datatype is.
4210     if (Idx == 0) {
4211       if (NumZero == 0) {
4212         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4213       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4214           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4215         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4216         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4217         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4218                                            DAG);
4219       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4220         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4221         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4222         EVT MiddleVT = MVT::v4i32;
4223         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4224         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4225                                            Subtarget->hasSSE2(), DAG);
4226         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4227       }
4228     }
4229
4230     // Is it a vector logical left shift?
4231     if (NumElems == 2 && Idx == 1 &&
4232         X86::isZeroNode(Op.getOperand(0)) &&
4233         !X86::isZeroNode(Op.getOperand(1))) {
4234       unsigned NumBits = VT.getSizeInBits();
4235       return getVShift(true, VT,
4236                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4237                                    VT, Op.getOperand(1)),
4238                        NumBits/2, DAG, *this, dl);
4239     }
4240
4241     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4242       return SDValue();
4243
4244     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4245     // is a non-constant being inserted into an element other than the low one,
4246     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4247     // movd/movss) to move this into the low element, then shuffle it into
4248     // place.
4249     if (EVTBits == 32) {
4250       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4251
4252       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4253       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4254                                          Subtarget->hasSSE2(), DAG);
4255       SmallVector<int, 8> MaskVec;
4256       for (unsigned i = 0; i < NumElems; i++)
4257         MaskVec.push_back(i == Idx ? 0 : 1);
4258       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4259     }
4260   }
4261
4262   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4263   if (Values.size() == 1) {
4264     if (EVTBits == 32) {
4265       // Instead of a shuffle like this:
4266       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4267       // Check if it's possible to issue this instead.
4268       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4269       unsigned Idx = CountTrailingZeros_32(NonZeros);
4270       SDValue Item = Op.getOperand(Idx);
4271       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4272         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4273     }
4274     return SDValue();
4275   }
4276
4277   // A vector full of immediates; various special cases are already
4278   // handled, so this is best done with a single constant-pool load.
4279   if (IsAllConstants)
4280     return SDValue();
4281
4282   // Let legalizer expand 2-wide build_vectors.
4283   if (EVTBits == 64) {
4284     if (NumNonZero == 1) {
4285       // One half is zero or undef.
4286       unsigned Idx = CountTrailingZeros_32(NonZeros);
4287       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4288                                  Op.getOperand(Idx));
4289       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4290                                          Subtarget->hasSSE2(), DAG);
4291     }
4292     return SDValue();
4293   }
4294
4295   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4296   if (EVTBits == 8 && NumElems == 16) {
4297     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4298                                         *this);
4299     if (V.getNode()) return V;
4300   }
4301
4302   if (EVTBits == 16 && NumElems == 8) {
4303     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4304                                       *this);
4305     if (V.getNode()) return V;
4306   }
4307
4308   // If element VT is == 32 bits, turn it into a number of shuffles.
4309   SmallVector<SDValue, 8> V;
4310   V.resize(NumElems);
4311   if (NumElems == 4 && NumZero > 0) {
4312     for (unsigned i = 0; i < 4; ++i) {
4313       bool isZero = !(NonZeros & (1 << i));
4314       if (isZero)
4315         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4316       else
4317         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4318     }
4319
4320     for (unsigned i = 0; i < 2; ++i) {
4321       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4322         default: break;
4323         case 0:
4324           V[i] = V[i*2];  // Must be a zero vector.
4325           break;
4326         case 1:
4327           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4328           break;
4329         case 2:
4330           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4331           break;
4332         case 3:
4333           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4334           break;
4335       }
4336     }
4337
4338     SmallVector<int, 8> MaskVec;
4339     bool Reverse = (NonZeros & 0x3) == 2;
4340     for (unsigned i = 0; i < 2; ++i)
4341       MaskVec.push_back(Reverse ? 1-i : i);
4342     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4343     for (unsigned i = 0; i < 2; ++i)
4344       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4345     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4346   }
4347
4348   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4349     // Check for a build vector of consecutive loads.
4350     for (unsigned i = 0; i < NumElems; ++i)
4351       V[i] = Op.getOperand(i);
4352     
4353     // Check for elements which are consecutive loads.
4354     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4355     if (LD.getNode())
4356       return LD;
4357     
4358     // For SSE 4.1, use insertps to put the high elements into the low element. 
4359     if (getSubtarget()->hasSSE41()) {
4360       SDValue Result;
4361       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4362         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4363       else
4364         Result = DAG.getUNDEF(VT);
4365       
4366       for (unsigned i = 1; i < NumElems; ++i) {
4367         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4368         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4369                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4370       }
4371       return Result;
4372     }
4373     
4374     // Otherwise, expand into a number of unpckl*, start by extending each of
4375     // our (non-undef) elements to the full vector width with the element in the
4376     // bottom slot of the vector (which generates no code for SSE).
4377     for (unsigned i = 0; i < NumElems; ++i) {
4378       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4379         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4380       else
4381         V[i] = DAG.getUNDEF(VT);
4382     }
4383
4384     // Next, we iteratively mix elements, e.g. for v4f32:
4385     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4386     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4387     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4388     unsigned EltStride = NumElems >> 1;
4389     while (EltStride != 0) {
4390       for (unsigned i = 0; i < EltStride; ++i) {
4391         // If V[i+EltStride] is undef and this is the first round of mixing,
4392         // then it is safe to just drop this shuffle: V[i] is already in the
4393         // right place, the one element (since it's the first round) being
4394         // inserted as undef can be dropped.  This isn't safe for successive
4395         // rounds because they will permute elements within both vectors.
4396         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4397             EltStride == NumElems/2)
4398           continue;
4399         
4400         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4401       }
4402       EltStride >>= 1;
4403     }
4404     return V[0];
4405   }
4406   return SDValue();
4407 }
4408
4409 SDValue
4410 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4411   // We support concatenate two MMX registers and place them in a MMX
4412   // register.  This is better than doing a stack convert.
4413   DebugLoc dl = Op.getDebugLoc();
4414   EVT ResVT = Op.getValueType();
4415   assert(Op.getNumOperands() == 2);
4416   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4417          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4418   int Mask[2];
4419   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4420   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4421   InVec = Op.getOperand(1);
4422   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4423     unsigned NumElts = ResVT.getVectorNumElements();
4424     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4425     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4426                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4427   } else {
4428     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4429     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4430     Mask[0] = 0; Mask[1] = 2;
4431     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4432   }
4433   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4434 }
4435
4436 // v8i16 shuffles - Prefer shuffles in the following order:
4437 // 1. [all]   pshuflw, pshufhw, optional move
4438 // 2. [ssse3] 1 x pshufb
4439 // 3. [ssse3] 2 x pshufb + 1 x por
4440 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4441 SDValue
4442 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4443                                             SelectionDAG &DAG) const {
4444   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4445   SDValue V1 = SVOp->getOperand(0);
4446   SDValue V2 = SVOp->getOperand(1);
4447   DebugLoc dl = SVOp->getDebugLoc();
4448   SmallVector<int, 8> MaskVals;
4449
4450   // Determine if more than 1 of the words in each of the low and high quadwords
4451   // of the result come from the same quadword of one of the two inputs.  Undef
4452   // mask values count as coming from any quadword, for better codegen.
4453   SmallVector<unsigned, 4> LoQuad(4);
4454   SmallVector<unsigned, 4> HiQuad(4);
4455   BitVector InputQuads(4);
4456   for (unsigned i = 0; i < 8; ++i) {
4457     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4458     int EltIdx = SVOp->getMaskElt(i);
4459     MaskVals.push_back(EltIdx);
4460     if (EltIdx < 0) {
4461       ++Quad[0];
4462       ++Quad[1];
4463       ++Quad[2];
4464       ++Quad[3];
4465       continue;
4466     }
4467     ++Quad[EltIdx / 4];
4468     InputQuads.set(EltIdx / 4);
4469   }
4470
4471   int BestLoQuad = -1;
4472   unsigned MaxQuad = 1;
4473   for (unsigned i = 0; i < 4; ++i) {
4474     if (LoQuad[i] > MaxQuad) {
4475       BestLoQuad = i;
4476       MaxQuad = LoQuad[i];
4477     }
4478   }
4479
4480   int BestHiQuad = -1;
4481   MaxQuad = 1;
4482   for (unsigned i = 0; i < 4; ++i) {
4483     if (HiQuad[i] > MaxQuad) {
4484       BestHiQuad = i;
4485       MaxQuad = HiQuad[i];
4486     }
4487   }
4488
4489   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4490   // of the two input vectors, shuffle them into one input vector so only a
4491   // single pshufb instruction is necessary. If There are more than 2 input
4492   // quads, disable the next transformation since it does not help SSSE3.
4493   bool V1Used = InputQuads[0] || InputQuads[1];
4494   bool V2Used = InputQuads[2] || InputQuads[3];
4495   if (Subtarget->hasSSSE3()) {
4496     if (InputQuads.count() == 2 && V1Used && V2Used) {
4497       BestLoQuad = InputQuads.find_first();
4498       BestHiQuad = InputQuads.find_next(BestLoQuad);
4499     }
4500     if (InputQuads.count() > 2) {
4501       BestLoQuad = -1;
4502       BestHiQuad = -1;
4503     }
4504   }
4505
4506   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4507   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4508   // words from all 4 input quadwords.
4509   SDValue NewV;
4510   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4511     SmallVector<int, 8> MaskV;
4512     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4513     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4514     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4515                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4516                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4517     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4518
4519     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4520     // source words for the shuffle, to aid later transformations.
4521     bool AllWordsInNewV = true;
4522     bool InOrder[2] = { true, true };
4523     for (unsigned i = 0; i != 8; ++i) {
4524       int idx = MaskVals[i];
4525       if (idx != (int)i)
4526         InOrder[i/4] = false;
4527       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4528         continue;
4529       AllWordsInNewV = false;
4530       break;
4531     }
4532
4533     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4534     if (AllWordsInNewV) {
4535       for (int i = 0; i != 8; ++i) {
4536         int idx = MaskVals[i];
4537         if (idx < 0)
4538           continue;
4539         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4540         if ((idx != i) && idx < 4)
4541           pshufhw = false;
4542         if ((idx != i) && idx > 3)
4543           pshuflw = false;
4544       }
4545       V1 = NewV;
4546       V2Used = false;
4547       BestLoQuad = 0;
4548       BestHiQuad = 1;
4549     }
4550
4551     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4552     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4553     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4554       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4555       unsigned TargetMask = 0;
4556       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4557                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4558       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4559                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4560       V1 = NewV.getOperand(0);
4561       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4562     }
4563   }
4564
4565   // If we have SSSE3, and all words of the result are from 1 input vector,
4566   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4567   // is present, fall back to case 4.
4568   if (Subtarget->hasSSSE3()) {
4569     SmallVector<SDValue,16> pshufbMask;
4570
4571     // If we have elements from both input vectors, set the high bit of the
4572     // shuffle mask element to zero out elements that come from V2 in the V1
4573     // mask, and elements that come from V1 in the V2 mask, so that the two
4574     // results can be OR'd together.
4575     bool TwoInputs = V1Used && V2Used;
4576     for (unsigned i = 0; i != 8; ++i) {
4577       int EltIdx = MaskVals[i] * 2;
4578       if (TwoInputs && (EltIdx >= 16)) {
4579         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4580         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4581         continue;
4582       }
4583       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4584       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4585     }
4586     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4587     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4588                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4589                                  MVT::v16i8, &pshufbMask[0], 16));
4590     if (!TwoInputs)
4591       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4592
4593     // Calculate the shuffle mask for the second input, shuffle it, and
4594     // OR it with the first shuffled input.
4595     pshufbMask.clear();
4596     for (unsigned i = 0; i != 8; ++i) {
4597       int EltIdx = MaskVals[i] * 2;
4598       if (EltIdx < 16) {
4599         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4600         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4601         continue;
4602       }
4603       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4604       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4605     }
4606     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4607     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4608                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4609                                  MVT::v16i8, &pshufbMask[0], 16));
4610     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4611     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4612   }
4613
4614   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4615   // and update MaskVals with new element order.
4616   BitVector InOrder(8);
4617   if (BestLoQuad >= 0) {
4618     SmallVector<int, 8> MaskV;
4619     for (int i = 0; i != 4; ++i) {
4620       int idx = MaskVals[i];
4621       if (idx < 0) {
4622         MaskV.push_back(-1);
4623         InOrder.set(i);
4624       } else if ((idx / 4) == BestLoQuad) {
4625         MaskV.push_back(idx & 3);
4626         InOrder.set(i);
4627       } else {
4628         MaskV.push_back(-1);
4629       }
4630     }
4631     for (unsigned i = 4; i != 8; ++i)
4632       MaskV.push_back(i);
4633     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4634                                 &MaskV[0]);
4635
4636     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4637       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4638                                NewV.getOperand(0),
4639                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4640                                DAG);
4641   }
4642
4643   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4644   // and update MaskVals with the new element order.
4645   if (BestHiQuad >= 0) {
4646     SmallVector<int, 8> MaskV;
4647     for (unsigned i = 0; i != 4; ++i)
4648       MaskV.push_back(i);
4649     for (unsigned i = 4; i != 8; ++i) {
4650       int idx = MaskVals[i];
4651       if (idx < 0) {
4652         MaskV.push_back(-1);
4653         InOrder.set(i);
4654       } else if ((idx / 4) == BestHiQuad) {
4655         MaskV.push_back((idx & 3) + 4);
4656         InOrder.set(i);
4657       } else {
4658         MaskV.push_back(-1);
4659       }
4660     }
4661     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4662                                 &MaskV[0]);
4663
4664     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4665       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4666                               NewV.getOperand(0),
4667                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4668                               DAG);
4669   }
4670
4671   // In case BestHi & BestLo were both -1, which means each quadword has a word
4672   // from each of the four input quadwords, calculate the InOrder bitvector now
4673   // before falling through to the insert/extract cleanup.
4674   if (BestLoQuad == -1 && BestHiQuad == -1) {
4675     NewV = V1;
4676     for (int i = 0; i != 8; ++i)
4677       if (MaskVals[i] < 0 || MaskVals[i] == i)
4678         InOrder.set(i);
4679   }
4680
4681   // The other elements are put in the right place using pextrw and pinsrw.
4682   for (unsigned i = 0; i != 8; ++i) {
4683     if (InOrder[i])
4684       continue;
4685     int EltIdx = MaskVals[i];
4686     if (EltIdx < 0)
4687       continue;
4688     SDValue ExtOp = (EltIdx < 8)
4689     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4690                   DAG.getIntPtrConstant(EltIdx))
4691     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4692                   DAG.getIntPtrConstant(EltIdx - 8));
4693     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4694                        DAG.getIntPtrConstant(i));
4695   }
4696   return NewV;
4697 }
4698
4699 // v16i8 shuffles - Prefer shuffles in the following order:
4700 // 1. [ssse3] 1 x pshufb
4701 // 2. [ssse3] 2 x pshufb + 1 x por
4702 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4703 static
4704 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4705                                  SelectionDAG &DAG,
4706                                  const X86TargetLowering &TLI) {
4707   SDValue V1 = SVOp->getOperand(0);
4708   SDValue V2 = SVOp->getOperand(1);
4709   DebugLoc dl = SVOp->getDebugLoc();
4710   SmallVector<int, 16> MaskVals;
4711   SVOp->getMask(MaskVals);
4712
4713   // If we have SSSE3, case 1 is generated when all result bytes come from
4714   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4715   // present, fall back to case 3.
4716   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4717   bool V1Only = true;
4718   bool V2Only = true;
4719   for (unsigned i = 0; i < 16; ++i) {
4720     int EltIdx = MaskVals[i];
4721     if (EltIdx < 0)
4722       continue;
4723     if (EltIdx < 16)
4724       V2Only = false;
4725     else
4726       V1Only = false;
4727   }
4728
4729   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4730   if (TLI.getSubtarget()->hasSSSE3()) {
4731     SmallVector<SDValue,16> pshufbMask;
4732
4733     // If all result elements are from one input vector, then only translate
4734     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4735     //
4736     // Otherwise, we have elements from both input vectors, and must zero out
4737     // elements that come from V2 in the first mask, and V1 in the second mask
4738     // so that we can OR them together.
4739     bool TwoInputs = !(V1Only || V2Only);
4740     for (unsigned i = 0; i != 16; ++i) {
4741       int EltIdx = MaskVals[i];
4742       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4743         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4744         continue;
4745       }
4746       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4747     }
4748     // If all the elements are from V2, assign it to V1 and return after
4749     // building the first pshufb.
4750     if (V2Only)
4751       V1 = V2;
4752     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4753                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4754                                  MVT::v16i8, &pshufbMask[0], 16));
4755     if (!TwoInputs)
4756       return V1;
4757
4758     // Calculate the shuffle mask for the second input, shuffle it, and
4759     // OR it with the first shuffled input.
4760     pshufbMask.clear();
4761     for (unsigned i = 0; i != 16; ++i) {
4762       int EltIdx = MaskVals[i];
4763       if (EltIdx < 16) {
4764         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4765         continue;
4766       }
4767       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4768     }
4769     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4770                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4771                                  MVT::v16i8, &pshufbMask[0], 16));
4772     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4773   }
4774
4775   // No SSSE3 - Calculate in place words and then fix all out of place words
4776   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4777   // the 16 different words that comprise the two doublequadword input vectors.
4778   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4779   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4780   SDValue NewV = V2Only ? V2 : V1;
4781   for (int i = 0; i != 8; ++i) {
4782     int Elt0 = MaskVals[i*2];
4783     int Elt1 = MaskVals[i*2+1];
4784
4785     // This word of the result is all undef, skip it.
4786     if (Elt0 < 0 && Elt1 < 0)
4787       continue;
4788
4789     // This word of the result is already in the correct place, skip it.
4790     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4791       continue;
4792     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4793       continue;
4794
4795     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4796     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4797     SDValue InsElt;
4798
4799     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4800     // using a single extract together, load it and store it.
4801     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4802       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4803                            DAG.getIntPtrConstant(Elt1 / 2));
4804       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4805                         DAG.getIntPtrConstant(i));
4806       continue;
4807     }
4808
4809     // If Elt1 is defined, extract it from the appropriate source.  If the
4810     // source byte is not also odd, shift the extracted word left 8 bits
4811     // otherwise clear the bottom 8 bits if we need to do an or.
4812     if (Elt1 >= 0) {
4813       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4814                            DAG.getIntPtrConstant(Elt1 / 2));
4815       if ((Elt1 & 1) == 0)
4816         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4817                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4818       else if (Elt0 >= 0)
4819         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4820                              DAG.getConstant(0xFF00, MVT::i16));
4821     }
4822     // If Elt0 is defined, extract it from the appropriate source.  If the
4823     // source byte is not also even, shift the extracted word right 8 bits. If
4824     // Elt1 was also defined, OR the extracted values together before
4825     // inserting them in the result.
4826     if (Elt0 >= 0) {
4827       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4828                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4829       if ((Elt0 & 1) != 0)
4830         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4831                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4832       else if (Elt1 >= 0)
4833         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4834                              DAG.getConstant(0x00FF, MVT::i16));
4835       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4836                          : InsElt0;
4837     }
4838     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4839                        DAG.getIntPtrConstant(i));
4840   }
4841   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4842 }
4843
4844 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4845 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4846 /// done when every pair / quad of shuffle mask elements point to elements in
4847 /// the right sequence. e.g.
4848 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4849 static
4850 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4851                                  SelectionDAG &DAG, DebugLoc dl) {
4852   EVT VT = SVOp->getValueType(0);
4853   SDValue V1 = SVOp->getOperand(0);
4854   SDValue V2 = SVOp->getOperand(1);
4855   unsigned NumElems = VT.getVectorNumElements();
4856   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4857   EVT NewVT;
4858   switch (VT.getSimpleVT().SimpleTy) {
4859   default: assert(false && "Unexpected!");
4860   case MVT::v4f32: NewVT = MVT::v2f64; break;
4861   case MVT::v4i32: NewVT = MVT::v2i64; break;
4862   case MVT::v8i16: NewVT = MVT::v4i32; break;
4863   case MVT::v16i8: NewVT = MVT::v4i32; break;
4864   }
4865
4866   int Scale = NumElems / NewWidth;
4867   SmallVector<int, 8> MaskVec;
4868   for (unsigned i = 0; i < NumElems; i += Scale) {
4869     int StartIdx = -1;
4870     for (int j = 0; j < Scale; ++j) {
4871       int EltIdx = SVOp->getMaskElt(i+j);
4872       if (EltIdx < 0)
4873         continue;
4874       if (StartIdx == -1)
4875         StartIdx = EltIdx - (EltIdx % Scale);
4876       if (EltIdx != StartIdx + j)
4877         return SDValue();
4878     }
4879     if (StartIdx == -1)
4880       MaskVec.push_back(-1);
4881     else
4882       MaskVec.push_back(StartIdx / Scale);
4883   }
4884
4885   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4886   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4887   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4888 }
4889
4890 /// getVZextMovL - Return a zero-extending vector move low node.
4891 ///
4892 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4893                             SDValue SrcOp, SelectionDAG &DAG,
4894                             const X86Subtarget *Subtarget, DebugLoc dl) {
4895   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4896     LoadSDNode *LD = NULL;
4897     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4898       LD = dyn_cast<LoadSDNode>(SrcOp);
4899     if (!LD) {
4900       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4901       // instead.
4902       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4903       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4904           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4905           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4906           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4907         // PR2108
4908         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4909         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4910                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4911                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4912                                                    OpVT,
4913                                                    SrcOp.getOperand(0)
4914                                                           .getOperand(0))));
4915       }
4916     }
4917   }
4918
4919   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4920                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4921                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4922                                              OpVT, SrcOp)));
4923 }
4924
4925 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4926 /// shuffles.
4927 static SDValue
4928 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4929   SDValue V1 = SVOp->getOperand(0);
4930   SDValue V2 = SVOp->getOperand(1);
4931   DebugLoc dl = SVOp->getDebugLoc();
4932   EVT VT = SVOp->getValueType(0);
4933
4934   SmallVector<std::pair<int, int>, 8> Locs;
4935   Locs.resize(4);
4936   SmallVector<int, 8> Mask1(4U, -1);
4937   SmallVector<int, 8> PermMask;
4938   SVOp->getMask(PermMask);
4939
4940   unsigned NumHi = 0;
4941   unsigned NumLo = 0;
4942   for (unsigned i = 0; i != 4; ++i) {
4943     int Idx = PermMask[i];
4944     if (Idx < 0) {
4945       Locs[i] = std::make_pair(-1, -1);
4946     } else {
4947       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4948       if (Idx < 4) {
4949         Locs[i] = std::make_pair(0, NumLo);
4950         Mask1[NumLo] = Idx;
4951         NumLo++;
4952       } else {
4953         Locs[i] = std::make_pair(1, NumHi);
4954         if (2+NumHi < 4)
4955           Mask1[2+NumHi] = Idx;
4956         NumHi++;
4957       }
4958     }
4959   }
4960
4961   if (NumLo <= 2 && NumHi <= 2) {
4962     // If no more than two elements come from either vector. This can be
4963     // implemented with two shuffles. First shuffle gather the elements.
4964     // The second shuffle, which takes the first shuffle as both of its
4965     // vector operands, put the elements into the right order.
4966     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4967
4968     SmallVector<int, 8> Mask2(4U, -1);
4969
4970     for (unsigned i = 0; i != 4; ++i) {
4971       if (Locs[i].first == -1)
4972         continue;
4973       else {
4974         unsigned Idx = (i < 2) ? 0 : 4;
4975         Idx += Locs[i].first * 2 + Locs[i].second;
4976         Mask2[i] = Idx;
4977       }
4978     }
4979
4980     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4981   } else if (NumLo == 3 || NumHi == 3) {
4982     // Otherwise, we must have three elements from one vector, call it X, and
4983     // one element from the other, call it Y.  First, use a shufps to build an
4984     // intermediate vector with the one element from Y and the element from X
4985     // that will be in the same half in the final destination (the indexes don't
4986     // matter). Then, use a shufps to build the final vector, taking the half
4987     // containing the element from Y from the intermediate, and the other half
4988     // from X.
4989     if (NumHi == 3) {
4990       // Normalize it so the 3 elements come from V1.
4991       CommuteVectorShuffleMask(PermMask, VT);
4992       std::swap(V1, V2);
4993     }
4994
4995     // Find the element from V2.
4996     unsigned HiIndex;
4997     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4998       int Val = PermMask[HiIndex];
4999       if (Val < 0)
5000         continue;
5001       if (Val >= 4)
5002         break;
5003     }
5004
5005     Mask1[0] = PermMask[HiIndex];
5006     Mask1[1] = -1;
5007     Mask1[2] = PermMask[HiIndex^1];
5008     Mask1[3] = -1;
5009     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5010
5011     if (HiIndex >= 2) {
5012       Mask1[0] = PermMask[0];
5013       Mask1[1] = PermMask[1];
5014       Mask1[2] = HiIndex & 1 ? 6 : 4;
5015       Mask1[3] = HiIndex & 1 ? 4 : 6;
5016       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5017     } else {
5018       Mask1[0] = HiIndex & 1 ? 2 : 0;
5019       Mask1[1] = HiIndex & 1 ? 0 : 2;
5020       Mask1[2] = PermMask[2];
5021       Mask1[3] = PermMask[3];
5022       if (Mask1[2] >= 0)
5023         Mask1[2] += 4;
5024       if (Mask1[3] >= 0)
5025         Mask1[3] += 4;
5026       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5027     }
5028   }
5029
5030   // Break it into (shuffle shuffle_hi, shuffle_lo).
5031   Locs.clear();
5032   SmallVector<int,8> LoMask(4U, -1);
5033   SmallVector<int,8> HiMask(4U, -1);
5034
5035   SmallVector<int,8> *MaskPtr = &LoMask;
5036   unsigned MaskIdx = 0;
5037   unsigned LoIdx = 0;
5038   unsigned HiIdx = 2;
5039   for (unsigned i = 0; i != 4; ++i) {
5040     if (i == 2) {
5041       MaskPtr = &HiMask;
5042       MaskIdx = 1;
5043       LoIdx = 0;
5044       HiIdx = 2;
5045     }
5046     int Idx = PermMask[i];
5047     if (Idx < 0) {
5048       Locs[i] = std::make_pair(-1, -1);
5049     } else if (Idx < 4) {
5050       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5051       (*MaskPtr)[LoIdx] = Idx;
5052       LoIdx++;
5053     } else {
5054       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5055       (*MaskPtr)[HiIdx] = Idx;
5056       HiIdx++;
5057     }
5058   }
5059
5060   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5061   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5062   SmallVector<int, 8> MaskOps;
5063   for (unsigned i = 0; i != 4; ++i) {
5064     if (Locs[i].first == -1) {
5065       MaskOps.push_back(-1);
5066     } else {
5067       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5068       MaskOps.push_back(Idx);
5069     }
5070   }
5071   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5072 }
5073
5074 static bool MayFoldVectorLoad(SDValue V) {
5075   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5076     V = V.getOperand(0);
5077   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5078     V = V.getOperand(0);
5079   if (MayFoldLoad(V))
5080     return true;
5081   return false;
5082 }
5083
5084 // FIXME: the version above should always be used. Since there's
5085 // a bug where several vector shuffles can't be folded because the
5086 // DAG is not updated during lowering and a node claims to have two
5087 // uses while it only has one, use this version, and let isel match
5088 // another instruction if the load really happens to have more than
5089 // one use. Remove this version after this bug get fixed.
5090 // rdar://8434668, PR8156
5091 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5092   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5093     V = V.getOperand(0);
5094   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5095     V = V.getOperand(0);
5096   if (ISD::isNormalLoad(V.getNode()))
5097     return true;
5098   return false;
5099 }
5100
5101 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5102 /// a vector extract, and if both can be later optimized into a single load.
5103 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5104 /// here because otherwise a target specific shuffle node is going to be
5105 /// emitted for this shuffle, and the optimization not done.
5106 /// FIXME: This is probably not the best approach, but fix the problem
5107 /// until the right path is decided.
5108 static
5109 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5110                                          const TargetLowering &TLI) {
5111   EVT VT = V.getValueType();
5112   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5113
5114   // Be sure that the vector shuffle is present in a pattern like this:
5115   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5116   if (!V.hasOneUse())
5117     return false;
5118
5119   SDNode *N = *V.getNode()->use_begin();
5120   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5121     return false;
5122
5123   SDValue EltNo = N->getOperand(1);
5124   if (!isa<ConstantSDNode>(EltNo))
5125     return false;
5126
5127   // If the bit convert changed the number of elements, it is unsafe
5128   // to examine the mask.
5129   bool HasShuffleIntoBitcast = false;
5130   if (V.getOpcode() == ISD::BIT_CONVERT) {
5131     EVT SrcVT = V.getOperand(0).getValueType();
5132     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5133       return false;
5134     V = V.getOperand(0);
5135     HasShuffleIntoBitcast = true;
5136   }
5137
5138   // Select the input vector, guarding against out of range extract vector.
5139   unsigned NumElems = VT.getVectorNumElements();
5140   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5141   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5142   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5143
5144   // Skip one more bit_convert if necessary
5145   if (V.getOpcode() == ISD::BIT_CONVERT)
5146     V = V.getOperand(0);
5147
5148   if (ISD::isNormalLoad(V.getNode())) {
5149     // Is the original load suitable?
5150     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5151
5152     // FIXME: avoid the multi-use bug that is preventing lots of
5153     // of foldings to be detected, this is still wrong of course, but
5154     // give the temporary desired behavior, and if it happens that
5155     // the load has real more uses, during isel it will not fold, and
5156     // will generate poor code.
5157     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5158       return false;
5159
5160     if (!HasShuffleIntoBitcast)
5161       return true;
5162
5163     // If there's a bitcast before the shuffle, check if the load type and
5164     // alignment is valid.
5165     unsigned Align = LN0->getAlignment();
5166     unsigned NewAlign =
5167       TLI.getTargetData()->getABITypeAlignment(
5168                                     VT.getTypeForEVT(*DAG.getContext()));
5169
5170     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5171       return false;
5172   }
5173
5174   return true;
5175 }
5176
5177 static
5178 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5179   EVT VT = Op.getValueType();
5180
5181   // Canonizalize to v2f64.
5182   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, V1);
5183   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5184                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5185                                           V1, DAG));
5186 }
5187
5188 static
5189 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5190                         bool HasSSE2) {
5191   SDValue V1 = Op.getOperand(0);
5192   SDValue V2 = Op.getOperand(1);
5193   EVT VT = Op.getValueType();
5194
5195   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5196
5197   if (HasSSE2 && VT == MVT::v2f64)
5198     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5199
5200   // v4f32 or v4i32
5201   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5202 }
5203
5204 static
5205 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5206   SDValue V1 = Op.getOperand(0);
5207   SDValue V2 = Op.getOperand(1);
5208   EVT VT = Op.getValueType();
5209
5210   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5211          "unsupported shuffle type");
5212
5213   if (V2.getOpcode() == ISD::UNDEF)
5214     V2 = V1;
5215
5216   // v4i32 or v4f32
5217   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5218 }
5219
5220 static
5221 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5222   SDValue V1 = Op.getOperand(0);
5223   SDValue V2 = Op.getOperand(1);
5224   EVT VT = Op.getValueType();
5225   unsigned NumElems = VT.getVectorNumElements();
5226
5227   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5228   // operand of these instructions is only memory, so check if there's a
5229   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5230   // same masks.
5231   bool CanFoldLoad = false;
5232
5233   // Trivial case, when V2 comes from a load.
5234   if (MayFoldVectorLoad(V2))
5235     CanFoldLoad = true;
5236
5237   // When V1 is a load, it can be folded later into a store in isel, example:
5238   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5239   //    turns into:
5240   //  (MOVLPSmr addr:$src1, VR128:$src2)
5241   // So, recognize this potential and also use MOVLPS or MOVLPD
5242   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5243     CanFoldLoad = true;
5244
5245   if (CanFoldLoad) {
5246     if (HasSSE2 && NumElems == 2)
5247       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5248
5249     if (NumElems == 4)
5250       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5251   }
5252
5253   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5254   // movl and movlp will both match v2i64, but v2i64 is never matched by
5255   // movl earlier because we make it strict to avoid messing with the movlp load
5256   // folding logic (see the code above getMOVLP call). Match it here then,
5257   // this is horrible, but will stay like this until we move all shuffle
5258   // matching to x86 specific nodes. Note that for the 1st condition all
5259   // types are matched with movsd.
5260   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5261     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5262   else if (HasSSE2)
5263     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5264
5265
5266   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5267
5268   // Invert the operand order and use SHUFPS to match it.
5269   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5270                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5271 }
5272
5273 static inline unsigned getUNPCKLOpcode(EVT VT) {
5274   switch(VT.getSimpleVT().SimpleTy) {
5275   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5276   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5277   case MVT::v4f32: return X86ISD::UNPCKLPS;
5278   case MVT::v2f64: return X86ISD::UNPCKLPD;
5279   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5280   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5281   default:
5282     llvm_unreachable("Unknow type for unpckl");
5283   }
5284   return 0;
5285 }
5286
5287 static inline unsigned getUNPCKHOpcode(EVT VT) {
5288   switch(VT.getSimpleVT().SimpleTy) {
5289   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5290   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5291   case MVT::v4f32: return X86ISD::UNPCKHPS;
5292   case MVT::v2f64: return X86ISD::UNPCKHPD;
5293   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5294   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5295   default:
5296     llvm_unreachable("Unknow type for unpckh");
5297   }
5298   return 0;
5299 }
5300
5301 static
5302 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5303                                const TargetLowering &TLI,
5304                                const X86Subtarget *Subtarget) {
5305   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5306   EVT VT = Op.getValueType();
5307   DebugLoc dl = Op.getDebugLoc();
5308   SDValue V1 = Op.getOperand(0);
5309   SDValue V2 = Op.getOperand(1);
5310
5311   if (isZeroShuffle(SVOp))
5312     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5313
5314   // Handle splat operations
5315   if (SVOp->isSplat()) {
5316     // Special case, this is the only place now where it's
5317     // allowed to return a vector_shuffle operation without
5318     // using a target specific node, because *hopefully* it
5319     // will be optimized away by the dag combiner.
5320     if (VT.getVectorNumElements() <= 4 &&
5321         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5322       return Op;
5323
5324     // Handle splats by matching through known masks
5325     if (VT.getVectorNumElements() <= 4)
5326       return SDValue();
5327
5328     // Canonicalize all of the remaining to v4f32.
5329     return PromoteSplat(SVOp, DAG);
5330   }
5331
5332   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5333   // do it!
5334   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5335     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5336     if (NewOp.getNode())
5337       return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5338   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5339     // FIXME: Figure out a cleaner way to do this.
5340     // Try to make use of movq to zero out the top part.
5341     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5342       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5343       if (NewOp.getNode()) {
5344         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5345           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5346                               DAG, Subtarget, dl);
5347       }
5348     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5349       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5350       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5351         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5352                             DAG, Subtarget, dl);
5353     }
5354   }
5355   return SDValue();
5356 }
5357
5358 SDValue
5359 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5360   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5361   SDValue V1 = Op.getOperand(0);
5362   SDValue V2 = Op.getOperand(1);
5363   EVT VT = Op.getValueType();
5364   DebugLoc dl = Op.getDebugLoc();
5365   unsigned NumElems = VT.getVectorNumElements();
5366   bool isMMX = VT.getSizeInBits() == 64;
5367   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5368   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5369   bool V1IsSplat = false;
5370   bool V2IsSplat = false;
5371   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5372   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5373   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5374   MachineFunction &MF = DAG.getMachineFunction();
5375   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5376
5377   // Shuffle operations on MMX not supported.
5378   if (isMMX)
5379     return Op;
5380
5381   // Vector shuffle lowering takes 3 steps:
5382   //
5383   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5384   //    narrowing and commutation of operands should be handled.
5385   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5386   //    shuffle nodes.
5387   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5388   //    so the shuffle can be broken into other shuffles and the legalizer can
5389   //    try the lowering again.
5390   //
5391   // The general ideia is that no vector_shuffle operation should be left to
5392   // be matched during isel, all of them must be converted to a target specific
5393   // node here.
5394
5395   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5396   // narrowing and commutation of operands should be handled. The actual code
5397   // doesn't include all of those, work in progress...
5398   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5399   if (NewOp.getNode())
5400     return NewOp;
5401
5402   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5403   // unpckh_undef). Only use pshufd if speed is more important than size.
5404   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5405     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5406       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5407   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5408     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5409       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5410
5411   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5412       RelaxedMayFoldVectorLoad(V1))
5413     return getMOVDDup(Op, dl, V1, DAG);
5414
5415   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5416     return getMOVHighToLow(Op, dl, DAG);
5417
5418   // Use to match splats
5419   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5420       (VT == MVT::v2f64 || VT == MVT::v2i64))
5421     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5422
5423   if (X86::isPSHUFDMask(SVOp)) {
5424     // The actual implementation will match the mask in the if above and then
5425     // during isel it can match several different instructions, not only pshufd
5426     // as its name says, sad but true, emulate the behavior for now...
5427     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5428         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5429
5430     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5431
5432     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5433       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5434
5435     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5436       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5437                                   TargetMask, DAG);
5438
5439     if (VT == MVT::v4f32)
5440       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5441                                   TargetMask, DAG);
5442   }
5443
5444   // Check if this can be converted into a logical shift.
5445   bool isLeft = false;
5446   unsigned ShAmt = 0;
5447   SDValue ShVal;
5448   bool isShift = getSubtarget()->hasSSE2() &&
5449     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5450   if (isShift && ShVal.hasOneUse()) {
5451     // If the shifted value has multiple uses, it may be cheaper to use
5452     // v_set0 + movlhps or movhlps, etc.
5453     EVT EltVT = VT.getVectorElementType();
5454     ShAmt *= EltVT.getSizeInBits();
5455     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5456   }
5457
5458   if (X86::isMOVLMask(SVOp)) {
5459     if (V1IsUndef)
5460       return V2;
5461     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5462       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5463     if (!X86::isMOVLPMask(SVOp)) {
5464       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5465         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5466
5467       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5468         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5469     }
5470   }
5471
5472   // FIXME: fold these into legal mask.
5473   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5474     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5475
5476   if (X86::isMOVHLPSMask(SVOp))
5477     return getMOVHighToLow(Op, dl, DAG);
5478
5479   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5480     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5481
5482   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5483     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5484
5485   if (X86::isMOVLPMask(SVOp))
5486     return getMOVLP(Op, dl, DAG, HasSSE2);
5487
5488   if (ShouldXformToMOVHLPS(SVOp) ||
5489       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5490     return CommuteVectorShuffle(SVOp, DAG);
5491
5492   if (isShift) {
5493     // No better options. Use a vshl / vsrl.
5494     EVT EltVT = VT.getVectorElementType();
5495     ShAmt *= EltVT.getSizeInBits();
5496     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5497   }
5498
5499   bool Commuted = false;
5500   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5501   // 1,1,1,1 -> v8i16 though.
5502   V1IsSplat = isSplatVector(V1.getNode());
5503   V2IsSplat = isSplatVector(V2.getNode());
5504
5505   // Canonicalize the splat or undef, if present, to be on the RHS.
5506   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5507     Op = CommuteVectorShuffle(SVOp, DAG);
5508     SVOp = cast<ShuffleVectorSDNode>(Op);
5509     V1 = SVOp->getOperand(0);
5510     V2 = SVOp->getOperand(1);
5511     std::swap(V1IsSplat, V2IsSplat);
5512     std::swap(V1IsUndef, V2IsUndef);
5513     Commuted = true;
5514   }
5515
5516   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5517     // Shuffling low element of v1 into undef, just return v1.
5518     if (V2IsUndef)
5519       return V1;
5520     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5521     // the instruction selector will not match, so get a canonical MOVL with
5522     // swapped operands to undo the commute.
5523     return getMOVL(DAG, dl, VT, V2, V1);
5524   }
5525
5526   if (X86::isUNPCKLMask(SVOp))
5527     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5528
5529   if (X86::isUNPCKHMask(SVOp))
5530     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5531
5532   if (V2IsSplat) {
5533     // Normalize mask so all entries that point to V2 points to its first
5534     // element then try to match unpck{h|l} again. If match, return a
5535     // new vector_shuffle with the corrected mask.
5536     SDValue NewMask = NormalizeMask(SVOp, DAG);
5537     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5538     if (NSVOp != SVOp) {
5539       if (X86::isUNPCKLMask(NSVOp, true)) {
5540         return NewMask;
5541       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5542         return NewMask;
5543       }
5544     }
5545   }
5546
5547   if (Commuted) {
5548     // Commute is back and try unpck* again.
5549     // FIXME: this seems wrong.
5550     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5551     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5552
5553     if (X86::isUNPCKLMask(NewSVOp))
5554       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5555
5556     if (X86::isUNPCKHMask(NewSVOp))
5557       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5558   }
5559
5560   // Normalize the node to match x86 shuffle ops if needed
5561   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5562     return CommuteVectorShuffle(SVOp, DAG);
5563
5564   // The checks below are all present in isShuffleMaskLegal, but they are
5565   // inlined here right now to enable us to directly emit target specific
5566   // nodes, and remove one by one until they don't return Op anymore.
5567   SmallVector<int, 16> M;
5568   SVOp->getMask(M);
5569
5570   if (isPALIGNRMask(M, VT, HasSSSE3))
5571     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5572                                 X86::getShufflePALIGNRImmediate(SVOp),
5573                                 DAG);
5574
5575   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5576       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5577     if (VT == MVT::v2f64)
5578       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5579     if (VT == MVT::v2i64)
5580       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5581   }
5582
5583   if (isPSHUFHWMask(M, VT))
5584     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5585                                 X86::getShufflePSHUFHWImmediate(SVOp),
5586                                 DAG);
5587
5588   if (isPSHUFLWMask(M, VT))
5589     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5590                                 X86::getShufflePSHUFLWImmediate(SVOp),
5591                                 DAG);
5592
5593   if (isSHUFPMask(M, VT)) {
5594     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5595     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5596       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5597                                   TargetMask, DAG);
5598     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5599       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5600                                   TargetMask, DAG);
5601   }
5602
5603   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5604     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5605       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5606   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5607     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5608       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5609
5610   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5611   if (VT == MVT::v8i16) {
5612     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5613     if (NewOp.getNode())
5614       return NewOp;
5615   }
5616
5617   if (VT == MVT::v16i8) {
5618     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5619     if (NewOp.getNode())
5620       return NewOp;
5621   }
5622
5623   // Handle all 4 wide cases with a number of shuffles.
5624   if (NumElems == 4)
5625     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5626
5627   return SDValue();
5628 }
5629
5630 SDValue
5631 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5632                                                 SelectionDAG &DAG) const {
5633   EVT VT = Op.getValueType();
5634   DebugLoc dl = Op.getDebugLoc();
5635   if (VT.getSizeInBits() == 8) {
5636     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5637                                     Op.getOperand(0), Op.getOperand(1));
5638     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5639                                     DAG.getValueType(VT));
5640     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5641   } else if (VT.getSizeInBits() == 16) {
5642     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5643     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5644     if (Idx == 0)
5645       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5646                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5647                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5648                                                  MVT::v4i32,
5649                                                  Op.getOperand(0)),
5650                                      Op.getOperand(1)));
5651     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5652                                     Op.getOperand(0), Op.getOperand(1));
5653     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5654                                     DAG.getValueType(VT));
5655     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5656   } else if (VT == MVT::f32) {
5657     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5658     // the result back to FR32 register. It's only worth matching if the
5659     // result has a single use which is a store or a bitcast to i32.  And in
5660     // the case of a store, it's not worth it if the index is a constant 0,
5661     // because a MOVSSmr can be used instead, which is smaller and faster.
5662     if (!Op.hasOneUse())
5663       return SDValue();
5664     SDNode *User = *Op.getNode()->use_begin();
5665     if ((User->getOpcode() != ISD::STORE ||
5666          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5667           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5668         (User->getOpcode() != ISD::BIT_CONVERT ||
5669          User->getValueType(0) != MVT::i32))
5670       return SDValue();
5671     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5672                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5673                                               Op.getOperand(0)),
5674                                               Op.getOperand(1));
5675     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5676   } else if (VT == MVT::i32) {
5677     // ExtractPS works with constant index.
5678     if (isa<ConstantSDNode>(Op.getOperand(1)))
5679       return Op;
5680   }
5681   return SDValue();
5682 }
5683
5684
5685 SDValue
5686 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5687                                            SelectionDAG &DAG) const {
5688   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5689     return SDValue();
5690
5691   if (Subtarget->hasSSE41()) {
5692     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5693     if (Res.getNode())
5694       return Res;
5695   }
5696
5697   EVT VT = Op.getValueType();
5698   DebugLoc dl = Op.getDebugLoc();
5699   // TODO: handle v16i8.
5700   if (VT.getSizeInBits() == 16) {
5701     SDValue Vec = Op.getOperand(0);
5702     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5703     if (Idx == 0)
5704       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5705                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5706                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5707                                                  MVT::v4i32, Vec),
5708                                      Op.getOperand(1)));
5709     // Transform it so it match pextrw which produces a 32-bit result.
5710     EVT EltVT = MVT::i32;
5711     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5712                                     Op.getOperand(0), Op.getOperand(1));
5713     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5714                                     DAG.getValueType(VT));
5715     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5716   } else if (VT.getSizeInBits() == 32) {
5717     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5718     if (Idx == 0)
5719       return Op;
5720
5721     // SHUFPS the element to the lowest double word, then movss.
5722     int Mask[4] = { Idx, -1, -1, -1 };
5723     EVT VVT = Op.getOperand(0).getValueType();
5724     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5725                                        DAG.getUNDEF(VVT), Mask);
5726     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5727                        DAG.getIntPtrConstant(0));
5728   } else if (VT.getSizeInBits() == 64) {
5729     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5730     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5731     //        to match extract_elt for f64.
5732     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5733     if (Idx == 0)
5734       return Op;
5735
5736     // UNPCKHPD the element to the lowest double word, then movsd.
5737     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5738     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5739     int Mask[2] = { 1, -1 };
5740     EVT VVT = Op.getOperand(0).getValueType();
5741     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5742                                        DAG.getUNDEF(VVT), Mask);
5743     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5744                        DAG.getIntPtrConstant(0));
5745   }
5746
5747   return SDValue();
5748 }
5749
5750 SDValue
5751 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5752                                                SelectionDAG &DAG) const {
5753   EVT VT = Op.getValueType();
5754   EVT EltVT = VT.getVectorElementType();
5755   DebugLoc dl = Op.getDebugLoc();
5756
5757   SDValue N0 = Op.getOperand(0);
5758   SDValue N1 = Op.getOperand(1);
5759   SDValue N2 = Op.getOperand(2);
5760
5761   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5762       isa<ConstantSDNode>(N2)) {
5763     unsigned Opc;
5764     if (VT == MVT::v8i16)
5765       Opc = X86ISD::PINSRW;
5766     else if (VT == MVT::v16i8)
5767       Opc = X86ISD::PINSRB;
5768     else
5769       Opc = X86ISD::PINSRB;
5770
5771     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5772     // argument.
5773     if (N1.getValueType() != MVT::i32)
5774       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5775     if (N2.getValueType() != MVT::i32)
5776       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5777     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5778   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5779     // Bits [7:6] of the constant are the source select.  This will always be
5780     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5781     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5782     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5783     // Bits [5:4] of the constant are the destination select.  This is the
5784     //  value of the incoming immediate.
5785     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5786     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5787     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5788     // Create this as a scalar to vector..
5789     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5790     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5791   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5792     // PINSR* works with constant index.
5793     return Op;
5794   }
5795   return SDValue();
5796 }
5797
5798 SDValue
5799 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5800   EVT VT = Op.getValueType();
5801   EVT EltVT = VT.getVectorElementType();
5802
5803   if (Subtarget->hasSSE41())
5804     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5805
5806   if (EltVT == MVT::i8)
5807     return SDValue();
5808
5809   DebugLoc dl = Op.getDebugLoc();
5810   SDValue N0 = Op.getOperand(0);
5811   SDValue N1 = Op.getOperand(1);
5812   SDValue N2 = Op.getOperand(2);
5813
5814   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5815     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5816     // as its second argument.
5817     if (N1.getValueType() != MVT::i32)
5818       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5819     if (N2.getValueType() != MVT::i32)
5820       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5821     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5822   }
5823   return SDValue();
5824 }
5825
5826 SDValue
5827 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5828   DebugLoc dl = Op.getDebugLoc();
5829   
5830   if (Op.getValueType() == MVT::v1i64 &&
5831       Op.getOperand(0).getValueType() == MVT::i64)
5832     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5833
5834   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5835   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5836          "Expected an SSE type!");
5837   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5838                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5839 }
5840
5841 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5842 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5843 // one of the above mentioned nodes. It has to be wrapped because otherwise
5844 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5845 // be used to form addressing mode. These wrapped nodes will be selected
5846 // into MOV32ri.
5847 SDValue
5848 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5849   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5850
5851   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5852   // global base reg.
5853   unsigned char OpFlag = 0;
5854   unsigned WrapperKind = X86ISD::Wrapper;
5855   CodeModel::Model M = getTargetMachine().getCodeModel();
5856
5857   if (Subtarget->isPICStyleRIPRel() &&
5858       (M == CodeModel::Small || M == CodeModel::Kernel))
5859     WrapperKind = X86ISD::WrapperRIP;
5860   else if (Subtarget->isPICStyleGOT())
5861     OpFlag = X86II::MO_GOTOFF;
5862   else if (Subtarget->isPICStyleStubPIC())
5863     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5864
5865   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5866                                              CP->getAlignment(),
5867                                              CP->getOffset(), OpFlag);
5868   DebugLoc DL = CP->getDebugLoc();
5869   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5870   // With PIC, the address is actually $g + Offset.
5871   if (OpFlag) {
5872     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5873                          DAG.getNode(X86ISD::GlobalBaseReg,
5874                                      DebugLoc(), getPointerTy()),
5875                          Result);
5876   }
5877
5878   return Result;
5879 }
5880
5881 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5882   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5883
5884   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5885   // global base reg.
5886   unsigned char OpFlag = 0;
5887   unsigned WrapperKind = X86ISD::Wrapper;
5888   CodeModel::Model M = getTargetMachine().getCodeModel();
5889
5890   if (Subtarget->isPICStyleRIPRel() &&
5891       (M == CodeModel::Small || M == CodeModel::Kernel))
5892     WrapperKind = X86ISD::WrapperRIP;
5893   else if (Subtarget->isPICStyleGOT())
5894     OpFlag = X86II::MO_GOTOFF;
5895   else if (Subtarget->isPICStyleStubPIC())
5896     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5897
5898   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5899                                           OpFlag);
5900   DebugLoc DL = JT->getDebugLoc();
5901   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5902
5903   // With PIC, the address is actually $g + Offset.
5904   if (OpFlag) {
5905     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5906                          DAG.getNode(X86ISD::GlobalBaseReg,
5907                                      DebugLoc(), getPointerTy()),
5908                          Result);
5909   }
5910
5911   return Result;
5912 }
5913
5914 SDValue
5915 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5916   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5917
5918   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5919   // global base reg.
5920   unsigned char OpFlag = 0;
5921   unsigned WrapperKind = X86ISD::Wrapper;
5922   CodeModel::Model M = getTargetMachine().getCodeModel();
5923
5924   if (Subtarget->isPICStyleRIPRel() &&
5925       (M == CodeModel::Small || M == CodeModel::Kernel))
5926     WrapperKind = X86ISD::WrapperRIP;
5927   else if (Subtarget->isPICStyleGOT())
5928     OpFlag = X86II::MO_GOTOFF;
5929   else if (Subtarget->isPICStyleStubPIC())
5930     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5931
5932   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5933
5934   DebugLoc DL = Op.getDebugLoc();
5935   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5936
5937
5938   // With PIC, the address is actually $g + Offset.
5939   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5940       !Subtarget->is64Bit()) {
5941     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5942                          DAG.getNode(X86ISD::GlobalBaseReg,
5943                                      DebugLoc(), getPointerTy()),
5944                          Result);
5945   }
5946
5947   return Result;
5948 }
5949
5950 SDValue
5951 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5952   // Create the TargetBlockAddressAddress node.
5953   unsigned char OpFlags =
5954     Subtarget->ClassifyBlockAddressReference();
5955   CodeModel::Model M = getTargetMachine().getCodeModel();
5956   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5957   DebugLoc dl = Op.getDebugLoc();
5958   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5959                                        /*isTarget=*/true, OpFlags);
5960
5961   if (Subtarget->isPICStyleRIPRel() &&
5962       (M == CodeModel::Small || M == CodeModel::Kernel))
5963     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5964   else
5965     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5966
5967   // With PIC, the address is actually $g + Offset.
5968   if (isGlobalRelativeToPICBase(OpFlags)) {
5969     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5970                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5971                          Result);
5972   }
5973
5974   return Result;
5975 }
5976
5977 SDValue
5978 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5979                                       int64_t Offset,
5980                                       SelectionDAG &DAG) const {
5981   // Create the TargetGlobalAddress node, folding in the constant
5982   // offset if it is legal.
5983   unsigned char OpFlags =
5984     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5985   CodeModel::Model M = getTargetMachine().getCodeModel();
5986   SDValue Result;
5987   if (OpFlags == X86II::MO_NO_FLAG &&
5988       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5989     // A direct static reference to a global.
5990     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5991     Offset = 0;
5992   } else {
5993     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5994   }
5995
5996   if (Subtarget->isPICStyleRIPRel() &&
5997       (M == CodeModel::Small || M == CodeModel::Kernel))
5998     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5999   else
6000     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6001
6002   // With PIC, the address is actually $g + Offset.
6003   if (isGlobalRelativeToPICBase(OpFlags)) {
6004     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6005                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6006                          Result);
6007   }
6008
6009   // For globals that require a load from a stub to get the address, emit the
6010   // load.
6011   if (isGlobalStubReference(OpFlags))
6012     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6013                          MachinePointerInfo::getGOT(), false, false, 0);
6014
6015   // If there was a non-zero offset that we didn't fold, create an explicit
6016   // addition for it.
6017   if (Offset != 0)
6018     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6019                          DAG.getConstant(Offset, getPointerTy()));
6020
6021   return Result;
6022 }
6023
6024 SDValue
6025 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6026   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6027   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6028   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6029 }
6030
6031 static SDValue
6032 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6033            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6034            unsigned char OperandFlags) {
6035   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6036   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6037   DebugLoc dl = GA->getDebugLoc();
6038   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6039                                            GA->getValueType(0),
6040                                            GA->getOffset(),
6041                                            OperandFlags);
6042   if (InFlag) {
6043     SDValue Ops[] = { Chain,  TGA, *InFlag };
6044     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6045   } else {
6046     SDValue Ops[]  = { Chain, TGA };
6047     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6048   }
6049
6050   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6051   MFI->setAdjustsStack(true);
6052
6053   SDValue Flag = Chain.getValue(1);
6054   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6055 }
6056
6057 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6058 static SDValue
6059 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6060                                 const EVT PtrVT) {
6061   SDValue InFlag;
6062   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6063   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6064                                      DAG.getNode(X86ISD::GlobalBaseReg,
6065                                                  DebugLoc(), PtrVT), InFlag);
6066   InFlag = Chain.getValue(1);
6067
6068   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6069 }
6070
6071 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6072 static SDValue
6073 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6074                                 const EVT PtrVT) {
6075   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6076                     X86::RAX, X86II::MO_TLSGD);
6077 }
6078
6079 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6080 // "local exec" model.
6081 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6082                                    const EVT PtrVT, TLSModel::Model model,
6083                                    bool is64Bit) {
6084   DebugLoc dl = GA->getDebugLoc();
6085   
6086   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6087   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6088                                                          is64Bit ? 257 : 256));
6089
6090   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 
6091                                       DAG.getIntPtrConstant(0),
6092                                       MachinePointerInfo(Ptr), false, false, 0);
6093
6094   unsigned char OperandFlags = 0;
6095   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6096   // initialexec.
6097   unsigned WrapperKind = X86ISD::Wrapper;
6098   if (model == TLSModel::LocalExec) {
6099     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6100   } else if (is64Bit) {
6101     assert(model == TLSModel::InitialExec);
6102     OperandFlags = X86II::MO_GOTTPOFF;
6103     WrapperKind = X86ISD::WrapperRIP;
6104   } else {
6105     assert(model == TLSModel::InitialExec);
6106     OperandFlags = X86II::MO_INDNTPOFF;
6107   }
6108
6109   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6110   // exec)
6111   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 
6112                                            GA->getValueType(0),
6113                                            GA->getOffset(), OperandFlags);
6114   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6115
6116   if (model == TLSModel::InitialExec)
6117     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6118                          MachinePointerInfo::getGOT(), false, false, 0);
6119
6120   // The address of the thread local variable is the add of the thread
6121   // pointer with the offset of the variable.
6122   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6123 }
6124
6125 SDValue
6126 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6127   
6128   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6129   const GlobalValue *GV = GA->getGlobal();
6130
6131   if (Subtarget->isTargetELF()) {
6132     // TODO: implement the "local dynamic" model
6133     // TODO: implement the "initial exec"model for pic executables
6134     
6135     // If GV is an alias then use the aliasee for determining
6136     // thread-localness.
6137     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6138       GV = GA->resolveAliasedGlobal(false);
6139     
6140     TLSModel::Model model 
6141       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6142     
6143     switch (model) {
6144       case TLSModel::GeneralDynamic:
6145       case TLSModel::LocalDynamic: // not implemented
6146         if (Subtarget->is64Bit())
6147           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6148         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6149         
6150       case TLSModel::InitialExec:
6151       case TLSModel::LocalExec:
6152         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6153                                    Subtarget->is64Bit());
6154     }
6155   } else if (Subtarget->isTargetDarwin()) {
6156     // Darwin only has one model of TLS.  Lower to that.
6157     unsigned char OpFlag = 0;
6158     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6159                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6160     
6161     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6162     // global base reg.
6163     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6164                   !Subtarget->is64Bit();
6165     if (PIC32)
6166       OpFlag = X86II::MO_TLVP_PIC_BASE;
6167     else
6168       OpFlag = X86II::MO_TLVP;
6169     DebugLoc DL = Op.getDebugLoc();    
6170     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6171                                                 getPointerTy(),
6172                                                 GA->getOffset(), OpFlag);
6173     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6174   
6175     // With PIC32, the address is actually $g + Offset.
6176     if (PIC32)
6177       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6178                            DAG.getNode(X86ISD::GlobalBaseReg,
6179                                        DebugLoc(), getPointerTy()),
6180                            Offset);
6181     
6182     // Lowering the machine isd will make sure everything is in the right
6183     // location.
6184     SDValue Args[] = { Offset };
6185     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6186     
6187     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6188     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6189     MFI->setAdjustsStack(true);
6190
6191     // And our return value (tls address) is in the standard call return value
6192     // location.
6193     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6194     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6195   }
6196   
6197   assert(false &&
6198          "TLS not implemented for this target.");
6199
6200   llvm_unreachable("Unreachable");
6201   return SDValue();
6202 }
6203
6204
6205 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6206 /// take a 2 x i32 value to shift plus a shift amount.
6207 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6208   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6209   EVT VT = Op.getValueType();
6210   unsigned VTBits = VT.getSizeInBits();
6211   DebugLoc dl = Op.getDebugLoc();
6212   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6213   SDValue ShOpLo = Op.getOperand(0);
6214   SDValue ShOpHi = Op.getOperand(1);
6215   SDValue ShAmt  = Op.getOperand(2);
6216   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6217                                      DAG.getConstant(VTBits - 1, MVT::i8))
6218                        : DAG.getConstant(0, VT);
6219
6220   SDValue Tmp2, Tmp3;
6221   if (Op.getOpcode() == ISD::SHL_PARTS) {
6222     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6223     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6224   } else {
6225     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6226     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6227   }
6228
6229   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6230                                 DAG.getConstant(VTBits, MVT::i8));
6231   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6232                              AndNode, DAG.getConstant(0, MVT::i8));
6233
6234   SDValue Hi, Lo;
6235   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6236   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6237   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6238
6239   if (Op.getOpcode() == ISD::SHL_PARTS) {
6240     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6241     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6242   } else {
6243     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6244     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6245   }
6246
6247   SDValue Ops[2] = { Lo, Hi };
6248   return DAG.getMergeValues(Ops, 2, dl);
6249 }
6250
6251 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6252                                            SelectionDAG &DAG) const {
6253   EVT SrcVT = Op.getOperand(0).getValueType();
6254
6255   if (SrcVT.isVector())
6256     return SDValue();
6257
6258   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6259          "Unknown SINT_TO_FP to lower!");
6260
6261   // These are really Legal; return the operand so the caller accepts it as
6262   // Legal.
6263   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6264     return Op;
6265   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6266       Subtarget->is64Bit()) {
6267     return Op;
6268   }
6269
6270   DebugLoc dl = Op.getDebugLoc();
6271   unsigned Size = SrcVT.getSizeInBits()/8;
6272   MachineFunction &MF = DAG.getMachineFunction();
6273   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6274   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6275   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6276                                StackSlot,
6277                                MachinePointerInfo::getFixedStack(SSFI),
6278                                false, false, 0);
6279   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6280 }
6281
6282 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6283                                      SDValue StackSlot, 
6284                                      SelectionDAG &DAG) const {
6285   // Build the FILD
6286   DebugLoc DL = Op.getDebugLoc();
6287   SDVTList Tys;
6288   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6289   if (useSSE)
6290     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6291   else
6292     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6293   
6294   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6295   
6296   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6297   MachineMemOperand *MMO =
6298     DAG.getMachineFunction()
6299     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6300                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6301   
6302   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6303   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6304                                            X86ISD::FILD, DL,
6305                                            Tys, Ops, array_lengthof(Ops),
6306                                            SrcVT, MMO);
6307
6308   if (useSSE) {
6309     Chain = Result.getValue(1);
6310     SDValue InFlag = Result.getValue(2);
6311
6312     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6313     // shouldn't be necessary except that RFP cannot be live across
6314     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6315     MachineFunction &MF = DAG.getMachineFunction();
6316     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6317     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6318     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6319     Tys = DAG.getVTList(MVT::Other);
6320     SDValue Ops[] = {
6321       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6322     };
6323     MachineMemOperand *MMO =
6324       DAG.getMachineFunction()
6325       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6326                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6327     
6328     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6329                                     Ops, array_lengthof(Ops),
6330                                     Op.getValueType(), MMO);
6331     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6332                          MachinePointerInfo::getFixedStack(SSFI),
6333                          false, false, 0);
6334   }
6335
6336   return Result;
6337 }
6338
6339 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6340 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6341                                                SelectionDAG &DAG) const {
6342   // This algorithm is not obvious. Here it is in C code, more or less:
6343   /*
6344     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6345       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6346       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6347
6348       // Copy ints to xmm registers.
6349       __m128i xh = _mm_cvtsi32_si128( hi );
6350       __m128i xl = _mm_cvtsi32_si128( lo );
6351
6352       // Combine into low half of a single xmm register.
6353       __m128i x = _mm_unpacklo_epi32( xh, xl );
6354       __m128d d;
6355       double sd;
6356
6357       // Merge in appropriate exponents to give the integer bits the right
6358       // magnitude.
6359       x = _mm_unpacklo_epi32( x, exp );
6360
6361       // Subtract away the biases to deal with the IEEE-754 double precision
6362       // implicit 1.
6363       d = _mm_sub_pd( (__m128d) x, bias );
6364
6365       // All conversions up to here are exact. The correctly rounded result is
6366       // calculated using the current rounding mode using the following
6367       // horizontal add.
6368       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6369       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6370                                 // store doesn't really need to be here (except
6371                                 // maybe to zero the other double)
6372       return sd;
6373     }
6374   */
6375
6376   DebugLoc dl = Op.getDebugLoc();
6377   LLVMContext *Context = DAG.getContext();
6378
6379   // Build some magic constants.
6380   std::vector<Constant*> CV0;
6381   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6382   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6383   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6384   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6385   Constant *C0 = ConstantVector::get(CV0);
6386   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6387
6388   std::vector<Constant*> CV1;
6389   CV1.push_back(
6390     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6391   CV1.push_back(
6392     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6393   Constant *C1 = ConstantVector::get(CV1);
6394   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6395
6396   SDValue XR1 = 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(1)));
6400   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6401                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6402                                         Op.getOperand(0),
6403                                         DAG.getIntPtrConstant(0)));
6404   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6405   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6406                               MachinePointerInfo::getConstantPool(),
6407                               false, false, 16);
6408   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6409   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6410   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6411                               MachinePointerInfo::getConstantPool(),
6412                               false, false, 16);
6413   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6414
6415   // Add the halves; easiest way is to swap them into another reg first.
6416   int ShufMask[2] = { 1, -1 };
6417   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6418                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6419   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6420   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6421                      DAG.getIntPtrConstant(0));
6422 }
6423
6424 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6425 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6426                                                SelectionDAG &DAG) const {
6427   DebugLoc dl = Op.getDebugLoc();
6428   // FP constant to bias correct the final result.
6429   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6430                                    MVT::f64);
6431
6432   // Load the 32-bit value into an XMM register.
6433   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6434                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6435                                          Op.getOperand(0),
6436                                          DAG.getIntPtrConstant(0)));
6437
6438   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6439                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6440                      DAG.getIntPtrConstant(0));
6441
6442   // Or the load with the bias.
6443   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6444                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6445                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6446                                                    MVT::v2f64, Load)),
6447                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6448                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6449                                                    MVT::v2f64, Bias)));
6450   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6451                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6452                    DAG.getIntPtrConstant(0));
6453
6454   // Subtract the bias.
6455   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6456
6457   // Handle final rounding.
6458   EVT DestVT = Op.getValueType();
6459
6460   if (DestVT.bitsLT(MVT::f64)) {
6461     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6462                        DAG.getIntPtrConstant(0));
6463   } else if (DestVT.bitsGT(MVT::f64)) {
6464     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6465   }
6466
6467   // Handle final rounding.
6468   return Sub;
6469 }
6470
6471 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6472                                            SelectionDAG &DAG) const {
6473   SDValue N0 = Op.getOperand(0);
6474   DebugLoc dl = Op.getDebugLoc();
6475
6476   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6477   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6478   // the optimization here.
6479   if (DAG.SignBitIsZero(N0))
6480     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6481
6482   EVT SrcVT = N0.getValueType();
6483   EVT DstVT = Op.getValueType();
6484   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6485     return LowerUINT_TO_FP_i64(Op, DAG);
6486   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6487     return LowerUINT_TO_FP_i32(Op, DAG);
6488
6489   // Make a 64-bit buffer, and use it to build an FILD.
6490   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6491   if (SrcVT == MVT::i32) {
6492     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6493     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6494                                      getPointerTy(), StackSlot, WordOff);
6495     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6496                                   StackSlot, MachinePointerInfo(),
6497                                   false, false, 0);
6498     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6499                                   OffsetSlot, MachinePointerInfo(),
6500                                   false, false, 0);
6501     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6502     return Fild;
6503   }
6504
6505   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6506   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6507                                 StackSlot, MachinePointerInfo(),
6508                                false, false, 0);
6509   // For i64 source, we need to add the appropriate power of 2 if the input
6510   // was negative.  This is the same as the optimization in
6511   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6512   // we must be careful to do the computation in x87 extended precision, not
6513   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6514   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6515   MachineMemOperand *MMO =
6516     DAG.getMachineFunction()
6517     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6518                           MachineMemOperand::MOLoad, 8, 8);
6519   
6520   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6521   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6522   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6523                                          MVT::i64, MMO);
6524
6525   APInt FF(32, 0x5F800000ULL);
6526
6527   // Check whether the sign bit is set.
6528   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6529                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6530                                  ISD::SETLT);
6531
6532   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6533   SDValue FudgePtr = DAG.getConstantPool(
6534                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6535                                          getPointerTy());
6536
6537   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6538   SDValue Zero = DAG.getIntPtrConstant(0);
6539   SDValue Four = DAG.getIntPtrConstant(4);
6540   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6541                                Zero, Four);
6542   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6543
6544   // Load the value out, extending it from f32 to f80.
6545   // FIXME: Avoid the extend by constructing the right constant pool?
6546   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6547                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6548                                  MVT::f32, false, false, 4);
6549   // Extend everything to 80 bits to force it to be done on x87.
6550   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6551   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6552 }
6553
6554 std::pair<SDValue,SDValue> X86TargetLowering::
6555 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6556   DebugLoc DL = Op.getDebugLoc();
6557
6558   EVT DstTy = Op.getValueType();
6559
6560   if (!IsSigned) {
6561     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6562     DstTy = MVT::i64;
6563   }
6564
6565   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6566          DstTy.getSimpleVT() >= MVT::i16 &&
6567          "Unknown FP_TO_SINT to lower!");
6568
6569   // These are really Legal.
6570   if (DstTy == MVT::i32 &&
6571       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6572     return std::make_pair(SDValue(), SDValue());
6573   if (Subtarget->is64Bit() &&
6574       DstTy == MVT::i64 &&
6575       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6576     return std::make_pair(SDValue(), SDValue());
6577
6578   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6579   // stack slot.
6580   MachineFunction &MF = DAG.getMachineFunction();
6581   unsigned MemSize = DstTy.getSizeInBits()/8;
6582   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6583   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6584
6585   
6586   
6587   unsigned Opc;
6588   switch (DstTy.getSimpleVT().SimpleTy) {
6589   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6590   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6591   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6592   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6593   }
6594
6595   SDValue Chain = DAG.getEntryNode();
6596   SDValue Value = Op.getOperand(0);
6597   EVT TheVT = Op.getOperand(0).getValueType();
6598   if (isScalarFPTypeInSSEReg(TheVT)) {
6599     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6600     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6601                          MachinePointerInfo::getFixedStack(SSFI),
6602                          false, false, 0);
6603     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6604     SDValue Ops[] = {
6605       Chain, StackSlot, DAG.getValueType(TheVT)
6606     };
6607     
6608     MachineMemOperand *MMO =
6609       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6610                               MachineMemOperand::MOLoad, MemSize, MemSize);
6611     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6612                                     DstTy, MMO);
6613     Chain = Value.getValue(1);
6614     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6615     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6616   }
6617   
6618   MachineMemOperand *MMO =
6619     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6620                             MachineMemOperand::MOStore, MemSize, MemSize);
6621
6622   // Build the FP_TO_INT*_IN_MEM
6623   SDValue Ops[] = { Chain, Value, StackSlot };
6624   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6625                                          Ops, 3, DstTy, MMO);
6626
6627   return std::make_pair(FIST, StackSlot);
6628 }
6629
6630 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6631                                            SelectionDAG &DAG) const {
6632   if (Op.getValueType().isVector())
6633     return SDValue();
6634
6635   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6636   SDValue FIST = Vals.first, StackSlot = Vals.second;
6637   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6638   if (FIST.getNode() == 0) return Op;
6639
6640   // Load the result.
6641   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6642                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6643 }
6644
6645 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6646                                            SelectionDAG &DAG) const {
6647   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6648   SDValue FIST = Vals.first, StackSlot = Vals.second;
6649   assert(FIST.getNode() && "Unexpected failure");
6650
6651   // Load the result.
6652   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6653                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6654 }
6655
6656 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6657                                      SelectionDAG &DAG) const {
6658   LLVMContext *Context = DAG.getContext();
6659   DebugLoc dl = Op.getDebugLoc();
6660   EVT VT = Op.getValueType();
6661   EVT EltVT = VT;
6662   if (VT.isVector())
6663     EltVT = VT.getVectorElementType();
6664   std::vector<Constant*> CV;
6665   if (EltVT == MVT::f64) {
6666     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6667     CV.push_back(C);
6668     CV.push_back(C);
6669   } else {
6670     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6671     CV.push_back(C);
6672     CV.push_back(C);
6673     CV.push_back(C);
6674     CV.push_back(C);
6675   }
6676   Constant *C = ConstantVector::get(CV);
6677   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6678   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6679                              MachinePointerInfo::getConstantPool(),
6680                              false, false, 16);
6681   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6682 }
6683
6684 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6685   LLVMContext *Context = DAG.getContext();
6686   DebugLoc dl = Op.getDebugLoc();
6687   EVT VT = Op.getValueType();
6688   EVT EltVT = VT;
6689   if (VT.isVector())
6690     EltVT = VT.getVectorElementType();
6691   std::vector<Constant*> CV;
6692   if (EltVT == MVT::f64) {
6693     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6694     CV.push_back(C);
6695     CV.push_back(C);
6696   } else {
6697     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6698     CV.push_back(C);
6699     CV.push_back(C);
6700     CV.push_back(C);
6701     CV.push_back(C);
6702   }
6703   Constant *C = ConstantVector::get(CV);
6704   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6705   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6706                              MachinePointerInfo::getConstantPool(),
6707                              false, false, 16);
6708   if (VT.isVector()) {
6709     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6710                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6711                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6712                                 Op.getOperand(0)),
6713                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6714   } else {
6715     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6716   }
6717 }
6718
6719 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6720   LLVMContext *Context = DAG.getContext();
6721   SDValue Op0 = Op.getOperand(0);
6722   SDValue Op1 = Op.getOperand(1);
6723   DebugLoc dl = Op.getDebugLoc();
6724   EVT VT = Op.getValueType();
6725   EVT SrcVT = Op1.getValueType();
6726
6727   // If second operand is smaller, extend it first.
6728   if (SrcVT.bitsLT(VT)) {
6729     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6730     SrcVT = VT;
6731   }
6732   // And if it is bigger, shrink it first.
6733   if (SrcVT.bitsGT(VT)) {
6734     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6735     SrcVT = VT;
6736   }
6737
6738   // At this point the operands and the result should have the same
6739   // type, and that won't be f80 since that is not custom lowered.
6740
6741   // First get the sign bit of second operand.
6742   std::vector<Constant*> CV;
6743   if (SrcVT == MVT::f64) {
6744     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6745     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6746   } else {
6747     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6748     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6749     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6750     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6751   }
6752   Constant *C = ConstantVector::get(CV);
6753   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6754   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6755                               MachinePointerInfo::getConstantPool(),
6756                               false, false, 16);
6757   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6758
6759   // Shift sign bit right or left if the two operands have different types.
6760   if (SrcVT.bitsGT(VT)) {
6761     // Op0 is MVT::f32, Op1 is MVT::f64.
6762     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6763     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6764                           DAG.getConstant(32, MVT::i32));
6765     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6766     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6767                           DAG.getIntPtrConstant(0));
6768   }
6769
6770   // Clear first operand sign bit.
6771   CV.clear();
6772   if (VT == MVT::f64) {
6773     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6774     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6775   } else {
6776     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6777     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6778     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6779     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6780   }
6781   C = ConstantVector::get(CV);
6782   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6783   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6784                               MachinePointerInfo::getConstantPool(),
6785                               false, false, 16);
6786   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6787
6788   // Or the value with the sign bit.
6789   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6790 }
6791
6792 /// Emit nodes that will be selected as "test Op0,Op0", or something
6793 /// equivalent.
6794 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6795                                     SelectionDAG &DAG) const {
6796   DebugLoc dl = Op.getDebugLoc();
6797
6798   // CF and OF aren't always set the way we want. Determine which
6799   // of these we need.
6800   bool NeedCF = false;
6801   bool NeedOF = false;
6802   switch (X86CC) {
6803   default: break;
6804   case X86::COND_A: case X86::COND_AE:
6805   case X86::COND_B: case X86::COND_BE:
6806     NeedCF = true;
6807     break;
6808   case X86::COND_G: case X86::COND_GE:
6809   case X86::COND_L: case X86::COND_LE:
6810   case X86::COND_O: case X86::COND_NO:
6811     NeedOF = true;
6812     break;
6813   }
6814
6815   // See if we can use the EFLAGS value from the operand instead of
6816   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6817   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6818   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6819     // Emit a CMP with 0, which is the TEST pattern.
6820     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6821                        DAG.getConstant(0, Op.getValueType()));
6822
6823   unsigned Opcode = 0;
6824   unsigned NumOperands = 0;
6825   switch (Op.getNode()->getOpcode()) {
6826   case ISD::ADD:
6827     // Due to an isel shortcoming, be conservative if this add is likely to be
6828     // selected as part of a load-modify-store instruction. When the root node
6829     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6830     // uses of other nodes in the match, such as the ADD in this case. This
6831     // leads to the ADD being left around and reselected, with the result being
6832     // two adds in the output.  Alas, even if none our users are stores, that
6833     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6834     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6835     // climbing the DAG back to the root, and it doesn't seem to be worth the
6836     // effort.
6837     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6838            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6839       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6840         goto default_case;
6841
6842     if (ConstantSDNode *C =
6843         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6844       // An add of one will be selected as an INC.
6845       if (C->getAPIntValue() == 1) {
6846         Opcode = X86ISD::INC;
6847         NumOperands = 1;
6848         break;
6849       }
6850
6851       // An add of negative one (subtract of one) will be selected as a DEC.
6852       if (C->getAPIntValue().isAllOnesValue()) {
6853         Opcode = X86ISD::DEC;
6854         NumOperands = 1;
6855         break;
6856       }
6857     }
6858
6859     // Otherwise use a regular EFLAGS-setting add.
6860     Opcode = X86ISD::ADD;
6861     NumOperands = 2;
6862     break;
6863   case ISD::AND: {
6864     // If the primary and result isn't used, don't bother using X86ISD::AND,
6865     // because a TEST instruction will be better.
6866     bool NonFlagUse = false;
6867     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6868            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6869       SDNode *User = *UI;
6870       unsigned UOpNo = UI.getOperandNo();
6871       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6872         // Look pass truncate.
6873         UOpNo = User->use_begin().getOperandNo();
6874         User = *User->use_begin();
6875       }
6876
6877       if (User->getOpcode() != ISD::BRCOND &&
6878           User->getOpcode() != ISD::SETCC &&
6879           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6880         NonFlagUse = true;
6881         break;
6882       }
6883     }
6884
6885     if (!NonFlagUse)
6886       break;
6887   }
6888     // FALL THROUGH
6889   case ISD::SUB:
6890   case ISD::OR:
6891   case ISD::XOR:
6892     // Due to the ISEL shortcoming noted above, be conservative if this op is
6893     // likely to be selected as part of a load-modify-store instruction.
6894     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6895            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6896       if (UI->getOpcode() == ISD::STORE)
6897         goto default_case;
6898
6899     // Otherwise use a regular EFLAGS-setting instruction.
6900     switch (Op.getNode()->getOpcode()) {
6901     default: llvm_unreachable("unexpected operator!");
6902     case ISD::SUB: Opcode = X86ISD::SUB; break;
6903     case ISD::OR:  Opcode = X86ISD::OR;  break;
6904     case ISD::XOR: Opcode = X86ISD::XOR; break;
6905     case ISD::AND: Opcode = X86ISD::AND; break;
6906     }
6907
6908     NumOperands = 2;
6909     break;
6910   case X86ISD::ADD:
6911   case X86ISD::SUB:
6912   case X86ISD::INC:
6913   case X86ISD::DEC:
6914   case X86ISD::OR:
6915   case X86ISD::XOR:
6916   case X86ISD::AND:
6917     return SDValue(Op.getNode(), 1);
6918   default:
6919   default_case:
6920     break;
6921   }
6922
6923   if (Opcode == 0)
6924     // Emit a CMP with 0, which is the TEST pattern.
6925     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6926                        DAG.getConstant(0, Op.getValueType()));
6927
6928   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6929   SmallVector<SDValue, 4> Ops;
6930   for (unsigned i = 0; i != NumOperands; ++i)
6931     Ops.push_back(Op.getOperand(i));
6932
6933   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6934   DAG.ReplaceAllUsesWith(Op, New);
6935   return SDValue(New.getNode(), 1);
6936 }
6937
6938 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6939 /// equivalent.
6940 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6941                                    SelectionDAG &DAG) const {
6942   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6943     if (C->getAPIntValue() == 0)
6944       return EmitTest(Op0, X86CC, DAG);
6945
6946   DebugLoc dl = Op0.getDebugLoc();
6947   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6948 }
6949
6950 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6951 /// if it's possible.
6952 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6953                                      DebugLoc dl, SelectionDAG &DAG) const {
6954   SDValue Op0 = And.getOperand(0);
6955   SDValue Op1 = And.getOperand(1);
6956   if (Op0.getOpcode() == ISD::TRUNCATE)
6957     Op0 = Op0.getOperand(0);
6958   if (Op1.getOpcode() == ISD::TRUNCATE)
6959     Op1 = Op1.getOperand(0);
6960
6961   SDValue LHS, RHS;
6962   if (Op1.getOpcode() == ISD::SHL)
6963     std::swap(Op0, Op1);
6964   if (Op0.getOpcode() == ISD::SHL) {
6965     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6966       if (And00C->getZExtValue() == 1) {
6967         // If we looked past a truncate, check that it's only truncating away
6968         // known zeros.
6969         unsigned BitWidth = Op0.getValueSizeInBits();
6970         unsigned AndBitWidth = And.getValueSizeInBits();
6971         if (BitWidth > AndBitWidth) {
6972           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6973           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6974           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6975             return SDValue();
6976         }
6977         LHS = Op1;
6978         RHS = Op0.getOperand(1);
6979       }
6980   } else if (Op1.getOpcode() == ISD::Constant) {
6981     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6982     SDValue AndLHS = Op0;
6983     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6984       LHS = AndLHS.getOperand(0);
6985       RHS = AndLHS.getOperand(1);
6986     }
6987   }
6988
6989   if (LHS.getNode()) {
6990     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6991     // instruction.  Since the shift amount is in-range-or-undefined, we know
6992     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6993     // the encoding for the i16 version is larger than the i32 version.
6994     // Also promote i16 to i32 for performance / code size reason.
6995     if (LHS.getValueType() == MVT::i8 ||
6996         LHS.getValueType() == MVT::i16)
6997       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6998
6999     // If the operand types disagree, extend the shift amount to match.  Since
7000     // BT ignores high bits (like shifts) we can use anyextend.
7001     if (LHS.getValueType() != RHS.getValueType())
7002       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7003
7004     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7005     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7006     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7007                        DAG.getConstant(Cond, MVT::i8), BT);
7008   }
7009
7010   return SDValue();
7011 }
7012
7013 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7014   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7015   SDValue Op0 = Op.getOperand(0);
7016   SDValue Op1 = Op.getOperand(1);
7017   DebugLoc dl = Op.getDebugLoc();
7018   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7019
7020   // Optimize to BT if possible.
7021   // Lower (X & (1 << N)) == 0 to BT(X, N).
7022   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7023   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7024   if (Op0.getOpcode() == ISD::AND &&
7025       Op0.hasOneUse() &&
7026       Op1.getOpcode() == ISD::Constant &&
7027       cast<ConstantSDNode>(Op1)->isNullValue() &&
7028       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7029     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7030     if (NewSetCC.getNode())
7031       return NewSetCC;
7032   }
7033
7034   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7035   if (Op0.getOpcode() == X86ISD::SETCC &&
7036       Op1.getOpcode() == ISD::Constant &&
7037       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7038        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7039       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7040     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7041     bool Invert = (CC == ISD::SETNE) ^
7042       cast<ConstantSDNode>(Op1)->isNullValue();
7043     if (Invert)
7044       CCode = X86::GetOppositeBranchCondition(CCode);
7045     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7046                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7047   }
7048
7049   bool isFP = Op1.getValueType().isFloatingPoint();
7050   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7051   if (X86CC == X86::COND_INVALID)
7052     return SDValue();
7053
7054   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7055
7056   // Use sbb x, x to materialize carry bit into a GPR.
7057   if (X86CC == X86::COND_B)
7058     return DAG.getNode(ISD::AND, dl, MVT::i8,
7059                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7060                                    DAG.getConstant(X86CC, MVT::i8), Cond),
7061                        DAG.getConstant(1, MVT::i8));
7062
7063   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7064                      DAG.getConstant(X86CC, MVT::i8), Cond);
7065 }
7066
7067 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7068   SDValue Cond;
7069   SDValue Op0 = Op.getOperand(0);
7070   SDValue Op1 = Op.getOperand(1);
7071   SDValue CC = Op.getOperand(2);
7072   EVT VT = Op.getValueType();
7073   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7074   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7075   DebugLoc dl = Op.getDebugLoc();
7076
7077   if (isFP) {
7078     unsigned SSECC = 8;
7079     EVT VT0 = Op0.getValueType();
7080     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7081     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7082     bool Swap = false;
7083
7084     switch (SetCCOpcode) {
7085     default: break;
7086     case ISD::SETOEQ:
7087     case ISD::SETEQ:  SSECC = 0; break;
7088     case ISD::SETOGT:
7089     case ISD::SETGT: Swap = true; // Fallthrough
7090     case ISD::SETLT:
7091     case ISD::SETOLT: SSECC = 1; break;
7092     case ISD::SETOGE:
7093     case ISD::SETGE: Swap = true; // Fallthrough
7094     case ISD::SETLE:
7095     case ISD::SETOLE: SSECC = 2; break;
7096     case ISD::SETUO:  SSECC = 3; break;
7097     case ISD::SETUNE:
7098     case ISD::SETNE:  SSECC = 4; break;
7099     case ISD::SETULE: Swap = true;
7100     case ISD::SETUGE: SSECC = 5; break;
7101     case ISD::SETULT: Swap = true;
7102     case ISD::SETUGT: SSECC = 6; break;
7103     case ISD::SETO:   SSECC = 7; break;
7104     }
7105     if (Swap)
7106       std::swap(Op0, Op1);
7107
7108     // In the two special cases we can't handle, emit two comparisons.
7109     if (SSECC == 8) {
7110       if (SetCCOpcode == ISD::SETUEQ) {
7111         SDValue UNORD, EQ;
7112         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7113         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7114         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7115       }
7116       else if (SetCCOpcode == ISD::SETONE) {
7117         SDValue ORD, NEQ;
7118         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7119         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7120         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7121       }
7122       llvm_unreachable("Illegal FP comparison");
7123     }
7124     // Handle all other FP comparisons here.
7125     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7126   }
7127
7128   // We are handling one of the integer comparisons here.  Since SSE only has
7129   // GT and EQ comparisons for integer, swapping operands and multiple
7130   // operations may be required for some comparisons.
7131   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7132   bool Swap = false, Invert = false, FlipSigns = false;
7133
7134   switch (VT.getSimpleVT().SimpleTy) {
7135   default: break;
7136   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7137   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7138   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7139   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7140   }
7141
7142   switch (SetCCOpcode) {
7143   default: break;
7144   case ISD::SETNE:  Invert = true;
7145   case ISD::SETEQ:  Opc = EQOpc; break;
7146   case ISD::SETLT:  Swap = true;
7147   case ISD::SETGT:  Opc = GTOpc; break;
7148   case ISD::SETGE:  Swap = true;
7149   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7150   case ISD::SETULT: Swap = true;
7151   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7152   case ISD::SETUGE: Swap = true;
7153   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7154   }
7155   if (Swap)
7156     std::swap(Op0, Op1);
7157
7158   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7159   // bits of the inputs before performing those operations.
7160   if (FlipSigns) {
7161     EVT EltVT = VT.getVectorElementType();
7162     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7163                                       EltVT);
7164     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7165     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7166                                     SignBits.size());
7167     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7168     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7169   }
7170
7171   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7172
7173   // If the logical-not of the result is required, perform that now.
7174   if (Invert)
7175     Result = DAG.getNOT(dl, Result, VT);
7176
7177   return Result;
7178 }
7179
7180 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7181 static bool isX86LogicalCmp(SDValue Op) {
7182   unsigned Opc = Op.getNode()->getOpcode();
7183   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7184     return true;
7185   if (Op.getResNo() == 1 &&
7186       (Opc == X86ISD::ADD ||
7187        Opc == X86ISD::SUB ||
7188        Opc == X86ISD::SMUL ||
7189        Opc == X86ISD::UMUL ||
7190        Opc == X86ISD::INC ||
7191        Opc == X86ISD::DEC ||
7192        Opc == X86ISD::OR ||
7193        Opc == X86ISD::XOR ||
7194        Opc == X86ISD::AND))
7195     return true;
7196
7197   return false;
7198 }
7199
7200 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7201   bool addTest = true;
7202   SDValue Cond  = Op.getOperand(0);
7203   DebugLoc dl = Op.getDebugLoc();
7204   SDValue CC;
7205
7206   if (Cond.getOpcode() == ISD::SETCC) {
7207     SDValue NewCond = LowerSETCC(Cond, DAG);
7208     if (NewCond.getNode())
7209       Cond = NewCond;
7210   }
7211
7212   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7213   SDValue Op1 = Op.getOperand(1);
7214   SDValue Op2 = Op.getOperand(2);
7215   if (Cond.getOpcode() == X86ISD::SETCC &&
7216       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7217     SDValue Cmp = Cond.getOperand(1);
7218     if (Cmp.getOpcode() == X86ISD::CMP) {
7219       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7220       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7221       ConstantSDNode *RHSC =
7222         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7223       if (N1C && N1C->isAllOnesValue() &&
7224           N2C && N2C->isNullValue() &&
7225           RHSC && RHSC->isNullValue()) {
7226         SDValue CmpOp0 = Cmp.getOperand(0);
7227         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7228                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7229         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7230                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7231       }
7232     }
7233   }
7234
7235   // Look pass (and (setcc_carry (cmp ...)), 1).
7236   if (Cond.getOpcode() == ISD::AND &&
7237       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7238     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7239     if (C && C->getAPIntValue() == 1) 
7240       Cond = Cond.getOperand(0);
7241   }
7242
7243   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7244   // setting operand in place of the X86ISD::SETCC.
7245   if (Cond.getOpcode() == X86ISD::SETCC ||
7246       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7247     CC = Cond.getOperand(0);
7248
7249     SDValue Cmp = Cond.getOperand(1);
7250     unsigned Opc = Cmp.getOpcode();
7251     EVT VT = Op.getValueType();
7252
7253     bool IllegalFPCMov = false;
7254     if (VT.isFloatingPoint() && !VT.isVector() &&
7255         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7256       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7257
7258     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7259         Opc == X86ISD::BT) { // FIXME
7260       Cond = Cmp;
7261       addTest = false;
7262     }
7263   }
7264
7265   if (addTest) {
7266     // Look pass the truncate.
7267     if (Cond.getOpcode() == ISD::TRUNCATE)
7268       Cond = Cond.getOperand(0);
7269
7270     // We know the result of AND is compared against zero. Try to match
7271     // it to BT.
7272     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7273       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7274       if (NewSetCC.getNode()) {
7275         CC = NewSetCC.getOperand(0);
7276         Cond = NewSetCC.getOperand(1);
7277         addTest = false;
7278       }
7279     }
7280   }
7281
7282   if (addTest) {
7283     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7284     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7285   }
7286
7287   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7288   // condition is true.
7289   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7290   SDValue Ops[] = { Op2, Op1, CC, Cond };
7291   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7292 }
7293
7294 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7295 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7296 // from the AND / OR.
7297 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7298   Opc = Op.getOpcode();
7299   if (Opc != ISD::OR && Opc != ISD::AND)
7300     return false;
7301   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7302           Op.getOperand(0).hasOneUse() &&
7303           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7304           Op.getOperand(1).hasOneUse());
7305 }
7306
7307 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7308 // 1 and that the SETCC node has a single use.
7309 static bool isXor1OfSetCC(SDValue Op) {
7310   if (Op.getOpcode() != ISD::XOR)
7311     return false;
7312   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7313   if (N1C && N1C->getAPIntValue() == 1) {
7314     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7315       Op.getOperand(0).hasOneUse();
7316   }
7317   return false;
7318 }
7319
7320 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7321   bool addTest = true;
7322   SDValue Chain = Op.getOperand(0);
7323   SDValue Cond  = Op.getOperand(1);
7324   SDValue Dest  = Op.getOperand(2);
7325   DebugLoc dl = Op.getDebugLoc();
7326   SDValue CC;
7327
7328   if (Cond.getOpcode() == ISD::SETCC) {
7329     SDValue NewCond = LowerSETCC(Cond, DAG);
7330     if (NewCond.getNode())
7331       Cond = NewCond;
7332   }
7333 #if 0
7334   // FIXME: LowerXALUO doesn't handle these!!
7335   else if (Cond.getOpcode() == X86ISD::ADD  ||
7336            Cond.getOpcode() == X86ISD::SUB  ||
7337            Cond.getOpcode() == X86ISD::SMUL ||
7338            Cond.getOpcode() == X86ISD::UMUL)
7339     Cond = LowerXALUO(Cond, DAG);
7340 #endif
7341
7342   // Look pass (and (setcc_carry (cmp ...)), 1).
7343   if (Cond.getOpcode() == ISD::AND &&
7344       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7345     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7346     if (C && C->getAPIntValue() == 1) 
7347       Cond = Cond.getOperand(0);
7348   }
7349
7350   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7351   // setting operand in place of the X86ISD::SETCC.
7352   if (Cond.getOpcode() == X86ISD::SETCC ||
7353       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7354     CC = Cond.getOperand(0);
7355
7356     SDValue Cmp = Cond.getOperand(1);
7357     unsigned Opc = Cmp.getOpcode();
7358     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7359     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7360       Cond = Cmp;
7361       addTest = false;
7362     } else {
7363       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7364       default: break;
7365       case X86::COND_O:
7366       case X86::COND_B:
7367         // These can only come from an arithmetic instruction with overflow,
7368         // e.g. SADDO, UADDO.
7369         Cond = Cond.getNode()->getOperand(1);
7370         addTest = false;
7371         break;
7372       }
7373     }
7374   } else {
7375     unsigned CondOpc;
7376     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7377       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7378       if (CondOpc == ISD::OR) {
7379         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7380         // two branches instead of an explicit OR instruction with a
7381         // separate test.
7382         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7383             isX86LogicalCmp(Cmp)) {
7384           CC = Cond.getOperand(0).getOperand(0);
7385           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7386                               Chain, Dest, CC, Cmp);
7387           CC = Cond.getOperand(1).getOperand(0);
7388           Cond = Cmp;
7389           addTest = false;
7390         }
7391       } else { // ISD::AND
7392         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7393         // two branches instead of an explicit AND instruction with a
7394         // separate test. However, we only do this if this block doesn't
7395         // have a fall-through edge, because this requires an explicit
7396         // jmp when the condition is false.
7397         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7398             isX86LogicalCmp(Cmp) &&
7399             Op.getNode()->hasOneUse()) {
7400           X86::CondCode CCode =
7401             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7402           CCode = X86::GetOppositeBranchCondition(CCode);
7403           CC = DAG.getConstant(CCode, MVT::i8);
7404           SDNode *User = *Op.getNode()->use_begin();
7405           // Look for an unconditional branch following this conditional branch.
7406           // We need this because we need to reverse the successors in order
7407           // to implement FCMP_OEQ.
7408           if (User->getOpcode() == ISD::BR) {
7409             SDValue FalseBB = User->getOperand(1);
7410             SDNode *NewBR =
7411               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7412             assert(NewBR == User);
7413             (void)NewBR;
7414             Dest = FalseBB;
7415
7416             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7417                                 Chain, Dest, CC, Cmp);
7418             X86::CondCode CCode =
7419               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7420             CCode = X86::GetOppositeBranchCondition(CCode);
7421             CC = DAG.getConstant(CCode, MVT::i8);
7422             Cond = Cmp;
7423             addTest = false;
7424           }
7425         }
7426       }
7427     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7428       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7429       // It should be transformed during dag combiner except when the condition
7430       // is set by a arithmetics with overflow node.
7431       X86::CondCode CCode =
7432         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7433       CCode = X86::GetOppositeBranchCondition(CCode);
7434       CC = DAG.getConstant(CCode, MVT::i8);
7435       Cond = Cond.getOperand(0).getOperand(1);
7436       addTest = false;
7437     }
7438   }
7439
7440   if (addTest) {
7441     // Look pass the truncate.
7442     if (Cond.getOpcode() == ISD::TRUNCATE)
7443       Cond = Cond.getOperand(0);
7444
7445     // We know the result of AND is compared against zero. Try to match
7446     // it to BT.
7447     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7448       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7449       if (NewSetCC.getNode()) {
7450         CC = NewSetCC.getOperand(0);
7451         Cond = NewSetCC.getOperand(1);
7452         addTest = false;
7453       }
7454     }
7455   }
7456
7457   if (addTest) {
7458     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7459     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7460   }
7461   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7462                      Chain, Dest, CC, Cond);
7463 }
7464
7465
7466 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7467 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7468 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7469 // that the guard pages used by the OS virtual memory manager are allocated in
7470 // correct sequence.
7471 SDValue
7472 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7473                                            SelectionDAG &DAG) const {
7474   assert(Subtarget->isTargetCygMing() &&
7475          "This should be used only on Cygwin/Mingw targets");
7476   DebugLoc dl = Op.getDebugLoc();
7477
7478   // Get the inputs.
7479   SDValue Chain = Op.getOperand(0);
7480   SDValue Size  = Op.getOperand(1);
7481   // FIXME: Ensure alignment here
7482
7483   SDValue Flag;
7484
7485   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7486
7487   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7488   Flag = Chain.getValue(1);
7489
7490   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7491
7492   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7493   Flag = Chain.getValue(1);
7494
7495   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7496
7497   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7498   return DAG.getMergeValues(Ops1, 2, dl);
7499 }
7500
7501 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7502   MachineFunction &MF = DAG.getMachineFunction();
7503   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7504
7505   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7506   DebugLoc DL = Op.getDebugLoc();
7507
7508   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7509     // vastart just stores the address of the VarArgsFrameIndex slot into the
7510     // memory location argument.
7511     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7512                                    getPointerTy());
7513     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7514                         MachinePointerInfo(SV), false, false, 0);
7515   }
7516
7517   // __va_list_tag:
7518   //   gp_offset         (0 - 6 * 8)
7519   //   fp_offset         (48 - 48 + 8 * 16)
7520   //   overflow_arg_area (point to parameters coming in memory).
7521   //   reg_save_area
7522   SmallVector<SDValue, 8> MemOps;
7523   SDValue FIN = Op.getOperand(1);
7524   // Store gp_offset
7525   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7526                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7527                                                MVT::i32),
7528                                FIN, MachinePointerInfo(SV), false, false, 0);
7529   MemOps.push_back(Store);
7530
7531   // Store fp_offset
7532   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7533                     FIN, DAG.getIntPtrConstant(4));
7534   Store = DAG.getStore(Op.getOperand(0), DL,
7535                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7536                                        MVT::i32),
7537                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7538   MemOps.push_back(Store);
7539
7540   // Store ptr to overflow_arg_area
7541   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7542                     FIN, DAG.getIntPtrConstant(4));
7543   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7544                                     getPointerTy());
7545   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7546                        MachinePointerInfo(SV, 8),
7547                        false, false, 0);
7548   MemOps.push_back(Store);
7549
7550   // Store ptr to reg_save_area.
7551   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7552                     FIN, DAG.getIntPtrConstant(8));
7553   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7554                                     getPointerTy());
7555   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7556                        MachinePointerInfo(SV, 16), false, false, 0);
7557   MemOps.push_back(Store);
7558   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7559                      &MemOps[0], MemOps.size());
7560 }
7561
7562 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7563   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7564   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7565
7566   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7567   return SDValue();
7568 }
7569
7570 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7571   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7572   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7573   SDValue Chain = Op.getOperand(0);
7574   SDValue DstPtr = Op.getOperand(1);
7575   SDValue SrcPtr = Op.getOperand(2);
7576   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7577   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7578   DebugLoc DL = Op.getDebugLoc();
7579
7580   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7581                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7582                        false, 
7583                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7584 }
7585
7586 SDValue
7587 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7588   DebugLoc dl = Op.getDebugLoc();
7589   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7590   switch (IntNo) {
7591   default: return SDValue();    // Don't custom lower most intrinsics.
7592   // Comparison intrinsics.
7593   case Intrinsic::x86_sse_comieq_ss:
7594   case Intrinsic::x86_sse_comilt_ss:
7595   case Intrinsic::x86_sse_comile_ss:
7596   case Intrinsic::x86_sse_comigt_ss:
7597   case Intrinsic::x86_sse_comige_ss:
7598   case Intrinsic::x86_sse_comineq_ss:
7599   case Intrinsic::x86_sse_ucomieq_ss:
7600   case Intrinsic::x86_sse_ucomilt_ss:
7601   case Intrinsic::x86_sse_ucomile_ss:
7602   case Intrinsic::x86_sse_ucomigt_ss:
7603   case Intrinsic::x86_sse_ucomige_ss:
7604   case Intrinsic::x86_sse_ucomineq_ss:
7605   case Intrinsic::x86_sse2_comieq_sd:
7606   case Intrinsic::x86_sse2_comilt_sd:
7607   case Intrinsic::x86_sse2_comile_sd:
7608   case Intrinsic::x86_sse2_comigt_sd:
7609   case Intrinsic::x86_sse2_comige_sd:
7610   case Intrinsic::x86_sse2_comineq_sd:
7611   case Intrinsic::x86_sse2_ucomieq_sd:
7612   case Intrinsic::x86_sse2_ucomilt_sd:
7613   case Intrinsic::x86_sse2_ucomile_sd:
7614   case Intrinsic::x86_sse2_ucomigt_sd:
7615   case Intrinsic::x86_sse2_ucomige_sd:
7616   case Intrinsic::x86_sse2_ucomineq_sd: {
7617     unsigned Opc = 0;
7618     ISD::CondCode CC = ISD::SETCC_INVALID;
7619     switch (IntNo) {
7620     default: break;
7621     case Intrinsic::x86_sse_comieq_ss:
7622     case Intrinsic::x86_sse2_comieq_sd:
7623       Opc = X86ISD::COMI;
7624       CC = ISD::SETEQ;
7625       break;
7626     case Intrinsic::x86_sse_comilt_ss:
7627     case Intrinsic::x86_sse2_comilt_sd:
7628       Opc = X86ISD::COMI;
7629       CC = ISD::SETLT;
7630       break;
7631     case Intrinsic::x86_sse_comile_ss:
7632     case Intrinsic::x86_sse2_comile_sd:
7633       Opc = X86ISD::COMI;
7634       CC = ISD::SETLE;
7635       break;
7636     case Intrinsic::x86_sse_comigt_ss:
7637     case Intrinsic::x86_sse2_comigt_sd:
7638       Opc = X86ISD::COMI;
7639       CC = ISD::SETGT;
7640       break;
7641     case Intrinsic::x86_sse_comige_ss:
7642     case Intrinsic::x86_sse2_comige_sd:
7643       Opc = X86ISD::COMI;
7644       CC = ISD::SETGE;
7645       break;
7646     case Intrinsic::x86_sse_comineq_ss:
7647     case Intrinsic::x86_sse2_comineq_sd:
7648       Opc = X86ISD::COMI;
7649       CC = ISD::SETNE;
7650       break;
7651     case Intrinsic::x86_sse_ucomieq_ss:
7652     case Intrinsic::x86_sse2_ucomieq_sd:
7653       Opc = X86ISD::UCOMI;
7654       CC = ISD::SETEQ;
7655       break;
7656     case Intrinsic::x86_sse_ucomilt_ss:
7657     case Intrinsic::x86_sse2_ucomilt_sd:
7658       Opc = X86ISD::UCOMI;
7659       CC = ISD::SETLT;
7660       break;
7661     case Intrinsic::x86_sse_ucomile_ss:
7662     case Intrinsic::x86_sse2_ucomile_sd:
7663       Opc = X86ISD::UCOMI;
7664       CC = ISD::SETLE;
7665       break;
7666     case Intrinsic::x86_sse_ucomigt_ss:
7667     case Intrinsic::x86_sse2_ucomigt_sd:
7668       Opc = X86ISD::UCOMI;
7669       CC = ISD::SETGT;
7670       break;
7671     case Intrinsic::x86_sse_ucomige_ss:
7672     case Intrinsic::x86_sse2_ucomige_sd:
7673       Opc = X86ISD::UCOMI;
7674       CC = ISD::SETGE;
7675       break;
7676     case Intrinsic::x86_sse_ucomineq_ss:
7677     case Intrinsic::x86_sse2_ucomineq_sd:
7678       Opc = X86ISD::UCOMI;
7679       CC = ISD::SETNE;
7680       break;
7681     }
7682
7683     SDValue LHS = Op.getOperand(1);
7684     SDValue RHS = Op.getOperand(2);
7685     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7686     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7687     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7688     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7689                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7690     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7691   }
7692   // ptest and testp intrinsics. The intrinsic these come from are designed to
7693   // return an integer value, not just an instruction so lower it to the ptest
7694   // or testp pattern and a setcc for the result.
7695   case Intrinsic::x86_sse41_ptestz:
7696   case Intrinsic::x86_sse41_ptestc:
7697   case Intrinsic::x86_sse41_ptestnzc:
7698   case Intrinsic::x86_avx_ptestz_256:
7699   case Intrinsic::x86_avx_ptestc_256:
7700   case Intrinsic::x86_avx_ptestnzc_256:
7701   case Intrinsic::x86_avx_vtestz_ps:
7702   case Intrinsic::x86_avx_vtestc_ps:
7703   case Intrinsic::x86_avx_vtestnzc_ps:
7704   case Intrinsic::x86_avx_vtestz_pd:
7705   case Intrinsic::x86_avx_vtestc_pd:
7706   case Intrinsic::x86_avx_vtestnzc_pd:
7707   case Intrinsic::x86_avx_vtestz_ps_256:
7708   case Intrinsic::x86_avx_vtestc_ps_256:
7709   case Intrinsic::x86_avx_vtestnzc_ps_256:
7710   case Intrinsic::x86_avx_vtestz_pd_256:
7711   case Intrinsic::x86_avx_vtestc_pd_256:
7712   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7713     bool IsTestPacked = false;
7714     unsigned X86CC = 0;
7715     switch (IntNo) {
7716     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7717     case Intrinsic::x86_avx_vtestz_ps:
7718     case Intrinsic::x86_avx_vtestz_pd:
7719     case Intrinsic::x86_avx_vtestz_ps_256:
7720     case Intrinsic::x86_avx_vtestz_pd_256:
7721       IsTestPacked = true; // Fallthrough
7722     case Intrinsic::x86_sse41_ptestz:
7723     case Intrinsic::x86_avx_ptestz_256:
7724       // ZF = 1
7725       X86CC = X86::COND_E;
7726       break;
7727     case Intrinsic::x86_avx_vtestc_ps:
7728     case Intrinsic::x86_avx_vtestc_pd:
7729     case Intrinsic::x86_avx_vtestc_ps_256:
7730     case Intrinsic::x86_avx_vtestc_pd_256:
7731       IsTestPacked = true; // Fallthrough
7732     case Intrinsic::x86_sse41_ptestc:
7733     case Intrinsic::x86_avx_ptestc_256:
7734       // CF = 1
7735       X86CC = X86::COND_B;
7736       break;
7737     case Intrinsic::x86_avx_vtestnzc_ps:
7738     case Intrinsic::x86_avx_vtestnzc_pd:
7739     case Intrinsic::x86_avx_vtestnzc_ps_256:
7740     case Intrinsic::x86_avx_vtestnzc_pd_256:
7741       IsTestPacked = true; // Fallthrough
7742     case Intrinsic::x86_sse41_ptestnzc:
7743     case Intrinsic::x86_avx_ptestnzc_256:
7744       // ZF and CF = 0
7745       X86CC = X86::COND_A;
7746       break;
7747     }
7748
7749     SDValue LHS = Op.getOperand(1);
7750     SDValue RHS = Op.getOperand(2);
7751     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7752     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7753     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7754     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7755     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7756   }
7757
7758   // Fix vector shift instructions where the last operand is a non-immediate
7759   // i32 value.
7760   case Intrinsic::x86_sse2_pslli_w:
7761   case Intrinsic::x86_sse2_pslli_d:
7762   case Intrinsic::x86_sse2_pslli_q:
7763   case Intrinsic::x86_sse2_psrli_w:
7764   case Intrinsic::x86_sse2_psrli_d:
7765   case Intrinsic::x86_sse2_psrli_q:
7766   case Intrinsic::x86_sse2_psrai_w:
7767   case Intrinsic::x86_sse2_psrai_d:
7768   case Intrinsic::x86_mmx_pslli_w:
7769   case Intrinsic::x86_mmx_pslli_d:
7770   case Intrinsic::x86_mmx_pslli_q:
7771   case Intrinsic::x86_mmx_psrli_w:
7772   case Intrinsic::x86_mmx_psrli_d:
7773   case Intrinsic::x86_mmx_psrli_q:
7774   case Intrinsic::x86_mmx_psrai_w:
7775   case Intrinsic::x86_mmx_psrai_d: {
7776     SDValue ShAmt = Op.getOperand(2);
7777     if (isa<ConstantSDNode>(ShAmt))
7778       return SDValue();
7779
7780     unsigned NewIntNo = 0;
7781     EVT ShAmtVT = MVT::v4i32;
7782     switch (IntNo) {
7783     case Intrinsic::x86_sse2_pslli_w:
7784       NewIntNo = Intrinsic::x86_sse2_psll_w;
7785       break;
7786     case Intrinsic::x86_sse2_pslli_d:
7787       NewIntNo = Intrinsic::x86_sse2_psll_d;
7788       break;
7789     case Intrinsic::x86_sse2_pslli_q:
7790       NewIntNo = Intrinsic::x86_sse2_psll_q;
7791       break;
7792     case Intrinsic::x86_sse2_psrli_w:
7793       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7794       break;
7795     case Intrinsic::x86_sse2_psrli_d:
7796       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7797       break;
7798     case Intrinsic::x86_sse2_psrli_q:
7799       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7800       break;
7801     case Intrinsic::x86_sse2_psrai_w:
7802       NewIntNo = Intrinsic::x86_sse2_psra_w;
7803       break;
7804     case Intrinsic::x86_sse2_psrai_d:
7805       NewIntNo = Intrinsic::x86_sse2_psra_d;
7806       break;
7807     default: {
7808       ShAmtVT = MVT::v2i32;
7809       switch (IntNo) {
7810       case Intrinsic::x86_mmx_pslli_w:
7811         NewIntNo = Intrinsic::x86_mmx_psll_w;
7812         break;
7813       case Intrinsic::x86_mmx_pslli_d:
7814         NewIntNo = Intrinsic::x86_mmx_psll_d;
7815         break;
7816       case Intrinsic::x86_mmx_pslli_q:
7817         NewIntNo = Intrinsic::x86_mmx_psll_q;
7818         break;
7819       case Intrinsic::x86_mmx_psrli_w:
7820         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7821         break;
7822       case Intrinsic::x86_mmx_psrli_d:
7823         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7824         break;
7825       case Intrinsic::x86_mmx_psrli_q:
7826         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7827         break;
7828       case Intrinsic::x86_mmx_psrai_w:
7829         NewIntNo = Intrinsic::x86_mmx_psra_w;
7830         break;
7831       case Intrinsic::x86_mmx_psrai_d:
7832         NewIntNo = Intrinsic::x86_mmx_psra_d;
7833         break;
7834       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7835       }
7836       break;
7837     }
7838     }
7839
7840     // The vector shift intrinsics with scalars uses 32b shift amounts but
7841     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7842     // to be zero.
7843     SDValue ShOps[4];
7844     ShOps[0] = ShAmt;
7845     ShOps[1] = DAG.getConstant(0, MVT::i32);
7846     if (ShAmtVT == MVT::v4i32) {
7847       ShOps[2] = DAG.getUNDEF(MVT::i32);
7848       ShOps[3] = DAG.getUNDEF(MVT::i32);
7849       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7850     } else {
7851       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7852 // FIXME this must be lowered to get rid of the invalid type.
7853     }
7854
7855     EVT VT = Op.getValueType();
7856     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7857     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7858                        DAG.getConstant(NewIntNo, MVT::i32),
7859                        Op.getOperand(1), ShAmt);
7860   }
7861   }
7862 }
7863
7864 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7865                                            SelectionDAG &DAG) const {
7866   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7867   MFI->setReturnAddressIsTaken(true);
7868
7869   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7870   DebugLoc dl = Op.getDebugLoc();
7871
7872   if (Depth > 0) {
7873     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7874     SDValue Offset =
7875       DAG.getConstant(TD->getPointerSize(),
7876                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7877     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7878                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7879                                    FrameAddr, Offset),
7880                        MachinePointerInfo(), false, false, 0);
7881   }
7882
7883   // Just load the return address.
7884   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7885   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7886                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7887 }
7888
7889 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7890   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7891   MFI->setFrameAddressIsTaken(true);
7892
7893   EVT VT = Op.getValueType();
7894   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7895   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7896   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7897   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7898   while (Depth--)
7899     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7900                             MachinePointerInfo(),
7901                             false, false, 0);
7902   return FrameAddr;
7903 }
7904
7905 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7906                                                      SelectionDAG &DAG) const {
7907   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7908 }
7909
7910 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7911   MachineFunction &MF = DAG.getMachineFunction();
7912   SDValue Chain     = Op.getOperand(0);
7913   SDValue Offset    = Op.getOperand(1);
7914   SDValue Handler   = Op.getOperand(2);
7915   DebugLoc dl       = Op.getDebugLoc();
7916
7917   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7918                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7919                                      getPointerTy());
7920   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7921
7922   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7923                                   DAG.getIntPtrConstant(TD->getPointerSize()));
7924   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7925   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
7926                        false, false, 0);
7927   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7928   MF.getRegInfo().addLiveOut(StoreAddrReg);
7929
7930   return DAG.getNode(X86ISD::EH_RETURN, dl,
7931                      MVT::Other,
7932                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7933 }
7934
7935 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7936                                              SelectionDAG &DAG) const {
7937   SDValue Root = Op.getOperand(0);
7938   SDValue Trmp = Op.getOperand(1); // trampoline
7939   SDValue FPtr = Op.getOperand(2); // nested function
7940   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7941   DebugLoc dl  = Op.getDebugLoc();
7942
7943   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7944
7945   if (Subtarget->is64Bit()) {
7946     SDValue OutChains[6];
7947
7948     // Large code-model.
7949     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7950     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7951
7952     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7953     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7954
7955     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7956
7957     // Load the pointer to the nested function into R11.
7958     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7959     SDValue Addr = Trmp;
7960     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7961                                 Addr, MachinePointerInfo(TrmpAddr),
7962                                 false, false, 0);
7963
7964     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7965                        DAG.getConstant(2, MVT::i64));
7966     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
7967                                 MachinePointerInfo(TrmpAddr, 2),
7968                                 false, false, 2);
7969
7970     // Load the 'nest' parameter value into R10.
7971     // R10 is specified in X86CallingConv.td
7972     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7973     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7974                        DAG.getConstant(10, MVT::i64));
7975     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7976                                 Addr, MachinePointerInfo(TrmpAddr, 10),
7977                                 false, false, 0);
7978
7979     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7980                        DAG.getConstant(12, MVT::i64));
7981     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
7982                                 MachinePointerInfo(TrmpAddr, 12),
7983                                 false, false, 2);
7984
7985     // Jump to the nested function.
7986     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7987     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7988                        DAG.getConstant(20, MVT::i64));
7989     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7990                                 Addr, MachinePointerInfo(TrmpAddr, 20),
7991                                 false, false, 0);
7992
7993     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7994     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7995                        DAG.getConstant(22, MVT::i64));
7996     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7997                                 MachinePointerInfo(TrmpAddr, 22),
7998                                 false, false, 0);
7999
8000     SDValue Ops[] =
8001       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8002     return DAG.getMergeValues(Ops, 2, dl);
8003   } else {
8004     const Function *Func =
8005       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8006     CallingConv::ID CC = Func->getCallingConv();
8007     unsigned NestReg;
8008
8009     switch (CC) {
8010     default:
8011       llvm_unreachable("Unsupported calling convention");
8012     case CallingConv::C:
8013     case CallingConv::X86_StdCall: {
8014       // Pass 'nest' parameter in ECX.
8015       // Must be kept in sync with X86CallingConv.td
8016       NestReg = X86::ECX;
8017
8018       // Check that ECX wasn't needed by an 'inreg' parameter.
8019       const FunctionType *FTy = Func->getFunctionType();
8020       const AttrListPtr &Attrs = Func->getAttributes();
8021
8022       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8023         unsigned InRegCount = 0;
8024         unsigned Idx = 1;
8025
8026         for (FunctionType::param_iterator I = FTy->param_begin(),
8027              E = FTy->param_end(); I != E; ++I, ++Idx)
8028           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8029             // FIXME: should only count parameters that are lowered to integers.
8030             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8031
8032         if (InRegCount > 2) {
8033           report_fatal_error("Nest register in use - reduce number of inreg"
8034                              " parameters!");
8035         }
8036       }
8037       break;
8038     }
8039     case CallingConv::X86_FastCall:
8040     case CallingConv::X86_ThisCall:
8041     case CallingConv::Fast:
8042       // Pass 'nest' parameter in EAX.
8043       // Must be kept in sync with X86CallingConv.td
8044       NestReg = X86::EAX;
8045       break;
8046     }
8047
8048     SDValue OutChains[4];
8049     SDValue Addr, Disp;
8050
8051     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8052                        DAG.getConstant(10, MVT::i32));
8053     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8054
8055     // This is storing the opcode for MOV32ri.
8056     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8057     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8058     OutChains[0] = DAG.getStore(Root, dl,
8059                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8060                                 Trmp, MachinePointerInfo(TrmpAddr),
8061                                 false, false, 0);
8062
8063     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8064                        DAG.getConstant(1, MVT::i32));
8065     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8066                                 MachinePointerInfo(TrmpAddr, 1),
8067                                 false, false, 1);
8068
8069     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8070     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8071                        DAG.getConstant(5, MVT::i32));
8072     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8073                                 MachinePointerInfo(TrmpAddr, 5),
8074                                 false, false, 1);
8075
8076     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8077                        DAG.getConstant(6, MVT::i32));
8078     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8079                                 MachinePointerInfo(TrmpAddr, 6),
8080                                 false, false, 1);
8081
8082     SDValue Ops[] =
8083       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8084     return DAG.getMergeValues(Ops, 2, dl);
8085   }
8086 }
8087
8088 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8089                                             SelectionDAG &DAG) const {
8090   /*
8091    The rounding mode is in bits 11:10 of FPSR, and has the following
8092    settings:
8093      00 Round to nearest
8094      01 Round to -inf
8095      10 Round to +inf
8096      11 Round to 0
8097
8098   FLT_ROUNDS, on the other hand, expects the following:
8099     -1 Undefined
8100      0 Round to 0
8101      1 Round to nearest
8102      2 Round to +inf
8103      3 Round to -inf
8104
8105   To perform the conversion, we do:
8106     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8107   */
8108
8109   MachineFunction &MF = DAG.getMachineFunction();
8110   const TargetMachine &TM = MF.getTarget();
8111   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8112   unsigned StackAlignment = TFI.getStackAlignment();
8113   EVT VT = Op.getValueType();
8114   DebugLoc DL = Op.getDebugLoc();
8115
8116   // Save FP Control Word to stack slot
8117   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8118   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8119
8120   
8121   MachineMemOperand *MMO =
8122    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8123                            MachineMemOperand::MOStore, 2, 2);
8124   
8125   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8126   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8127                                           DAG.getVTList(MVT::Other),
8128                                           Ops, 2, MVT::i16, MMO);
8129
8130   // Load FP Control Word from stack slot
8131   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8132                             MachinePointerInfo(), false, false, 0);
8133
8134   // Transform as necessary
8135   SDValue CWD1 =
8136     DAG.getNode(ISD::SRL, DL, MVT::i16,
8137                 DAG.getNode(ISD::AND, DL, MVT::i16,
8138                             CWD, DAG.getConstant(0x800, MVT::i16)),
8139                 DAG.getConstant(11, MVT::i8));
8140   SDValue CWD2 =
8141     DAG.getNode(ISD::SRL, DL, MVT::i16,
8142                 DAG.getNode(ISD::AND, DL, MVT::i16,
8143                             CWD, DAG.getConstant(0x400, MVT::i16)),
8144                 DAG.getConstant(9, MVT::i8));
8145
8146   SDValue RetVal =
8147     DAG.getNode(ISD::AND, DL, MVT::i16,
8148                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8149                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8150                             DAG.getConstant(1, MVT::i16)),
8151                 DAG.getConstant(3, MVT::i16));
8152
8153
8154   return DAG.getNode((VT.getSizeInBits() < 16 ?
8155                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8156 }
8157
8158 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8159   EVT VT = Op.getValueType();
8160   EVT OpVT = VT;
8161   unsigned NumBits = VT.getSizeInBits();
8162   DebugLoc dl = Op.getDebugLoc();
8163
8164   Op = Op.getOperand(0);
8165   if (VT == MVT::i8) {
8166     // Zero extend to i32 since there is not an i8 bsr.
8167     OpVT = MVT::i32;
8168     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8169   }
8170
8171   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8172   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8173   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8174
8175   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8176   SDValue Ops[] = {
8177     Op,
8178     DAG.getConstant(NumBits+NumBits-1, OpVT),
8179     DAG.getConstant(X86::COND_E, MVT::i8),
8180     Op.getValue(1)
8181   };
8182   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8183
8184   // Finally xor with NumBits-1.
8185   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8186
8187   if (VT == MVT::i8)
8188     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8189   return Op;
8190 }
8191
8192 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8193   EVT VT = Op.getValueType();
8194   EVT OpVT = VT;
8195   unsigned NumBits = VT.getSizeInBits();
8196   DebugLoc dl = Op.getDebugLoc();
8197
8198   Op = Op.getOperand(0);
8199   if (VT == MVT::i8) {
8200     OpVT = MVT::i32;
8201     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8202   }
8203
8204   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8205   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8206   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8207
8208   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8209   SDValue Ops[] = {
8210     Op,
8211     DAG.getConstant(NumBits, OpVT),
8212     DAG.getConstant(X86::COND_E, MVT::i8),
8213     Op.getValue(1)
8214   };
8215   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8216
8217   if (VT == MVT::i8)
8218     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8219   return Op;
8220 }
8221
8222 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8223   EVT VT = Op.getValueType();
8224   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8225   DebugLoc dl = Op.getDebugLoc();
8226
8227   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8228   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8229   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8230   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8231   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8232   //
8233   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8234   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8235   //  return AloBlo + AloBhi + AhiBlo;
8236
8237   SDValue A = Op.getOperand(0);
8238   SDValue B = Op.getOperand(1);
8239
8240   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8241                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8242                        A, DAG.getConstant(32, MVT::i32));
8243   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8244                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8245                        B, DAG.getConstant(32, MVT::i32));
8246   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8247                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8248                        A, B);
8249   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8250                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8251                        A, Bhi);
8252   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8253                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8254                        Ahi, B);
8255   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8256                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8257                        AloBhi, DAG.getConstant(32, MVT::i32));
8258   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8259                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8260                        AhiBlo, DAG.getConstant(32, MVT::i32));
8261   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8262   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8263   return Res;
8264 }
8265
8266 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8267   EVT VT = Op.getValueType();
8268   DebugLoc dl = Op.getDebugLoc();
8269   SDValue R = Op.getOperand(0);
8270
8271   LLVMContext *Context = DAG.getContext();
8272
8273   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8274
8275   if (VT == MVT::v4i32) {
8276     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8277                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8278                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8279
8280     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8281     
8282     std::vector<Constant*> CV(4, CI);
8283     Constant *C = ConstantVector::get(CV);
8284     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8285     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8286                                  MachinePointerInfo::getConstantPool(),
8287                                  false, false, 16);
8288
8289     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8290     Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8291     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8292     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8293   }
8294   if (VT == MVT::v16i8) {
8295     // a = a << 5;
8296     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8297                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8298                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8299
8300     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8301     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8302
8303     std::vector<Constant*> CVM1(16, CM1);
8304     std::vector<Constant*> CVM2(16, CM2);
8305     Constant *C = ConstantVector::get(CVM1);
8306     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8307     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8308                             MachinePointerInfo::getConstantPool(),
8309                             false, false, 16);
8310
8311     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8312     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8313     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8314                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8315                     DAG.getConstant(4, MVT::i32));
8316     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8317                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8318                     R, M, Op);
8319     // a += a
8320     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8321     
8322     C = ConstantVector::get(CVM2);
8323     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8324     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8325                     MachinePointerInfo::getConstantPool(),
8326                     false, false, 16);
8327     
8328     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8329     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8330     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8331                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8332                     DAG.getConstant(2, MVT::i32));
8333     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8334                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8335                     R, M, Op);
8336     // a += a
8337     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8338     
8339     // return pblendv(r, r+r, a);
8340     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8341                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8342                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8343     return R;
8344   }
8345   return SDValue();
8346 }
8347
8348 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8349   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8350   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8351   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8352   // has only one use.
8353   SDNode *N = Op.getNode();
8354   SDValue LHS = N->getOperand(0);
8355   SDValue RHS = N->getOperand(1);
8356   unsigned BaseOp = 0;
8357   unsigned Cond = 0;
8358   DebugLoc dl = Op.getDebugLoc();
8359
8360   switch (Op.getOpcode()) {
8361   default: llvm_unreachable("Unknown ovf instruction!");
8362   case ISD::SADDO:
8363     // A subtract of one will be selected as a INC. Note that INC doesn't
8364     // set CF, so we can't do this for UADDO.
8365     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8366       if (C->getAPIntValue() == 1) {
8367         BaseOp = X86ISD::INC;
8368         Cond = X86::COND_O;
8369         break;
8370       }
8371     BaseOp = X86ISD::ADD;
8372     Cond = X86::COND_O;
8373     break;
8374   case ISD::UADDO:
8375     BaseOp = X86ISD::ADD;
8376     Cond = X86::COND_B;
8377     break;
8378   case ISD::SSUBO:
8379     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8380     // set CF, so we can't do this for USUBO.
8381     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8382       if (C->getAPIntValue() == 1) {
8383         BaseOp = X86ISD::DEC;
8384         Cond = X86::COND_O;
8385         break;
8386       }
8387     BaseOp = X86ISD::SUB;
8388     Cond = X86::COND_O;
8389     break;
8390   case ISD::USUBO:
8391     BaseOp = X86ISD::SUB;
8392     Cond = X86::COND_B;
8393     break;
8394   case ISD::SMULO:
8395     BaseOp = X86ISD::SMUL;
8396     Cond = X86::COND_O;
8397     break;
8398   case ISD::UMULO:
8399     BaseOp = X86ISD::UMUL;
8400     Cond = X86::COND_B;
8401     break;
8402   }
8403
8404   // Also sets EFLAGS.
8405   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8406   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8407
8408   SDValue SetCC =
8409     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8410                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8411
8412   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8413   return Sum;
8414 }
8415
8416 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8417   DebugLoc dl = Op.getDebugLoc();
8418   
8419   if (!Subtarget->hasSSE2()) {
8420     SDValue Chain = Op.getOperand(0);
8421     SDValue Zero = DAG.getConstant(0, 
8422                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8423     SDValue Ops[] = {
8424       DAG.getRegister(X86::ESP, MVT::i32), // Base
8425       DAG.getTargetConstant(1, MVT::i8),   // Scale
8426       DAG.getRegister(0, MVT::i32),        // Index
8427       DAG.getTargetConstant(0, MVT::i32),  // Disp
8428       DAG.getRegister(0, MVT::i32),        // Segment.
8429       Zero,
8430       Chain
8431     };
8432     SDNode *Res = 
8433       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8434                           array_lengthof(Ops));
8435     return SDValue(Res, 0);
8436   }
8437   
8438   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8439   if (!isDev)
8440     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8441   
8442   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8443   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8444   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8445   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8446   
8447   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8448   if (!Op1 && !Op2 && !Op3 && Op4)
8449     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8450   
8451   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8452   if (Op1 && !Op2 && !Op3 && !Op4)
8453     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8454   
8455   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 
8456   //           (MFENCE)>;
8457   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8458 }
8459
8460 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8461   EVT T = Op.getValueType();
8462   DebugLoc DL = Op.getDebugLoc();
8463   unsigned Reg = 0;
8464   unsigned size = 0;
8465   switch(T.getSimpleVT().SimpleTy) {
8466   default:
8467     assert(false && "Invalid value type!");
8468   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8469   case MVT::i16: Reg = X86::AX;  size = 2; break;
8470   case MVT::i32: Reg = X86::EAX; size = 4; break;
8471   case MVT::i64:
8472     assert(Subtarget->is64Bit() && "Node not type legal!");
8473     Reg = X86::RAX; size = 8;
8474     break;
8475   }
8476   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8477                                     Op.getOperand(2), SDValue());
8478   SDValue Ops[] = { cpIn.getValue(0),
8479                     Op.getOperand(1),
8480                     Op.getOperand(3),
8481                     DAG.getTargetConstant(size, MVT::i8),
8482                     cpIn.getValue(1) };
8483   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8484   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8485   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8486                                            Ops, 5, T, MMO);
8487   SDValue cpOut =
8488     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8489   return cpOut;
8490 }
8491
8492 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8493                                                  SelectionDAG &DAG) const {
8494   assert(Subtarget->is64Bit() && "Result not type legalized?");
8495   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8496   SDValue TheChain = Op.getOperand(0);
8497   DebugLoc dl = Op.getDebugLoc();
8498   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8499   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8500   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8501                                    rax.getValue(2));
8502   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8503                             DAG.getConstant(32, MVT::i8));
8504   SDValue Ops[] = {
8505     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8506     rdx.getValue(1)
8507   };
8508   return DAG.getMergeValues(Ops, 2, dl);
8509 }
8510
8511 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8512                                             SelectionDAG &DAG) const {
8513   EVT SrcVT = Op.getOperand(0).getValueType();
8514   EVT DstVT = Op.getValueType();
8515   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
8516           Subtarget->hasMMX() && !DisableMMX) &&
8517          "Unexpected custom BIT_CONVERT");
8518   assert((DstVT == MVT::i64 || 
8519           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8520          "Unexpected custom BIT_CONVERT");
8521   // i64 <=> MMX conversions are Legal.
8522   if (SrcVT==MVT::i64 && DstVT.isVector())
8523     return Op;
8524   if (DstVT==MVT::i64 && SrcVT.isVector())
8525     return Op;
8526   // MMX <=> MMX conversions are Legal.
8527   if (SrcVT.isVector() && DstVT.isVector())
8528     return Op;
8529   // All other conversions need to be expanded.
8530   return SDValue();
8531 }
8532 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8533   SDNode *Node = Op.getNode();
8534   DebugLoc dl = Node->getDebugLoc();
8535   EVT T = Node->getValueType(0);
8536   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8537                               DAG.getConstant(0, T), Node->getOperand(2));
8538   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8539                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8540                        Node->getOperand(0),
8541                        Node->getOperand(1), negOp,
8542                        cast<AtomicSDNode>(Node)->getSrcValue(),
8543                        cast<AtomicSDNode>(Node)->getAlignment());
8544 }
8545
8546 /// LowerOperation - Provide custom lowering hooks for some operations.
8547 ///
8548 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8549   switch (Op.getOpcode()) {
8550   default: llvm_unreachable("Should not custom lower this!");
8551   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8552   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8553   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8554   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8555   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8556   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8557   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8558   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8559   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8560   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8561   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8562   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8563   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8564   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8565   case ISD::SHL_PARTS:
8566   case ISD::SRA_PARTS:
8567   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8568   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8569   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8570   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8571   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8572   case ISD::FABS:               return LowerFABS(Op, DAG);
8573   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8574   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8575   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8576   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8577   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8578   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8579   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8580   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8581   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8582   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8583   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8584   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8585   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8586   case ISD::FRAME_TO_ARGS_OFFSET:
8587                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8588   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8589   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8590   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8591   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8592   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8593   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8594   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8595   case ISD::SHL:                return LowerSHL(Op, DAG);
8596   case ISD::SADDO:
8597   case ISD::UADDO:
8598   case ISD::SSUBO:
8599   case ISD::USUBO:
8600   case ISD::SMULO:
8601   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8602   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8603   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
8604   }
8605 }
8606
8607 void X86TargetLowering::
8608 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8609                         SelectionDAG &DAG, unsigned NewOp) const {
8610   EVT T = Node->getValueType(0);
8611   DebugLoc dl = Node->getDebugLoc();
8612   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8613
8614   SDValue Chain = Node->getOperand(0);
8615   SDValue In1 = Node->getOperand(1);
8616   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8617                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8618   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8619                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8620   SDValue Ops[] = { Chain, In1, In2L, In2H };
8621   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8622   SDValue Result =
8623     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8624                             cast<MemSDNode>(Node)->getMemOperand());
8625   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8626   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8627   Results.push_back(Result.getValue(2));
8628 }
8629
8630 /// ReplaceNodeResults - Replace a node with an illegal result type
8631 /// with a new node built out of custom code.
8632 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8633                                            SmallVectorImpl<SDValue>&Results,
8634                                            SelectionDAG &DAG) const {
8635   DebugLoc dl = N->getDebugLoc();
8636   switch (N->getOpcode()) {
8637   default:
8638     assert(false && "Do not know how to custom type legalize this operation!");
8639     return;
8640   case ISD::FP_TO_SINT: {
8641     std::pair<SDValue,SDValue> Vals =
8642         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8643     SDValue FIST = Vals.first, StackSlot = Vals.second;
8644     if (FIST.getNode() != 0) {
8645       EVT VT = N->getValueType(0);
8646       // Return a load from the stack slot.
8647       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8648                                     MachinePointerInfo(), false, false, 0));
8649     }
8650     return;
8651   }
8652   case ISD::READCYCLECOUNTER: {
8653     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8654     SDValue TheChain = N->getOperand(0);
8655     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8656     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8657                                      rd.getValue(1));
8658     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8659                                      eax.getValue(2));
8660     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8661     SDValue Ops[] = { eax, edx };
8662     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8663     Results.push_back(edx.getValue(1));
8664     return;
8665   }
8666   case ISD::ATOMIC_CMP_SWAP: {
8667     EVT T = N->getValueType(0);
8668     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8669     SDValue cpInL, cpInH;
8670     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8671                         DAG.getConstant(0, MVT::i32));
8672     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8673                         DAG.getConstant(1, MVT::i32));
8674     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8675     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8676                              cpInL.getValue(1));
8677     SDValue swapInL, swapInH;
8678     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8679                           DAG.getConstant(0, MVT::i32));
8680     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8681                           DAG.getConstant(1, MVT::i32));
8682     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8683                                cpInH.getValue(1));
8684     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8685                                swapInL.getValue(1));
8686     SDValue Ops[] = { swapInH.getValue(0),
8687                       N->getOperand(1),
8688                       swapInH.getValue(1) };
8689     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8690     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8691     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8692                                         MVT::i32, Result.getValue(1));
8693     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8694                                         MVT::i32, cpOutL.getValue(2));
8695     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8696     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8697     Results.push_back(cpOutH.getValue(1));
8698     return;
8699   }
8700   case ISD::ATOMIC_LOAD_ADD:
8701     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8702     return;
8703   case ISD::ATOMIC_LOAD_AND:
8704     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8705     return;
8706   case ISD::ATOMIC_LOAD_NAND:
8707     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8708     return;
8709   case ISD::ATOMIC_LOAD_OR:
8710     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8711     return;
8712   case ISD::ATOMIC_LOAD_SUB:
8713     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8714     return;
8715   case ISD::ATOMIC_LOAD_XOR:
8716     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8717     return;
8718   case ISD::ATOMIC_SWAP:
8719     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8720     return;
8721   }
8722 }
8723
8724 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8725   switch (Opcode) {
8726   default: return NULL;
8727   case X86ISD::BSF:                return "X86ISD::BSF";
8728   case X86ISD::BSR:                return "X86ISD::BSR";
8729   case X86ISD::SHLD:               return "X86ISD::SHLD";
8730   case X86ISD::SHRD:               return "X86ISD::SHRD";
8731   case X86ISD::FAND:               return "X86ISD::FAND";
8732   case X86ISD::FOR:                return "X86ISD::FOR";
8733   case X86ISD::FXOR:               return "X86ISD::FXOR";
8734   case X86ISD::FSRL:               return "X86ISD::FSRL";
8735   case X86ISD::FILD:               return "X86ISD::FILD";
8736   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8737   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8738   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8739   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8740   case X86ISD::FLD:                return "X86ISD::FLD";
8741   case X86ISD::FST:                return "X86ISD::FST";
8742   case X86ISD::CALL:               return "X86ISD::CALL";
8743   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8744   case X86ISD::BT:                 return "X86ISD::BT";
8745   case X86ISD::CMP:                return "X86ISD::CMP";
8746   case X86ISD::COMI:               return "X86ISD::COMI";
8747   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8748   case X86ISD::SETCC:              return "X86ISD::SETCC";
8749   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8750   case X86ISD::CMOV:               return "X86ISD::CMOV";
8751   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8752   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8753   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8754   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8755   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8756   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8757   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8758   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8759   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8760   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8761   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8762   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8763   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8764   case X86ISD::FMAX:               return "X86ISD::FMAX";
8765   case X86ISD::FMIN:               return "X86ISD::FMIN";
8766   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8767   case X86ISD::FRCP:               return "X86ISD::FRCP";
8768   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8769   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8770   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8771   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8772   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8773   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8774   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8775   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8776   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8777   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8778   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8779   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8780   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8781   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8782   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8783   case X86ISD::VSHL:               return "X86ISD::VSHL";
8784   case X86ISD::VSRL:               return "X86ISD::VSRL";
8785   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8786   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8787   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8788   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8789   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8790   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8791   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8792   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8793   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8794   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8795   case X86ISD::ADD:                return "X86ISD::ADD";
8796   case X86ISD::SUB:                return "X86ISD::SUB";
8797   case X86ISD::SMUL:               return "X86ISD::SMUL";
8798   case X86ISD::UMUL:               return "X86ISD::UMUL";
8799   case X86ISD::INC:                return "X86ISD::INC";
8800   case X86ISD::DEC:                return "X86ISD::DEC";
8801   case X86ISD::OR:                 return "X86ISD::OR";
8802   case X86ISD::XOR:                return "X86ISD::XOR";
8803   case X86ISD::AND:                return "X86ISD::AND";
8804   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8805   case X86ISD::PTEST:              return "X86ISD::PTEST";
8806   case X86ISD::TESTP:              return "X86ISD::TESTP";
8807   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8808   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8809   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8810   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8811   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8812   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8813   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8814   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8815   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8816   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8817   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8818   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8819   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8820   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8821   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8822   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8823   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8824   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8825   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8826   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8827   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8828   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8829   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8830   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8831   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8832   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8833   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8834   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8835   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8836   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8837   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8838   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8839   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8840   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8841   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
8842   }
8843 }
8844
8845 // isLegalAddressingMode - Return true if the addressing mode represented
8846 // by AM is legal for this target, for a load/store of the specified type.
8847 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8848                                               const Type *Ty) const {
8849   // X86 supports extremely general addressing modes.
8850   CodeModel::Model M = getTargetMachine().getCodeModel();
8851   Reloc::Model R = getTargetMachine().getRelocationModel();
8852
8853   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8854   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8855     return false;
8856
8857   if (AM.BaseGV) {
8858     unsigned GVFlags =
8859       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8860
8861     // If a reference to this global requires an extra load, we can't fold it.
8862     if (isGlobalStubReference(GVFlags))
8863       return false;
8864
8865     // If BaseGV requires a register for the PIC base, we cannot also have a
8866     // BaseReg specified.
8867     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8868       return false;
8869
8870     // If lower 4G is not available, then we must use rip-relative addressing.
8871     if ((M != CodeModel::Small || R != Reloc::Static) &&
8872         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8873       return false;
8874   }
8875
8876   switch (AM.Scale) {
8877   case 0:
8878   case 1:
8879   case 2:
8880   case 4:
8881   case 8:
8882     // These scales always work.
8883     break;
8884   case 3:
8885   case 5:
8886   case 9:
8887     // These scales are formed with basereg+scalereg.  Only accept if there is
8888     // no basereg yet.
8889     if (AM.HasBaseReg)
8890       return false;
8891     break;
8892   default:  // Other stuff never works.
8893     return false;
8894   }
8895
8896   return true;
8897 }
8898
8899
8900 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8901   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8902     return false;
8903   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8904   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8905   if (NumBits1 <= NumBits2)
8906     return false;
8907   return true;
8908 }
8909
8910 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8911   if (!VT1.isInteger() || !VT2.isInteger())
8912     return false;
8913   unsigned NumBits1 = VT1.getSizeInBits();
8914   unsigned NumBits2 = VT2.getSizeInBits();
8915   if (NumBits1 <= NumBits2)
8916     return false;
8917   return true;
8918 }
8919
8920 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8921   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8922   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8923 }
8924
8925 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8926   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8927   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8928 }
8929
8930 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8931   // i16 instructions are longer (0x66 prefix) and potentially slower.
8932   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8933 }
8934
8935 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8936 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8937 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8938 /// are assumed to be legal.
8939 bool
8940 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8941                                       EVT VT) const {
8942   // Very little shuffling can be done for 64-bit vectors right now.
8943   if (VT.getSizeInBits() == 64)
8944     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8945
8946   // FIXME: pshufb, blends, shifts.
8947   return (VT.getVectorNumElements() == 2 ||
8948           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8949           isMOVLMask(M, VT) ||
8950           isSHUFPMask(M, VT) ||
8951           isPSHUFDMask(M, VT) ||
8952           isPSHUFHWMask(M, VT) ||
8953           isPSHUFLWMask(M, VT) ||
8954           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8955           isUNPCKLMask(M, VT) ||
8956           isUNPCKHMask(M, VT) ||
8957           isUNPCKL_v_undef_Mask(M, VT) ||
8958           isUNPCKH_v_undef_Mask(M, VT));
8959 }
8960
8961 bool
8962 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8963                                           EVT VT) const {
8964   unsigned NumElts = VT.getVectorNumElements();
8965   // FIXME: This collection of masks seems suspect.
8966   if (NumElts == 2)
8967     return true;
8968   if (NumElts == 4 && VT.getSizeInBits() == 128) {
8969     return (isMOVLMask(Mask, VT)  ||
8970             isCommutedMOVLMask(Mask, VT, true) ||
8971             isSHUFPMask(Mask, VT) ||
8972             isCommutedSHUFPMask(Mask, VT));
8973   }
8974   return false;
8975 }
8976
8977 //===----------------------------------------------------------------------===//
8978 //                           X86 Scheduler Hooks
8979 //===----------------------------------------------------------------------===//
8980
8981 // private utility function
8982 MachineBasicBlock *
8983 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8984                                                        MachineBasicBlock *MBB,
8985                                                        unsigned regOpc,
8986                                                        unsigned immOpc,
8987                                                        unsigned LoadOpc,
8988                                                        unsigned CXchgOpc,
8989                                                        unsigned notOpc,
8990                                                        unsigned EAXreg,
8991                                                        TargetRegisterClass *RC,
8992                                                        bool invSrc) const {
8993   // For the atomic bitwise operator, we generate
8994   //   thisMBB:
8995   //   newMBB:
8996   //     ld  t1 = [bitinstr.addr]
8997   //     op  t2 = t1, [bitinstr.val]
8998   //     mov EAX = t1
8999   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9000   //     bz  newMBB
9001   //     fallthrough -->nextMBB
9002   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9003   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9004   MachineFunction::iterator MBBIter = MBB;
9005   ++MBBIter;
9006
9007   /// First build the CFG
9008   MachineFunction *F = MBB->getParent();
9009   MachineBasicBlock *thisMBB = MBB;
9010   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9011   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9012   F->insert(MBBIter, newMBB);
9013   F->insert(MBBIter, nextMBB);
9014
9015   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9016   nextMBB->splice(nextMBB->begin(), thisMBB,
9017                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9018                   thisMBB->end());
9019   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9020
9021   // Update thisMBB to fall through to newMBB
9022   thisMBB->addSuccessor(newMBB);
9023
9024   // newMBB jumps to itself and fall through to nextMBB
9025   newMBB->addSuccessor(nextMBB);
9026   newMBB->addSuccessor(newMBB);
9027
9028   // Insert instructions into newMBB based on incoming instruction
9029   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9030          "unexpected number of operands");
9031   DebugLoc dl = bInstr->getDebugLoc();
9032   MachineOperand& destOper = bInstr->getOperand(0);
9033   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9034   int numArgs = bInstr->getNumOperands() - 1;
9035   for (int i=0; i < numArgs; ++i)
9036     argOpers[i] = &bInstr->getOperand(i+1);
9037
9038   // x86 address has 4 operands: base, index, scale, and displacement
9039   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9040   int valArgIndx = lastAddrIndx + 1;
9041
9042   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9043   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9044   for (int i=0; i <= lastAddrIndx; ++i)
9045     (*MIB).addOperand(*argOpers[i]);
9046
9047   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9048   if (invSrc) {
9049     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9050   }
9051   else
9052     tt = t1;
9053
9054   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9055   assert((argOpers[valArgIndx]->isReg() ||
9056           argOpers[valArgIndx]->isImm()) &&
9057          "invalid operand");
9058   if (argOpers[valArgIndx]->isReg())
9059     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9060   else
9061     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9062   MIB.addReg(tt);
9063   (*MIB).addOperand(*argOpers[valArgIndx]);
9064
9065   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9066   MIB.addReg(t1);
9067
9068   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9069   for (int i=0; i <= lastAddrIndx; ++i)
9070     (*MIB).addOperand(*argOpers[i]);
9071   MIB.addReg(t2);
9072   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9073   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9074                     bInstr->memoperands_end());
9075
9076   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9077   MIB.addReg(EAXreg);
9078
9079   // insert branch
9080   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9081
9082   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9083   return nextMBB;
9084 }
9085
9086 // private utility function:  64 bit atomics on 32 bit host.
9087 MachineBasicBlock *
9088 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9089                                                        MachineBasicBlock *MBB,
9090                                                        unsigned regOpcL,
9091                                                        unsigned regOpcH,
9092                                                        unsigned immOpcL,
9093                                                        unsigned immOpcH,
9094                                                        bool invSrc) const {
9095   // For the atomic bitwise operator, we generate
9096   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9097   //     ld t1,t2 = [bitinstr.addr]
9098   //   newMBB:
9099   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9100   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9101   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9102   //     mov ECX, EBX <- t5, t6
9103   //     mov EAX, EDX <- t1, t2
9104   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9105   //     mov t3, t4 <- EAX, EDX
9106   //     bz  newMBB
9107   //     result in out1, out2
9108   //     fallthrough -->nextMBB
9109
9110   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9111   const unsigned LoadOpc = X86::MOV32rm;
9112   const unsigned NotOpc = X86::NOT32r;
9113   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9114   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9115   MachineFunction::iterator MBBIter = MBB;
9116   ++MBBIter;
9117
9118   /// First build the CFG
9119   MachineFunction *F = MBB->getParent();
9120   MachineBasicBlock *thisMBB = MBB;
9121   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9122   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9123   F->insert(MBBIter, newMBB);
9124   F->insert(MBBIter, nextMBB);
9125
9126   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9127   nextMBB->splice(nextMBB->begin(), thisMBB,
9128                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9129                   thisMBB->end());
9130   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9131
9132   // Update thisMBB to fall through to newMBB
9133   thisMBB->addSuccessor(newMBB);
9134
9135   // newMBB jumps to itself and fall through to nextMBB
9136   newMBB->addSuccessor(nextMBB);
9137   newMBB->addSuccessor(newMBB);
9138
9139   DebugLoc dl = bInstr->getDebugLoc();
9140   // Insert instructions into newMBB based on incoming instruction
9141   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9142   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9143          "unexpected number of operands");
9144   MachineOperand& dest1Oper = bInstr->getOperand(0);
9145   MachineOperand& dest2Oper = bInstr->getOperand(1);
9146   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9147   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9148     argOpers[i] = &bInstr->getOperand(i+2);
9149
9150     // We use some of the operands multiple times, so conservatively just
9151     // clear any kill flags that might be present.
9152     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9153       argOpers[i]->setIsKill(false);
9154   }
9155
9156   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9157   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9158
9159   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9160   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9161   for (int i=0; i <= lastAddrIndx; ++i)
9162     (*MIB).addOperand(*argOpers[i]);
9163   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9164   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9165   // add 4 to displacement.
9166   for (int i=0; i <= lastAddrIndx-2; ++i)
9167     (*MIB).addOperand(*argOpers[i]);
9168   MachineOperand newOp3 = *(argOpers[3]);
9169   if (newOp3.isImm())
9170     newOp3.setImm(newOp3.getImm()+4);
9171   else
9172     newOp3.setOffset(newOp3.getOffset()+4);
9173   (*MIB).addOperand(newOp3);
9174   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9175
9176   // t3/4 are defined later, at the bottom of the loop
9177   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9178   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9179   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9180     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9181   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9182     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9183
9184   // The subsequent operations should be using the destination registers of
9185   //the PHI instructions.
9186   if (invSrc) {
9187     t1 = F->getRegInfo().createVirtualRegister(RC);
9188     t2 = F->getRegInfo().createVirtualRegister(RC);
9189     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9190     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9191   } else {
9192     t1 = dest1Oper.getReg();
9193     t2 = dest2Oper.getReg();
9194   }
9195
9196   int valArgIndx = lastAddrIndx + 1;
9197   assert((argOpers[valArgIndx]->isReg() ||
9198           argOpers[valArgIndx]->isImm()) &&
9199          "invalid operand");
9200   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9201   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9202   if (argOpers[valArgIndx]->isReg())
9203     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9204   else
9205     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9206   if (regOpcL != X86::MOV32rr)
9207     MIB.addReg(t1);
9208   (*MIB).addOperand(*argOpers[valArgIndx]);
9209   assert(argOpers[valArgIndx + 1]->isReg() ==
9210          argOpers[valArgIndx]->isReg());
9211   assert(argOpers[valArgIndx + 1]->isImm() ==
9212          argOpers[valArgIndx]->isImm());
9213   if (argOpers[valArgIndx + 1]->isReg())
9214     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9215   else
9216     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9217   if (regOpcH != X86::MOV32rr)
9218     MIB.addReg(t2);
9219   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9220
9221   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9222   MIB.addReg(t1);
9223   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9224   MIB.addReg(t2);
9225
9226   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9227   MIB.addReg(t5);
9228   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9229   MIB.addReg(t6);
9230
9231   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9232   for (int i=0; i <= lastAddrIndx; ++i)
9233     (*MIB).addOperand(*argOpers[i]);
9234
9235   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9236   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9237                     bInstr->memoperands_end());
9238
9239   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9240   MIB.addReg(X86::EAX);
9241   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9242   MIB.addReg(X86::EDX);
9243
9244   // insert branch
9245   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9246
9247   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9248   return nextMBB;
9249 }
9250
9251 // private utility function
9252 MachineBasicBlock *
9253 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9254                                                       MachineBasicBlock *MBB,
9255                                                       unsigned cmovOpc) const {
9256   // For the atomic min/max operator, we generate
9257   //   thisMBB:
9258   //   newMBB:
9259   //     ld t1 = [min/max.addr]
9260   //     mov t2 = [min/max.val]
9261   //     cmp  t1, t2
9262   //     cmov[cond] t2 = t1
9263   //     mov EAX = t1
9264   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9265   //     bz   newMBB
9266   //     fallthrough -->nextMBB
9267   //
9268   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9269   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9270   MachineFunction::iterator MBBIter = MBB;
9271   ++MBBIter;
9272
9273   /// First build the CFG
9274   MachineFunction *F = MBB->getParent();
9275   MachineBasicBlock *thisMBB = MBB;
9276   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9277   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9278   F->insert(MBBIter, newMBB);
9279   F->insert(MBBIter, nextMBB);
9280
9281   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9282   nextMBB->splice(nextMBB->begin(), thisMBB,
9283                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9284                   thisMBB->end());
9285   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9286
9287   // Update thisMBB to fall through to newMBB
9288   thisMBB->addSuccessor(newMBB);
9289
9290   // newMBB jumps to newMBB and fall through to nextMBB
9291   newMBB->addSuccessor(nextMBB);
9292   newMBB->addSuccessor(newMBB);
9293
9294   DebugLoc dl = mInstr->getDebugLoc();
9295   // Insert instructions into newMBB based on incoming instruction
9296   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9297          "unexpected number of operands");
9298   MachineOperand& destOper = mInstr->getOperand(0);
9299   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9300   int numArgs = mInstr->getNumOperands() - 1;
9301   for (int i=0; i < numArgs; ++i)
9302     argOpers[i] = &mInstr->getOperand(i+1);
9303
9304   // x86 address has 4 operands: base, index, scale, and displacement
9305   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9306   int valArgIndx = lastAddrIndx + 1;
9307
9308   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9309   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9310   for (int i=0; i <= lastAddrIndx; ++i)
9311     (*MIB).addOperand(*argOpers[i]);
9312
9313   // We only support register and immediate values
9314   assert((argOpers[valArgIndx]->isReg() ||
9315           argOpers[valArgIndx]->isImm()) &&
9316          "invalid operand");
9317
9318   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9319   if (argOpers[valArgIndx]->isReg())
9320     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9321   else
9322     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9323   (*MIB).addOperand(*argOpers[valArgIndx]);
9324
9325   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9326   MIB.addReg(t1);
9327
9328   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9329   MIB.addReg(t1);
9330   MIB.addReg(t2);
9331
9332   // Generate movc
9333   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9334   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9335   MIB.addReg(t2);
9336   MIB.addReg(t1);
9337
9338   // Cmp and exchange if none has modified the memory location
9339   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9340   for (int i=0; i <= lastAddrIndx; ++i)
9341     (*MIB).addOperand(*argOpers[i]);
9342   MIB.addReg(t3);
9343   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9344   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9345                     mInstr->memoperands_end());
9346
9347   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9348   MIB.addReg(X86::EAX);
9349
9350   // insert branch
9351   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9352
9353   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9354   return nextMBB;
9355 }
9356
9357 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9358 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9359 // in the .td file.
9360 MachineBasicBlock *
9361 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9362                             unsigned numArgs, bool memArg) const {
9363
9364   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9365          "Target must have SSE4.2 or AVX features enabled");
9366
9367   DebugLoc dl = MI->getDebugLoc();
9368   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9369
9370   unsigned Opc;
9371
9372   if (!Subtarget->hasAVX()) {
9373     if (memArg)
9374       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9375     else
9376       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9377   } else {
9378     if (memArg)
9379       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9380     else
9381       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9382   }
9383
9384   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9385
9386   for (unsigned i = 0; i < numArgs; ++i) {
9387     MachineOperand &Op = MI->getOperand(i+1);
9388
9389     if (!(Op.isReg() && Op.isImplicit()))
9390       MIB.addOperand(Op);
9391   }
9392
9393   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9394     .addReg(X86::XMM0);
9395
9396   MI->eraseFromParent();
9397
9398   return BB;
9399 }
9400
9401 MachineBasicBlock *
9402 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9403                                                  MachineInstr *MI,
9404                                                  MachineBasicBlock *MBB) const {
9405   // Emit code to save XMM registers to the stack. The ABI says that the
9406   // number of registers to save is given in %al, so it's theoretically
9407   // possible to do an indirect jump trick to avoid saving all of them,
9408   // however this code takes a simpler approach and just executes all
9409   // of the stores if %al is non-zero. It's less code, and it's probably
9410   // easier on the hardware branch predictor, and stores aren't all that
9411   // expensive anyway.
9412
9413   // Create the new basic blocks. One block contains all the XMM stores,
9414   // and one block is the final destination regardless of whether any
9415   // stores were performed.
9416   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9417   MachineFunction *F = MBB->getParent();
9418   MachineFunction::iterator MBBIter = MBB;
9419   ++MBBIter;
9420   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9421   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9422   F->insert(MBBIter, XMMSaveMBB);
9423   F->insert(MBBIter, EndMBB);
9424
9425   // Transfer the remainder of MBB and its successor edges to EndMBB.
9426   EndMBB->splice(EndMBB->begin(), MBB,
9427                  llvm::next(MachineBasicBlock::iterator(MI)),
9428                  MBB->end());
9429   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9430
9431   // The original block will now fall through to the XMM save block.
9432   MBB->addSuccessor(XMMSaveMBB);
9433   // The XMMSaveMBB will fall through to the end block.
9434   XMMSaveMBB->addSuccessor(EndMBB);
9435
9436   // Now add the instructions.
9437   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9438   DebugLoc DL = MI->getDebugLoc();
9439
9440   unsigned CountReg = MI->getOperand(0).getReg();
9441   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9442   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9443
9444   if (!Subtarget->isTargetWin64()) {
9445     // If %al is 0, branch around the XMM save block.
9446     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9447     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9448     MBB->addSuccessor(EndMBB);
9449   }
9450
9451   // In the XMM save block, save all the XMM argument registers.
9452   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9453     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9454     MachineMemOperand *MMO =
9455       F->getMachineMemOperand(
9456           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9457         MachineMemOperand::MOStore,
9458         /*Size=*/16, /*Align=*/16);
9459     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9460       .addFrameIndex(RegSaveFrameIndex)
9461       .addImm(/*Scale=*/1)
9462       .addReg(/*IndexReg=*/0)
9463       .addImm(/*Disp=*/Offset)
9464       .addReg(/*Segment=*/0)
9465       .addReg(MI->getOperand(i).getReg())
9466       .addMemOperand(MMO);
9467   }
9468
9469   MI->eraseFromParent();   // The pseudo instruction is gone now.
9470
9471   return EndMBB;
9472 }
9473
9474 MachineBasicBlock *
9475 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9476                                      MachineBasicBlock *BB) const {
9477   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9478   DebugLoc DL = MI->getDebugLoc();
9479
9480   // To "insert" a SELECT_CC instruction, we actually have to insert the
9481   // diamond control-flow pattern.  The incoming instruction knows the
9482   // destination vreg to set, the condition code register to branch on, the
9483   // true/false values to select between, and a branch opcode to use.
9484   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9485   MachineFunction::iterator It = BB;
9486   ++It;
9487
9488   //  thisMBB:
9489   //  ...
9490   //   TrueVal = ...
9491   //   cmpTY ccX, r1, r2
9492   //   bCC copy1MBB
9493   //   fallthrough --> copy0MBB
9494   MachineBasicBlock *thisMBB = BB;
9495   MachineFunction *F = BB->getParent();
9496   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9497   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9498   F->insert(It, copy0MBB);
9499   F->insert(It, sinkMBB);
9500
9501   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9502   // live into the sink and copy blocks.
9503   const MachineFunction *MF = BB->getParent();
9504   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9505   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9506
9507   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9508     const MachineOperand &MO = MI->getOperand(I);
9509     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9510     unsigned Reg = MO.getReg();
9511     if (Reg != X86::EFLAGS) continue;
9512     copy0MBB->addLiveIn(Reg);
9513     sinkMBB->addLiveIn(Reg);
9514   }
9515
9516   // Transfer the remainder of BB and its successor edges to sinkMBB.
9517   sinkMBB->splice(sinkMBB->begin(), BB,
9518                   llvm::next(MachineBasicBlock::iterator(MI)),
9519                   BB->end());
9520   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9521
9522   // Add the true and fallthrough blocks as its successors.
9523   BB->addSuccessor(copy0MBB);
9524   BB->addSuccessor(sinkMBB);
9525
9526   // Create the conditional branch instruction.
9527   unsigned Opc =
9528     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9529   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9530
9531   //  copy0MBB:
9532   //   %FalseValue = ...
9533   //   # fallthrough to sinkMBB
9534   copy0MBB->addSuccessor(sinkMBB);
9535
9536   //  sinkMBB:
9537   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9538   //  ...
9539   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9540           TII->get(X86::PHI), MI->getOperand(0).getReg())
9541     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9542     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9543
9544   MI->eraseFromParent();   // The pseudo instruction is gone now.
9545   return sinkMBB;
9546 }
9547
9548 MachineBasicBlock *
9549 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9550                                           MachineBasicBlock *BB) const {
9551   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9552   DebugLoc DL = MI->getDebugLoc();
9553
9554   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9555   // non-trivial part is impdef of ESP.
9556   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9557   // mingw-w64.
9558
9559   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9560     .addExternalSymbol("_alloca")
9561     .addReg(X86::EAX, RegState::Implicit)
9562     .addReg(X86::ESP, RegState::Implicit)
9563     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9564     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9565     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9566
9567   MI->eraseFromParent();   // The pseudo instruction is gone now.
9568   return BB;
9569 }
9570
9571 MachineBasicBlock *
9572 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9573                                       MachineBasicBlock *BB) const {
9574   // This is pretty easy.  We're taking the value that we received from
9575   // our load from the relocation, sticking it in either RDI (x86-64)
9576   // or EAX and doing an indirect call.  The return value will then
9577   // be in the normal return register.
9578   const X86InstrInfo *TII 
9579     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9580   DebugLoc DL = MI->getDebugLoc();
9581   MachineFunction *F = BB->getParent();
9582
9583   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9584   assert(MI->getOperand(3).isGlobal() && "This should be a global");
9585   
9586   if (Subtarget->is64Bit()) {
9587     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9588                                       TII->get(X86::MOV64rm), X86::RDI)
9589     .addReg(X86::RIP)
9590     .addImm(0).addReg(0)
9591     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9592                       MI->getOperand(3).getTargetFlags())
9593     .addReg(0);
9594     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
9595     addDirectMem(MIB, X86::RDI);
9596   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9597     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9598                                       TII->get(X86::MOV32rm), X86::EAX)
9599     .addReg(0)
9600     .addImm(0).addReg(0)
9601     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9602                       MI->getOperand(3).getTargetFlags())
9603     .addReg(0);
9604     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9605     addDirectMem(MIB, X86::EAX);
9606   } else {
9607     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9608                                       TII->get(X86::MOV32rm), X86::EAX)
9609     .addReg(TII->getGlobalBaseReg(F))
9610     .addImm(0).addReg(0)
9611     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9612                       MI->getOperand(3).getTargetFlags())
9613     .addReg(0);
9614     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9615     addDirectMem(MIB, X86::EAX);
9616   }
9617   
9618   MI->eraseFromParent(); // The pseudo instruction is gone now.
9619   return BB;
9620 }
9621
9622 MachineBasicBlock *
9623 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9624                                                MachineBasicBlock *BB) const {
9625   switch (MI->getOpcode()) {
9626   default: assert(false && "Unexpected instr type to insert");
9627   case X86::MINGW_ALLOCA:
9628     return EmitLoweredMingwAlloca(MI, BB);
9629   case X86::TLSCall_32:
9630   case X86::TLSCall_64:
9631     return EmitLoweredTLSCall(MI, BB);
9632   case X86::CMOV_GR8:
9633   case X86::CMOV_FR32:
9634   case X86::CMOV_FR64:
9635   case X86::CMOV_V4F32:
9636   case X86::CMOV_V2F64:
9637   case X86::CMOV_V2I64:
9638   case X86::CMOV_GR16:
9639   case X86::CMOV_GR32:
9640   case X86::CMOV_RFP32:
9641   case X86::CMOV_RFP64:
9642   case X86::CMOV_RFP80:
9643     return EmitLoweredSelect(MI, BB);
9644
9645   case X86::FP32_TO_INT16_IN_MEM:
9646   case X86::FP32_TO_INT32_IN_MEM:
9647   case X86::FP32_TO_INT64_IN_MEM:
9648   case X86::FP64_TO_INT16_IN_MEM:
9649   case X86::FP64_TO_INT32_IN_MEM:
9650   case X86::FP64_TO_INT64_IN_MEM:
9651   case X86::FP80_TO_INT16_IN_MEM:
9652   case X86::FP80_TO_INT32_IN_MEM:
9653   case X86::FP80_TO_INT64_IN_MEM: {
9654     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9655     DebugLoc DL = MI->getDebugLoc();
9656
9657     // Change the floating point control register to use "round towards zero"
9658     // mode when truncating to an integer value.
9659     MachineFunction *F = BB->getParent();
9660     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9661     addFrameReference(BuildMI(*BB, MI, DL,
9662                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
9663
9664     // Load the old value of the high byte of the control word...
9665     unsigned OldCW =
9666       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9667     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9668                       CWFrameIdx);
9669
9670     // Set the high part to be round to zero...
9671     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9672       .addImm(0xC7F);
9673
9674     // Reload the modified control word now...
9675     addFrameReference(BuildMI(*BB, MI, DL,
9676                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9677
9678     // Restore the memory image of control word to original value
9679     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9680       .addReg(OldCW);
9681
9682     // Get the X86 opcode to use.
9683     unsigned Opc;
9684     switch (MI->getOpcode()) {
9685     default: llvm_unreachable("illegal opcode!");
9686     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9687     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9688     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9689     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9690     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9691     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9692     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9693     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9694     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9695     }
9696
9697     X86AddressMode AM;
9698     MachineOperand &Op = MI->getOperand(0);
9699     if (Op.isReg()) {
9700       AM.BaseType = X86AddressMode::RegBase;
9701       AM.Base.Reg = Op.getReg();
9702     } else {
9703       AM.BaseType = X86AddressMode::FrameIndexBase;
9704       AM.Base.FrameIndex = Op.getIndex();
9705     }
9706     Op = MI->getOperand(1);
9707     if (Op.isImm())
9708       AM.Scale = Op.getImm();
9709     Op = MI->getOperand(2);
9710     if (Op.isImm())
9711       AM.IndexReg = Op.getImm();
9712     Op = MI->getOperand(3);
9713     if (Op.isGlobal()) {
9714       AM.GV = Op.getGlobal();
9715     } else {
9716       AM.Disp = Op.getImm();
9717     }
9718     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9719                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9720
9721     // Reload the original control word now.
9722     addFrameReference(BuildMI(*BB, MI, DL,
9723                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9724
9725     MI->eraseFromParent();   // The pseudo instruction is gone now.
9726     return BB;
9727   }
9728     // String/text processing lowering.
9729   case X86::PCMPISTRM128REG:
9730   case X86::VPCMPISTRM128REG:
9731     return EmitPCMP(MI, BB, 3, false /* in-mem */);
9732   case X86::PCMPISTRM128MEM:
9733   case X86::VPCMPISTRM128MEM:
9734     return EmitPCMP(MI, BB, 3, true /* in-mem */);
9735   case X86::PCMPESTRM128REG:
9736   case X86::VPCMPESTRM128REG:
9737     return EmitPCMP(MI, BB, 5, false /* in mem */);
9738   case X86::PCMPESTRM128MEM:
9739   case X86::VPCMPESTRM128MEM:
9740     return EmitPCMP(MI, BB, 5, true /* in mem */);
9741
9742     // Atomic Lowering.
9743   case X86::ATOMAND32:
9744     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9745                                                X86::AND32ri, X86::MOV32rm,
9746                                                X86::LCMPXCHG32,
9747                                                X86::NOT32r, X86::EAX,
9748                                                X86::GR32RegisterClass);
9749   case X86::ATOMOR32:
9750     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9751                                                X86::OR32ri, X86::MOV32rm,
9752                                                X86::LCMPXCHG32,
9753                                                X86::NOT32r, X86::EAX,
9754                                                X86::GR32RegisterClass);
9755   case X86::ATOMXOR32:
9756     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9757                                                X86::XOR32ri, X86::MOV32rm,
9758                                                X86::LCMPXCHG32,
9759                                                X86::NOT32r, X86::EAX,
9760                                                X86::GR32RegisterClass);
9761   case X86::ATOMNAND32:
9762     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9763                                                X86::AND32ri, X86::MOV32rm,
9764                                                X86::LCMPXCHG32,
9765                                                X86::NOT32r, X86::EAX,
9766                                                X86::GR32RegisterClass, true);
9767   case X86::ATOMMIN32:
9768     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9769   case X86::ATOMMAX32:
9770     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9771   case X86::ATOMUMIN32:
9772     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9773   case X86::ATOMUMAX32:
9774     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9775
9776   case X86::ATOMAND16:
9777     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9778                                                X86::AND16ri, X86::MOV16rm,
9779                                                X86::LCMPXCHG16,
9780                                                X86::NOT16r, X86::AX,
9781                                                X86::GR16RegisterClass);
9782   case X86::ATOMOR16:
9783     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9784                                                X86::OR16ri, X86::MOV16rm,
9785                                                X86::LCMPXCHG16,
9786                                                X86::NOT16r, X86::AX,
9787                                                X86::GR16RegisterClass);
9788   case X86::ATOMXOR16:
9789     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9790                                                X86::XOR16ri, X86::MOV16rm,
9791                                                X86::LCMPXCHG16,
9792                                                X86::NOT16r, X86::AX,
9793                                                X86::GR16RegisterClass);
9794   case X86::ATOMNAND16:
9795     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9796                                                X86::AND16ri, X86::MOV16rm,
9797                                                X86::LCMPXCHG16,
9798                                                X86::NOT16r, X86::AX,
9799                                                X86::GR16RegisterClass, true);
9800   case X86::ATOMMIN16:
9801     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9802   case X86::ATOMMAX16:
9803     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9804   case X86::ATOMUMIN16:
9805     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9806   case X86::ATOMUMAX16:
9807     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9808
9809   case X86::ATOMAND8:
9810     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9811                                                X86::AND8ri, X86::MOV8rm,
9812                                                X86::LCMPXCHG8,
9813                                                X86::NOT8r, X86::AL,
9814                                                X86::GR8RegisterClass);
9815   case X86::ATOMOR8:
9816     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9817                                                X86::OR8ri, X86::MOV8rm,
9818                                                X86::LCMPXCHG8,
9819                                                X86::NOT8r, X86::AL,
9820                                                X86::GR8RegisterClass);
9821   case X86::ATOMXOR8:
9822     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9823                                                X86::XOR8ri, X86::MOV8rm,
9824                                                X86::LCMPXCHG8,
9825                                                X86::NOT8r, X86::AL,
9826                                                X86::GR8RegisterClass);
9827   case X86::ATOMNAND8:
9828     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9829                                                X86::AND8ri, X86::MOV8rm,
9830                                                X86::LCMPXCHG8,
9831                                                X86::NOT8r, X86::AL,
9832                                                X86::GR8RegisterClass, true);
9833   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9834   // This group is for 64-bit host.
9835   case X86::ATOMAND64:
9836     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9837                                                X86::AND64ri32, X86::MOV64rm,
9838                                                X86::LCMPXCHG64,
9839                                                X86::NOT64r, X86::RAX,
9840                                                X86::GR64RegisterClass);
9841   case X86::ATOMOR64:
9842     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9843                                                X86::OR64ri32, X86::MOV64rm,
9844                                                X86::LCMPXCHG64,
9845                                                X86::NOT64r, X86::RAX,
9846                                                X86::GR64RegisterClass);
9847   case X86::ATOMXOR64:
9848     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9849                                                X86::XOR64ri32, X86::MOV64rm,
9850                                                X86::LCMPXCHG64,
9851                                                X86::NOT64r, X86::RAX,
9852                                                X86::GR64RegisterClass);
9853   case X86::ATOMNAND64:
9854     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9855                                                X86::AND64ri32, X86::MOV64rm,
9856                                                X86::LCMPXCHG64,
9857                                                X86::NOT64r, X86::RAX,
9858                                                X86::GR64RegisterClass, true);
9859   case X86::ATOMMIN64:
9860     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9861   case X86::ATOMMAX64:
9862     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9863   case X86::ATOMUMIN64:
9864     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9865   case X86::ATOMUMAX64:
9866     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9867
9868   // This group does 64-bit operations on a 32-bit host.
9869   case X86::ATOMAND6432:
9870     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9871                                                X86::AND32rr, X86::AND32rr,
9872                                                X86::AND32ri, X86::AND32ri,
9873                                                false);
9874   case X86::ATOMOR6432:
9875     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9876                                                X86::OR32rr, X86::OR32rr,
9877                                                X86::OR32ri, X86::OR32ri,
9878                                                false);
9879   case X86::ATOMXOR6432:
9880     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9881                                                X86::XOR32rr, X86::XOR32rr,
9882                                                X86::XOR32ri, X86::XOR32ri,
9883                                                false);
9884   case X86::ATOMNAND6432:
9885     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9886                                                X86::AND32rr, X86::AND32rr,
9887                                                X86::AND32ri, X86::AND32ri,
9888                                                true);
9889   case X86::ATOMADD6432:
9890     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9891                                                X86::ADD32rr, X86::ADC32rr,
9892                                                X86::ADD32ri, X86::ADC32ri,
9893                                                false);
9894   case X86::ATOMSUB6432:
9895     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9896                                                X86::SUB32rr, X86::SBB32rr,
9897                                                X86::SUB32ri, X86::SBB32ri,
9898                                                false);
9899   case X86::ATOMSWAP6432:
9900     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9901                                                X86::MOV32rr, X86::MOV32rr,
9902                                                X86::MOV32ri, X86::MOV32ri,
9903                                                false);
9904   case X86::VASTART_SAVE_XMM_REGS:
9905     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9906   }
9907 }
9908
9909 //===----------------------------------------------------------------------===//
9910 //                           X86 Optimization Hooks
9911 //===----------------------------------------------------------------------===//
9912
9913 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9914                                                        const APInt &Mask,
9915                                                        APInt &KnownZero,
9916                                                        APInt &KnownOne,
9917                                                        const SelectionDAG &DAG,
9918                                                        unsigned Depth) const {
9919   unsigned Opc = Op.getOpcode();
9920   assert((Opc >= ISD::BUILTIN_OP_END ||
9921           Opc == ISD::INTRINSIC_WO_CHAIN ||
9922           Opc == ISD::INTRINSIC_W_CHAIN ||
9923           Opc == ISD::INTRINSIC_VOID) &&
9924          "Should use MaskedValueIsZero if you don't know whether Op"
9925          " is a target node!");
9926
9927   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
9928   switch (Opc) {
9929   default: break;
9930   case X86ISD::ADD:
9931   case X86ISD::SUB:
9932   case X86ISD::SMUL:
9933   case X86ISD::UMUL:
9934   case X86ISD::INC:
9935   case X86ISD::DEC:
9936   case X86ISD::OR:
9937   case X86ISD::XOR:
9938   case X86ISD::AND:
9939     // These nodes' second result is a boolean.
9940     if (Op.getResNo() == 0)
9941       break;
9942     // Fallthrough
9943   case X86ISD::SETCC:
9944     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9945                                        Mask.getBitWidth() - 1);
9946     break;
9947   }
9948 }
9949
9950 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
9951                                                          unsigned Depth) const {
9952   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
9953   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
9954     return Op.getValueType().getScalarType().getSizeInBits();
9955   
9956   // Fallback case.
9957   return 1;
9958 }
9959
9960 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9961 /// node is a GlobalAddress + offset.
9962 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9963                                        const GlobalValue* &GA,
9964                                        int64_t &Offset) const {
9965   if (N->getOpcode() == X86ISD::Wrapper) {
9966     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9967       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9968       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9969       return true;
9970     }
9971   }
9972   return TargetLowering::isGAPlusOffset(N, GA, Offset);
9973 }
9974
9975 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9976 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9977 /// if the load addresses are consecutive, non-overlapping, and in the right
9978 /// order.
9979 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9980                                      const TargetLowering &TLI) {
9981   DebugLoc dl = N->getDebugLoc();
9982   EVT VT = N->getValueType(0);
9983
9984   if (VT.getSizeInBits() != 128)
9985     return SDValue();
9986
9987   SmallVector<SDValue, 16> Elts;
9988   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9989     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
9990
9991   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9992 }
9993
9994 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
9995 /// generation and convert it from being a bunch of shuffles and extracts
9996 /// to a simple store and scalar loads to extract the elements.
9997 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
9998                                                 const TargetLowering &TLI) {
9999   SDValue InputVector = N->getOperand(0);
10000
10001   // Only operate on vectors of 4 elements, where the alternative shuffling
10002   // gets to be more expensive.
10003   if (InputVector.getValueType() != MVT::v4i32)
10004     return SDValue();
10005
10006   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10007   // single use which is a sign-extend or zero-extend, and all elements are
10008   // used.
10009   SmallVector<SDNode *, 4> Uses;
10010   unsigned ExtractedElements = 0;
10011   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10012        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10013     if (UI.getUse().getResNo() != InputVector.getResNo())
10014       return SDValue();
10015
10016     SDNode *Extract = *UI;
10017     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10018       return SDValue();
10019
10020     if (Extract->getValueType(0) != MVT::i32)
10021       return SDValue();
10022     if (!Extract->hasOneUse())
10023       return SDValue();
10024     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10025         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10026       return SDValue();
10027     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10028       return SDValue();
10029
10030     // Record which element was extracted.
10031     ExtractedElements |=
10032       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10033
10034     Uses.push_back(Extract);
10035   }
10036
10037   // If not all the elements were used, this may not be worthwhile.
10038   if (ExtractedElements != 15)
10039     return SDValue();
10040
10041   // Ok, we've now decided to do the transformation.
10042   DebugLoc dl = InputVector.getDebugLoc();
10043
10044   // Store the value to a temporary stack slot.
10045   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10046   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10047                             MachinePointerInfo(), false, false, 0);
10048
10049   // Replace each use (extract) with a load of the appropriate element.
10050   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10051        UE = Uses.end(); UI != UE; ++UI) {
10052     SDNode *Extract = *UI;
10053
10054     // Compute the element's address.
10055     SDValue Idx = Extract->getOperand(1);
10056     unsigned EltSize =
10057         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10058     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10059     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10060
10061     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10062                                      StackPtr, OffsetVal);
10063
10064     // Load the scalar.
10065     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10066                                      ScalarAddr, MachinePointerInfo(),
10067                                      false, false, 0);
10068
10069     // Replace the exact with the load.
10070     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10071   }
10072
10073   // The replacement was made in place; don't return anything.
10074   return SDValue();
10075 }
10076
10077 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10078 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10079                                     const X86Subtarget *Subtarget) {
10080   DebugLoc DL = N->getDebugLoc();
10081   SDValue Cond = N->getOperand(0);
10082   // Get the LHS/RHS of the select.
10083   SDValue LHS = N->getOperand(1);
10084   SDValue RHS = N->getOperand(2);
10085
10086   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10087   // instructions match the semantics of the common C idiom x<y?x:y but not
10088   // x<=y?x:y, because of how they handle negative zero (which can be
10089   // ignored in unsafe-math mode).
10090   if (Subtarget->hasSSE2() &&
10091       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10092       Cond.getOpcode() == ISD::SETCC) {
10093     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10094
10095     unsigned Opcode = 0;
10096     // Check for x CC y ? x : y.
10097     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10098         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10099       switch (CC) {
10100       default: break;
10101       case ISD::SETULT:
10102         // Converting this to a min would handle NaNs incorrectly, and swapping
10103         // the operands would cause it to handle comparisons between positive
10104         // and negative zero incorrectly.
10105         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10106           if (!UnsafeFPMath &&
10107               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10108             break;
10109           std::swap(LHS, RHS);
10110         }
10111         Opcode = X86ISD::FMIN;
10112         break;
10113       case ISD::SETOLE:
10114         // Converting this to a min would handle comparisons between positive
10115         // and negative zero incorrectly.
10116         if (!UnsafeFPMath &&
10117             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10118           break;
10119         Opcode = X86ISD::FMIN;
10120         break;
10121       case ISD::SETULE:
10122         // Converting this to a min would handle both negative zeros and NaNs
10123         // incorrectly, but we can swap the operands to fix both.
10124         std::swap(LHS, RHS);
10125       case ISD::SETOLT:
10126       case ISD::SETLT:
10127       case ISD::SETLE:
10128         Opcode = X86ISD::FMIN;
10129         break;
10130
10131       case ISD::SETOGE:
10132         // Converting this to a max would handle comparisons between positive
10133         // and negative zero incorrectly.
10134         if (!UnsafeFPMath &&
10135             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10136           break;
10137         Opcode = X86ISD::FMAX;
10138         break;
10139       case ISD::SETUGT:
10140         // Converting this to a max would handle NaNs incorrectly, and swapping
10141         // the operands would cause it to handle comparisons between positive
10142         // and negative zero incorrectly.
10143         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10144           if (!UnsafeFPMath &&
10145               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10146             break;
10147           std::swap(LHS, RHS);
10148         }
10149         Opcode = X86ISD::FMAX;
10150         break;
10151       case ISD::SETUGE:
10152         // Converting this to a max would handle both negative zeros and NaNs
10153         // incorrectly, but we can swap the operands to fix both.
10154         std::swap(LHS, RHS);
10155       case ISD::SETOGT:
10156       case ISD::SETGT:
10157       case ISD::SETGE:
10158         Opcode = X86ISD::FMAX;
10159         break;
10160       }
10161     // Check for x CC y ? y : x -- a min/max with reversed arms.
10162     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10163                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10164       switch (CC) {
10165       default: break;
10166       case ISD::SETOGE:
10167         // Converting this to a min would handle comparisons between positive
10168         // and negative zero incorrectly, and swapping the operands would
10169         // cause it to handle NaNs incorrectly.
10170         if (!UnsafeFPMath &&
10171             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10172           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10173             break;
10174           std::swap(LHS, RHS);
10175         }
10176         Opcode = X86ISD::FMIN;
10177         break;
10178       case ISD::SETUGT:
10179         // Converting this to a min would handle NaNs incorrectly.
10180         if (!UnsafeFPMath &&
10181             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10182           break;
10183         Opcode = X86ISD::FMIN;
10184         break;
10185       case ISD::SETUGE:
10186         // Converting this to a min would handle both negative zeros and NaNs
10187         // incorrectly, but we can swap the operands to fix both.
10188         std::swap(LHS, RHS);
10189       case ISD::SETOGT:
10190       case ISD::SETGT:
10191       case ISD::SETGE:
10192         Opcode = X86ISD::FMIN;
10193         break;
10194
10195       case ISD::SETULT:
10196         // Converting this to a max would handle NaNs incorrectly.
10197         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10198           break;
10199         Opcode = X86ISD::FMAX;
10200         break;
10201       case ISD::SETOLE:
10202         // Converting this to a max would handle comparisons between positive
10203         // and negative zero incorrectly, and swapping the operands would
10204         // cause it to handle NaNs incorrectly.
10205         if (!UnsafeFPMath &&
10206             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10207           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10208             break;
10209           std::swap(LHS, RHS);
10210         }
10211         Opcode = X86ISD::FMAX;
10212         break;
10213       case ISD::SETULE:
10214         // Converting this to a max would handle both negative zeros and NaNs
10215         // incorrectly, but we can swap the operands to fix both.
10216         std::swap(LHS, RHS);
10217       case ISD::SETOLT:
10218       case ISD::SETLT:
10219       case ISD::SETLE:
10220         Opcode = X86ISD::FMAX;
10221         break;
10222       }
10223     }
10224
10225     if (Opcode)
10226       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10227   }
10228
10229   // If this is a select between two integer constants, try to do some
10230   // optimizations.
10231   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10232     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10233       // Don't do this for crazy integer types.
10234       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10235         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10236         // so that TrueC (the true value) is larger than FalseC.
10237         bool NeedsCondInvert = false;
10238
10239         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10240             // Efficiently invertible.
10241             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10242              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10243               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10244           NeedsCondInvert = true;
10245           std::swap(TrueC, FalseC);
10246         }
10247
10248         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10249         if (FalseC->getAPIntValue() == 0 &&
10250             TrueC->getAPIntValue().isPowerOf2()) {
10251           if (NeedsCondInvert) // Invert the condition if needed.
10252             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10253                                DAG.getConstant(1, Cond.getValueType()));
10254
10255           // Zero extend the condition if needed.
10256           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10257
10258           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10259           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10260                              DAG.getConstant(ShAmt, MVT::i8));
10261         }
10262
10263         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10264         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10265           if (NeedsCondInvert) // Invert the condition if needed.
10266             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10267                                DAG.getConstant(1, Cond.getValueType()));
10268
10269           // Zero extend the condition if needed.
10270           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10271                              FalseC->getValueType(0), Cond);
10272           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10273                              SDValue(FalseC, 0));
10274         }
10275
10276         // Optimize cases that will turn into an LEA instruction.  This requires
10277         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10278         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10279           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10280           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10281
10282           bool isFastMultiplier = false;
10283           if (Diff < 10) {
10284             switch ((unsigned char)Diff) {
10285               default: break;
10286               case 1:  // result = add base, cond
10287               case 2:  // result = lea base(    , cond*2)
10288               case 3:  // result = lea base(cond, cond*2)
10289               case 4:  // result = lea base(    , cond*4)
10290               case 5:  // result = lea base(cond, cond*4)
10291               case 8:  // result = lea base(    , cond*8)
10292               case 9:  // result = lea base(cond, cond*8)
10293                 isFastMultiplier = true;
10294                 break;
10295             }
10296           }
10297
10298           if (isFastMultiplier) {
10299             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10300             if (NeedsCondInvert) // Invert the condition if needed.
10301               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10302                                  DAG.getConstant(1, Cond.getValueType()));
10303
10304             // Zero extend the condition if needed.
10305             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10306                                Cond);
10307             // Scale the condition by the difference.
10308             if (Diff != 1)
10309               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10310                                  DAG.getConstant(Diff, Cond.getValueType()));
10311
10312             // Add the base if non-zero.
10313             if (FalseC->getAPIntValue() != 0)
10314               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10315                                  SDValue(FalseC, 0));
10316             return Cond;
10317           }
10318         }
10319       }
10320   }
10321
10322   return SDValue();
10323 }
10324
10325 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10326 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10327                                   TargetLowering::DAGCombinerInfo &DCI) {
10328   DebugLoc DL = N->getDebugLoc();
10329
10330   // If the flag operand isn't dead, don't touch this CMOV.
10331   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10332     return SDValue();
10333
10334   // If this is a select between two integer constants, try to do some
10335   // optimizations.  Note that the operands are ordered the opposite of SELECT
10336   // operands.
10337   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10338     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10339       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10340       // larger than FalseC (the false value).
10341       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10342
10343       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10344         CC = X86::GetOppositeBranchCondition(CC);
10345         std::swap(TrueC, FalseC);
10346       }
10347
10348       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10349       // This is efficient for any integer data type (including i8/i16) and
10350       // shift amount.
10351       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10352         SDValue Cond = N->getOperand(3);
10353         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10354                            DAG.getConstant(CC, MVT::i8), Cond);
10355
10356         // Zero extend the condition if needed.
10357         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10358
10359         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10360         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10361                            DAG.getConstant(ShAmt, MVT::i8));
10362         if (N->getNumValues() == 2)  // Dead flag value?
10363           return DCI.CombineTo(N, Cond, SDValue());
10364         return Cond;
10365       }
10366
10367       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10368       // for any integer data type, including i8/i16.
10369       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10370         SDValue Cond = N->getOperand(3);
10371         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10372                            DAG.getConstant(CC, MVT::i8), Cond);
10373
10374         // Zero extend the condition if needed.
10375         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10376                            FalseC->getValueType(0), Cond);
10377         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10378                            SDValue(FalseC, 0));
10379
10380         if (N->getNumValues() == 2)  // Dead flag value?
10381           return DCI.CombineTo(N, Cond, SDValue());
10382         return Cond;
10383       }
10384
10385       // Optimize cases that will turn into an LEA instruction.  This requires
10386       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10387       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10388         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10389         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10390
10391         bool isFastMultiplier = false;
10392         if (Diff < 10) {
10393           switch ((unsigned char)Diff) {
10394           default: break;
10395           case 1:  // result = add base, cond
10396           case 2:  // result = lea base(    , cond*2)
10397           case 3:  // result = lea base(cond, cond*2)
10398           case 4:  // result = lea base(    , cond*4)
10399           case 5:  // result = lea base(cond, cond*4)
10400           case 8:  // result = lea base(    , cond*8)
10401           case 9:  // result = lea base(cond, cond*8)
10402             isFastMultiplier = true;
10403             break;
10404           }
10405         }
10406
10407         if (isFastMultiplier) {
10408           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10409           SDValue Cond = N->getOperand(3);
10410           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10411                              DAG.getConstant(CC, MVT::i8), Cond);
10412           // Zero extend the condition if needed.
10413           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10414                              Cond);
10415           // Scale the condition by the difference.
10416           if (Diff != 1)
10417             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10418                                DAG.getConstant(Diff, Cond.getValueType()));
10419
10420           // Add the base if non-zero.
10421           if (FalseC->getAPIntValue() != 0)
10422             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10423                                SDValue(FalseC, 0));
10424           if (N->getNumValues() == 2)  // Dead flag value?
10425             return DCI.CombineTo(N, Cond, SDValue());
10426           return Cond;
10427         }
10428       }
10429     }
10430   }
10431   return SDValue();
10432 }
10433
10434
10435 /// PerformMulCombine - Optimize a single multiply with constant into two
10436 /// in order to implement it with two cheaper instructions, e.g.
10437 /// LEA + SHL, LEA + LEA.
10438 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10439                                  TargetLowering::DAGCombinerInfo &DCI) {
10440   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10441     return SDValue();
10442
10443   EVT VT = N->getValueType(0);
10444   if (VT != MVT::i64)
10445     return SDValue();
10446
10447   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10448   if (!C)
10449     return SDValue();
10450   uint64_t MulAmt = C->getZExtValue();
10451   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10452     return SDValue();
10453
10454   uint64_t MulAmt1 = 0;
10455   uint64_t MulAmt2 = 0;
10456   if ((MulAmt % 9) == 0) {
10457     MulAmt1 = 9;
10458     MulAmt2 = MulAmt / 9;
10459   } else if ((MulAmt % 5) == 0) {
10460     MulAmt1 = 5;
10461     MulAmt2 = MulAmt / 5;
10462   } else if ((MulAmt % 3) == 0) {
10463     MulAmt1 = 3;
10464     MulAmt2 = MulAmt / 3;
10465   }
10466   if (MulAmt2 &&
10467       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10468     DebugLoc DL = N->getDebugLoc();
10469
10470     if (isPowerOf2_64(MulAmt2) &&
10471         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10472       // If second multiplifer is pow2, issue it first. We want the multiply by
10473       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10474       // is an add.
10475       std::swap(MulAmt1, MulAmt2);
10476
10477     SDValue NewMul;
10478     if (isPowerOf2_64(MulAmt1))
10479       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10480                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10481     else
10482       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10483                            DAG.getConstant(MulAmt1, VT));
10484
10485     if (isPowerOf2_64(MulAmt2))
10486       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10487                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10488     else
10489       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10490                            DAG.getConstant(MulAmt2, VT));
10491
10492     // Do not add new nodes to DAG combiner worklist.
10493     DCI.CombineTo(N, NewMul, false);
10494   }
10495   return SDValue();
10496 }
10497
10498 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10499   SDValue N0 = N->getOperand(0);
10500   SDValue N1 = N->getOperand(1);
10501   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10502   EVT VT = N0.getValueType();
10503
10504   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10505   // since the result of setcc_c is all zero's or all ones.
10506   if (N1C && N0.getOpcode() == ISD::AND &&
10507       N0.getOperand(1).getOpcode() == ISD::Constant) {
10508     SDValue N00 = N0.getOperand(0);
10509     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10510         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10511           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10512          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10513       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10514       APInt ShAmt = N1C->getAPIntValue();
10515       Mask = Mask.shl(ShAmt);
10516       if (Mask != 0)
10517         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10518                            N00, DAG.getConstant(Mask, VT));
10519     }
10520   }
10521
10522   return SDValue();
10523 }
10524
10525 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10526 ///                       when possible.
10527 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10528                                    const X86Subtarget *Subtarget) {
10529   EVT VT = N->getValueType(0);
10530   if (!VT.isVector() && VT.isInteger() &&
10531       N->getOpcode() == ISD::SHL)
10532     return PerformSHLCombine(N, DAG);
10533
10534   // On X86 with SSE2 support, we can transform this to a vector shift if
10535   // all elements are shifted by the same amount.  We can't do this in legalize
10536   // because the a constant vector is typically transformed to a constant pool
10537   // so we have no knowledge of the shift amount.
10538   if (!Subtarget->hasSSE2())
10539     return SDValue();
10540
10541   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10542     return SDValue();
10543
10544   SDValue ShAmtOp = N->getOperand(1);
10545   EVT EltVT = VT.getVectorElementType();
10546   DebugLoc DL = N->getDebugLoc();
10547   SDValue BaseShAmt = SDValue();
10548   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10549     unsigned NumElts = VT.getVectorNumElements();
10550     unsigned i = 0;
10551     for (; i != NumElts; ++i) {
10552       SDValue Arg = ShAmtOp.getOperand(i);
10553       if (Arg.getOpcode() == ISD::UNDEF) continue;
10554       BaseShAmt = Arg;
10555       break;
10556     }
10557     for (; i != NumElts; ++i) {
10558       SDValue Arg = ShAmtOp.getOperand(i);
10559       if (Arg.getOpcode() == ISD::UNDEF) continue;
10560       if (Arg != BaseShAmt) {
10561         return SDValue();
10562       }
10563     }
10564   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10565              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10566     SDValue InVec = ShAmtOp.getOperand(0);
10567     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10568       unsigned NumElts = InVec.getValueType().getVectorNumElements();
10569       unsigned i = 0;
10570       for (; i != NumElts; ++i) {
10571         SDValue Arg = InVec.getOperand(i);
10572         if (Arg.getOpcode() == ISD::UNDEF) continue;
10573         BaseShAmt = Arg;
10574         break;
10575       }
10576     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10577        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10578          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10579          if (C->getZExtValue() == SplatIdx)
10580            BaseShAmt = InVec.getOperand(1);
10581        }
10582     }
10583     if (BaseShAmt.getNode() == 0)
10584       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10585                               DAG.getIntPtrConstant(0));
10586   } else
10587     return SDValue();
10588
10589   // The shift amount is an i32.
10590   if (EltVT.bitsGT(MVT::i32))
10591     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10592   else if (EltVT.bitsLT(MVT::i32))
10593     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10594
10595   // The shift amount is identical so we can do a vector shift.
10596   SDValue  ValOp = N->getOperand(0);
10597   switch (N->getOpcode()) {
10598   default:
10599     llvm_unreachable("Unknown shift opcode!");
10600     break;
10601   case ISD::SHL:
10602     if (VT == MVT::v2i64)
10603       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10604                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10605                          ValOp, BaseShAmt);
10606     if (VT == MVT::v4i32)
10607       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10608                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10609                          ValOp, BaseShAmt);
10610     if (VT == MVT::v8i16)
10611       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10612                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10613                          ValOp, BaseShAmt);
10614     break;
10615   case ISD::SRA:
10616     if (VT == MVT::v4i32)
10617       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10618                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10619                          ValOp, BaseShAmt);
10620     if (VT == MVT::v8i16)
10621       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10622                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10623                          ValOp, BaseShAmt);
10624     break;
10625   case ISD::SRL:
10626     if (VT == MVT::v2i64)
10627       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10628                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10629                          ValOp, BaseShAmt);
10630     if (VT == MVT::v4i32)
10631       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10632                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10633                          ValOp, BaseShAmt);
10634     if (VT ==  MVT::v8i16)
10635       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10636                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10637                          ValOp, BaseShAmt);
10638     break;
10639   }
10640   return SDValue();
10641 }
10642
10643 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10644                                 TargetLowering::DAGCombinerInfo &DCI,
10645                                 const X86Subtarget *Subtarget) {
10646   if (DCI.isBeforeLegalizeOps())
10647     return SDValue();
10648
10649   EVT VT = N->getValueType(0);
10650   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10651     return SDValue();
10652
10653   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10654   SDValue N0 = N->getOperand(0);
10655   SDValue N1 = N->getOperand(1);
10656   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10657     std::swap(N0, N1);
10658   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10659     return SDValue();
10660   if (!N0.hasOneUse() || !N1.hasOneUse())
10661     return SDValue();
10662
10663   SDValue ShAmt0 = N0.getOperand(1);
10664   if (ShAmt0.getValueType() != MVT::i8)
10665     return SDValue();
10666   SDValue ShAmt1 = N1.getOperand(1);
10667   if (ShAmt1.getValueType() != MVT::i8)
10668     return SDValue();
10669   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10670     ShAmt0 = ShAmt0.getOperand(0);
10671   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10672     ShAmt1 = ShAmt1.getOperand(0);
10673
10674   DebugLoc DL = N->getDebugLoc();
10675   unsigned Opc = X86ISD::SHLD;
10676   SDValue Op0 = N0.getOperand(0);
10677   SDValue Op1 = N1.getOperand(0);
10678   if (ShAmt0.getOpcode() == ISD::SUB) {
10679     Opc = X86ISD::SHRD;
10680     std::swap(Op0, Op1);
10681     std::swap(ShAmt0, ShAmt1);
10682   }
10683
10684   unsigned Bits = VT.getSizeInBits();
10685   if (ShAmt1.getOpcode() == ISD::SUB) {
10686     SDValue Sum = ShAmt1.getOperand(0);
10687     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10688       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10689       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10690         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10691       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10692         return DAG.getNode(Opc, DL, VT,
10693                            Op0, Op1,
10694                            DAG.getNode(ISD::TRUNCATE, DL,
10695                                        MVT::i8, ShAmt0));
10696     }
10697   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10698     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10699     if (ShAmt0C &&
10700         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10701       return DAG.getNode(Opc, DL, VT,
10702                          N0.getOperand(0), N1.getOperand(0),
10703                          DAG.getNode(ISD::TRUNCATE, DL,
10704                                        MVT::i8, ShAmt0));
10705   }
10706
10707   return SDValue();
10708 }
10709
10710 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10711 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10712                                    const X86Subtarget *Subtarget) {
10713   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
10714   // the FP state in cases where an emms may be missing.
10715   // A preferable solution to the general problem is to figure out the right
10716   // places to insert EMMS.  This qualifies as a quick hack.
10717
10718   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10719   StoreSDNode *St = cast<StoreSDNode>(N);
10720   EVT VT = St->getValue().getValueType();
10721   if (VT.getSizeInBits() != 64)
10722     return SDValue();
10723
10724   const Function *F = DAG.getMachineFunction().getFunction();
10725   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10726   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10727     && Subtarget->hasSSE2();
10728   if ((VT.isVector() ||
10729        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10730       isa<LoadSDNode>(St->getValue()) &&
10731       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10732       St->getChain().hasOneUse() && !St->isVolatile()) {
10733     SDNode* LdVal = St->getValue().getNode();
10734     LoadSDNode *Ld = 0;
10735     int TokenFactorIndex = -1;
10736     SmallVector<SDValue, 8> Ops;
10737     SDNode* ChainVal = St->getChain().getNode();
10738     // Must be a store of a load.  We currently handle two cases:  the load
10739     // is a direct child, and it's under an intervening TokenFactor.  It is
10740     // possible to dig deeper under nested TokenFactors.
10741     if (ChainVal == LdVal)
10742       Ld = cast<LoadSDNode>(St->getChain());
10743     else if (St->getValue().hasOneUse() &&
10744              ChainVal->getOpcode() == ISD::TokenFactor) {
10745       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10746         if (ChainVal->getOperand(i).getNode() == LdVal) {
10747           TokenFactorIndex = i;
10748           Ld = cast<LoadSDNode>(St->getValue());
10749         } else
10750           Ops.push_back(ChainVal->getOperand(i));
10751       }
10752     }
10753
10754     if (!Ld || !ISD::isNormalLoad(Ld))
10755       return SDValue();
10756
10757     // If this is not the MMX case, i.e. we are just turning i64 load/store
10758     // into f64 load/store, avoid the transformation if there are multiple
10759     // uses of the loaded value.
10760     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10761       return SDValue();
10762
10763     DebugLoc LdDL = Ld->getDebugLoc();
10764     DebugLoc StDL = N->getDebugLoc();
10765     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10766     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10767     // pair instead.
10768     if (Subtarget->is64Bit() || F64IsLegal) {
10769       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10770       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
10771                                   Ld->getPointerInfo(), Ld->isVolatile(),
10772                                   Ld->isNonTemporal(), Ld->getAlignment());
10773       SDValue NewChain = NewLd.getValue(1);
10774       if (TokenFactorIndex != -1) {
10775         Ops.push_back(NewChain);
10776         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10777                                Ops.size());
10778       }
10779       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10780                           St->getPointerInfo(),
10781                           St->isVolatile(), St->isNonTemporal(),
10782                           St->getAlignment());
10783     }
10784
10785     // Otherwise, lower to two pairs of 32-bit loads / stores.
10786     SDValue LoAddr = Ld->getBasePtr();
10787     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10788                                  DAG.getConstant(4, MVT::i32));
10789
10790     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10791                                Ld->getPointerInfo(),
10792                                Ld->isVolatile(), Ld->isNonTemporal(),
10793                                Ld->getAlignment());
10794     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10795                                Ld->getPointerInfo().getWithOffset(4),
10796                                Ld->isVolatile(), Ld->isNonTemporal(),
10797                                MinAlign(Ld->getAlignment(), 4));
10798
10799     SDValue NewChain = LoLd.getValue(1);
10800     if (TokenFactorIndex != -1) {
10801       Ops.push_back(LoLd);
10802       Ops.push_back(HiLd);
10803       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10804                              Ops.size());
10805     }
10806
10807     LoAddr = St->getBasePtr();
10808     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10809                          DAG.getConstant(4, MVT::i32));
10810
10811     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10812                                 St->getPointerInfo(),
10813                                 St->isVolatile(), St->isNonTemporal(),
10814                                 St->getAlignment());
10815     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10816                                 St->getPointerInfo().getWithOffset(4),
10817                                 St->isVolatile(),
10818                                 St->isNonTemporal(),
10819                                 MinAlign(St->getAlignment(), 4));
10820     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10821   }
10822   return SDValue();
10823 }
10824
10825 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10826 /// X86ISD::FXOR nodes.
10827 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10828   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10829   // F[X]OR(0.0, x) -> x
10830   // F[X]OR(x, 0.0) -> x
10831   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10832     if (C->getValueAPF().isPosZero())
10833       return N->getOperand(1);
10834   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10835     if (C->getValueAPF().isPosZero())
10836       return N->getOperand(0);
10837   return SDValue();
10838 }
10839
10840 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10841 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10842   // FAND(0.0, x) -> 0.0
10843   // FAND(x, 0.0) -> 0.0
10844   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10845     if (C->getValueAPF().isPosZero())
10846       return N->getOperand(0);
10847   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10848     if (C->getValueAPF().isPosZero())
10849       return N->getOperand(1);
10850   return SDValue();
10851 }
10852
10853 static SDValue PerformBTCombine(SDNode *N,
10854                                 SelectionDAG &DAG,
10855                                 TargetLowering::DAGCombinerInfo &DCI) {
10856   // BT ignores high bits in the bit index operand.
10857   SDValue Op1 = N->getOperand(1);
10858   if (Op1.hasOneUse()) {
10859     unsigned BitWidth = Op1.getValueSizeInBits();
10860     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10861     APInt KnownZero, KnownOne;
10862     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10863                                           !DCI.isBeforeLegalizeOps());
10864     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10865     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10866         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10867       DCI.CommitTargetLoweringOpt(TLO);
10868   }
10869   return SDValue();
10870 }
10871
10872 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10873   SDValue Op = N->getOperand(0);
10874   if (Op.getOpcode() == ISD::BIT_CONVERT)
10875     Op = Op.getOperand(0);
10876   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10877   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10878       VT.getVectorElementType().getSizeInBits() ==
10879       OpVT.getVectorElementType().getSizeInBits()) {
10880     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10881   }
10882   return SDValue();
10883 }
10884
10885 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10886   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
10887   //           (and (i32 x86isd::setcc_carry), 1)
10888   // This eliminates the zext. This transformation is necessary because
10889   // ISD::SETCC is always legalized to i8.
10890   DebugLoc dl = N->getDebugLoc();
10891   SDValue N0 = N->getOperand(0);
10892   EVT VT = N->getValueType(0);
10893   if (N0.getOpcode() == ISD::AND &&
10894       N0.hasOneUse() &&
10895       N0.getOperand(0).hasOneUse()) {
10896     SDValue N00 = N0.getOperand(0);
10897     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10898       return SDValue();
10899     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10900     if (!C || C->getZExtValue() != 1)
10901       return SDValue();
10902     return DAG.getNode(ISD::AND, dl, VT,
10903                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10904                                    N00.getOperand(0), N00.getOperand(1)),
10905                        DAG.getConstant(1, VT));
10906   }
10907
10908   return SDValue();
10909 }
10910
10911 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10912                                              DAGCombinerInfo &DCI) const {
10913   SelectionDAG &DAG = DCI.DAG;
10914   switch (N->getOpcode()) {
10915   default: break;
10916   case ISD::EXTRACT_VECTOR_ELT:
10917                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10918   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
10919   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
10920   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
10921   case ISD::SHL:
10922   case ISD::SRA:
10923   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
10924   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
10925   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
10926   case X86ISD::FXOR:
10927   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
10928   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
10929   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
10930   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
10931   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
10932   case X86ISD::SHUFPS:      // Handle all target specific shuffles
10933   case X86ISD::SHUFPD:
10934   case X86ISD::PALIGN:
10935   case X86ISD::PUNPCKHBW:
10936   case X86ISD::PUNPCKHWD:
10937   case X86ISD::PUNPCKHDQ:
10938   case X86ISD::PUNPCKHQDQ:
10939   case X86ISD::UNPCKHPS:
10940   case X86ISD::UNPCKHPD:
10941   case X86ISD::PUNPCKLBW:
10942   case X86ISD::PUNPCKLWD:
10943   case X86ISD::PUNPCKLDQ:
10944   case X86ISD::PUNPCKLQDQ:
10945   case X86ISD::UNPCKLPS:
10946   case X86ISD::UNPCKLPD:
10947   case X86ISD::MOVHLPS:
10948   case X86ISD::MOVLHPS:
10949   case X86ISD::PSHUFD:
10950   case X86ISD::PSHUFHW:
10951   case X86ISD::PSHUFLW:
10952   case X86ISD::MOVSS:
10953   case X86ISD::MOVSD:
10954   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10955   }
10956
10957   return SDValue();
10958 }
10959
10960 /// isTypeDesirableForOp - Return true if the target has native support for
10961 /// the specified value type and it is 'desirable' to use the type for the
10962 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10963 /// instruction encodings are longer and some i16 instructions are slow.
10964 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10965   if (!isTypeLegal(VT))
10966     return false;
10967   if (VT != MVT::i16)
10968     return true;
10969
10970   switch (Opc) {
10971   default:
10972     return true;
10973   case ISD::LOAD:
10974   case ISD::SIGN_EXTEND:
10975   case ISD::ZERO_EXTEND:
10976   case ISD::ANY_EXTEND:
10977   case ISD::SHL:
10978   case ISD::SRL:
10979   case ISD::SUB:
10980   case ISD::ADD:
10981   case ISD::MUL:
10982   case ISD::AND:
10983   case ISD::OR:
10984   case ISD::XOR:
10985     return false;
10986   }
10987 }
10988
10989 /// IsDesirableToPromoteOp - This method query the target whether it is
10990 /// beneficial for dag combiner to promote the specified node. If true, it
10991 /// should return the desired promotion type by reference.
10992 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10993   EVT VT = Op.getValueType();
10994   if (VT != MVT::i16)
10995     return false;
10996
10997   bool Promote = false;
10998   bool Commute = false;
10999   switch (Op.getOpcode()) {
11000   default: break;
11001   case ISD::LOAD: {
11002     LoadSDNode *LD = cast<LoadSDNode>(Op);
11003     // If the non-extending load has a single use and it's not live out, then it
11004     // might be folded.
11005     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11006                                                      Op.hasOneUse()*/) {
11007       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11008              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11009         // The only case where we'd want to promote LOAD (rather then it being
11010         // promoted as an operand is when it's only use is liveout.
11011         if (UI->getOpcode() != ISD::CopyToReg)
11012           return false;
11013       }
11014     }
11015     Promote = true;
11016     break;
11017   }
11018   case ISD::SIGN_EXTEND:
11019   case ISD::ZERO_EXTEND:
11020   case ISD::ANY_EXTEND:
11021     Promote = true;
11022     break;
11023   case ISD::SHL:
11024   case ISD::SRL: {
11025     SDValue N0 = Op.getOperand(0);
11026     // Look out for (store (shl (load), x)).
11027     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11028       return false;
11029     Promote = true;
11030     break;
11031   }
11032   case ISD::ADD:
11033   case ISD::MUL:
11034   case ISD::AND:
11035   case ISD::OR:
11036   case ISD::XOR:
11037     Commute = true;
11038     // fallthrough
11039   case ISD::SUB: {
11040     SDValue N0 = Op.getOperand(0);
11041     SDValue N1 = Op.getOperand(1);
11042     if (!Commute && MayFoldLoad(N1))
11043       return false;
11044     // Avoid disabling potential load folding opportunities.
11045     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11046       return false;
11047     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11048       return false;
11049     Promote = true;
11050   }
11051   }
11052
11053   PVT = MVT::i32;
11054   return Promote;
11055 }
11056
11057 //===----------------------------------------------------------------------===//
11058 //                           X86 Inline Assembly Support
11059 //===----------------------------------------------------------------------===//
11060
11061 static bool LowerToBSwap(CallInst *CI) {
11062   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11063   // we will turn this bswap into something that will be lowered to logical ops
11064   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11065   // so don't worry about this.
11066
11067   // Verify this is a simple bswap.
11068   if (CI->getNumArgOperands() != 1 ||
11069       CI->getType() != CI->getArgOperand(0)->getType() ||
11070       !CI->getType()->isIntegerTy())
11071     return false;
11072
11073   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11074   if (!Ty || Ty->getBitWidth() % 16 != 0)
11075     return false;
11076
11077   // Okay, we can do this xform, do so now.
11078   const Type *Tys[] = { Ty };
11079   Module *M = CI->getParent()->getParent()->getParent();
11080   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11081
11082   Value *Op = CI->getArgOperand(0);
11083   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11084
11085   CI->replaceAllUsesWith(Op);
11086   CI->eraseFromParent();
11087   return true;
11088 }
11089
11090 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11091   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11092   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11093
11094   std::string AsmStr = IA->getAsmString();
11095
11096   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11097   SmallVector<StringRef, 4> AsmPieces;
11098   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
11099
11100   switch (AsmPieces.size()) {
11101   default: return false;
11102   case 1:
11103     AsmStr = AsmPieces[0];
11104     AsmPieces.clear();
11105     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11106
11107     // bswap $0
11108     if (AsmPieces.size() == 2 &&
11109         (AsmPieces[0] == "bswap" ||
11110          AsmPieces[0] == "bswapq" ||
11111          AsmPieces[0] == "bswapl") &&
11112         (AsmPieces[1] == "$0" ||
11113          AsmPieces[1] == "${0:q}")) {
11114       // No need to check constraints, nothing other than the equivalent of
11115       // "=r,0" would be valid here.
11116       return LowerToBSwap(CI);
11117     }
11118     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11119     if (CI->getType()->isIntegerTy(16) &&
11120         AsmPieces.size() == 3 &&
11121         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11122         AsmPieces[1] == "$$8," &&
11123         AsmPieces[2] == "${0:w}" &&
11124         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11125       AsmPieces.clear();
11126       const std::string &Constraints = IA->getConstraintString();
11127       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11128       std::sort(AsmPieces.begin(), AsmPieces.end());
11129       if (AsmPieces.size() == 4 &&
11130           AsmPieces[0] == "~{cc}" &&
11131           AsmPieces[1] == "~{dirflag}" &&
11132           AsmPieces[2] == "~{flags}" &&
11133           AsmPieces[3] == "~{fpsr}") {
11134         return LowerToBSwap(CI);
11135       }
11136     }
11137     break;
11138   case 3:
11139     if (CI->getType()->isIntegerTy(64) &&
11140         Constraints.size() >= 2 &&
11141         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11142         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11143       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11144       SmallVector<StringRef, 4> Words;
11145       SplitString(AsmPieces[0], Words, " \t");
11146       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11147         Words.clear();
11148         SplitString(AsmPieces[1], Words, " \t");
11149         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11150           Words.clear();
11151           SplitString(AsmPieces[2], Words, " \t,");
11152           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11153               Words[2] == "%edx") {
11154             return LowerToBSwap(CI);
11155           }
11156         }
11157       }
11158     }
11159     break;
11160   }
11161   return false;
11162 }
11163
11164
11165
11166 /// getConstraintType - Given a constraint letter, return the type of
11167 /// constraint it is for this target.
11168 X86TargetLowering::ConstraintType
11169 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11170   if (Constraint.size() == 1) {
11171     switch (Constraint[0]) {
11172     case 'A':
11173       return C_Register;
11174     case 'f':
11175     case 'r':
11176     case 'R':
11177     case 'l':
11178     case 'q':
11179     case 'Q':
11180     case 'x':
11181     case 'y':
11182     case 'Y':
11183       return C_RegisterClass;
11184     case 'e':
11185     case 'Z':
11186       return C_Other;
11187     default:
11188       break;
11189     }
11190   }
11191   return TargetLowering::getConstraintType(Constraint);
11192 }
11193
11194 /// Examine constraint type and operand type and determine a weight value,
11195 /// where: -1 = invalid match, and 0 = so-so match to 3 = good match.
11196 /// This object must already have been set up with the operand type
11197 /// and the current alternative constraint selected.
11198 int X86TargetLowering::getSingleConstraintMatchWeight(
11199     AsmOperandInfo &info, const char *constraint) const {
11200   int weight = -1;
11201   Value *CallOperandVal = info.CallOperandVal;
11202     // If we don't have a value, we can't do a match,
11203     // but allow it at the lowest weight.
11204   if (CallOperandVal == NULL)
11205     return 0;
11206   // Look at the constraint type.
11207   switch (*constraint) {
11208   default:
11209     return TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11210     break;
11211   case 'I':
11212     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11213       if (C->getZExtValue() <= 31)
11214         weight = 3;
11215     }
11216     break;
11217   // etc.
11218   }
11219   return weight;
11220 }
11221
11222 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11223 /// with another that has more specific requirements based on the type of the
11224 /// corresponding operand.
11225 const char *X86TargetLowering::
11226 LowerXConstraint(EVT ConstraintVT) const {
11227   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11228   // 'f' like normal targets.
11229   if (ConstraintVT.isFloatingPoint()) {
11230     if (Subtarget->hasSSE2())
11231       return "Y";
11232     if (Subtarget->hasSSE1())
11233       return "x";
11234   }
11235
11236   return TargetLowering::LowerXConstraint(ConstraintVT);
11237 }
11238
11239 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11240 /// vector.  If it is invalid, don't add anything to Ops.
11241 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11242                                                      char Constraint,
11243                                                      std::vector<SDValue>&Ops,
11244                                                      SelectionDAG &DAG) const {
11245   SDValue Result(0, 0);
11246
11247   switch (Constraint) {
11248   default: break;
11249   case 'I':
11250     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11251       if (C->getZExtValue() <= 31) {
11252         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11253         break;
11254       }
11255     }
11256     return;
11257   case 'J':
11258     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11259       if (C->getZExtValue() <= 63) {
11260         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11261         break;
11262       }
11263     }
11264     return;
11265   case 'K':
11266     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11267       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11268         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11269         break;
11270       }
11271     }
11272     return;
11273   case 'N':
11274     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11275       if (C->getZExtValue() <= 255) {
11276         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11277         break;
11278       }
11279     }
11280     return;
11281   case 'e': {
11282     // 32-bit signed value
11283     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11284       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11285                                            C->getSExtValue())) {
11286         // Widen to 64 bits here to get it sign extended.
11287         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11288         break;
11289       }
11290     // FIXME gcc accepts some relocatable values here too, but only in certain
11291     // memory models; it's complicated.
11292     }
11293     return;
11294   }
11295   case 'Z': {
11296     // 32-bit unsigned value
11297     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11298       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11299                                            C->getZExtValue())) {
11300         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11301         break;
11302       }
11303     }
11304     // FIXME gcc accepts some relocatable values here too, but only in certain
11305     // memory models; it's complicated.
11306     return;
11307   }
11308   case 'i': {
11309     // Literal immediates are always ok.
11310     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11311       // Widen to 64 bits here to get it sign extended.
11312       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11313       break;
11314     }
11315
11316     // In any sort of PIC mode addresses need to be computed at runtime by
11317     // adding in a register or some sort of table lookup.  These can't
11318     // be used as immediates.
11319     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11320       return;
11321
11322     // If we are in non-pic codegen mode, we allow the address of a global (with
11323     // an optional displacement) to be used with 'i'.
11324     GlobalAddressSDNode *GA = 0;
11325     int64_t Offset = 0;
11326
11327     // Match either (GA), (GA+C), (GA+C1+C2), etc.
11328     while (1) {
11329       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11330         Offset += GA->getOffset();
11331         break;
11332       } else if (Op.getOpcode() == ISD::ADD) {
11333         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11334           Offset += C->getZExtValue();
11335           Op = Op.getOperand(0);
11336           continue;
11337         }
11338       } else if (Op.getOpcode() == ISD::SUB) {
11339         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11340           Offset += -C->getZExtValue();
11341           Op = Op.getOperand(0);
11342           continue;
11343         }
11344       }
11345
11346       // Otherwise, this isn't something we can handle, reject it.
11347       return;
11348     }
11349
11350     const GlobalValue *GV = GA->getGlobal();
11351     // If we require an extra load to get this address, as in PIC mode, we
11352     // can't accept it.
11353     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11354                                                         getTargetMachine())))
11355       return;
11356
11357     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11358                                         GA->getValueType(0), Offset);
11359     break;
11360   }
11361   }
11362
11363   if (Result.getNode()) {
11364     Ops.push_back(Result);
11365     return;
11366   }
11367   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11368 }
11369
11370 std::vector<unsigned> X86TargetLowering::
11371 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11372                                   EVT VT) const {
11373   if (Constraint.size() == 1) {
11374     // FIXME: not handling fp-stack yet!
11375     switch (Constraint[0]) {      // GCC X86 Constraint Letters
11376     default: break;  // Unknown constraint letter
11377     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11378       if (Subtarget->is64Bit()) {
11379         if (VT == MVT::i32)
11380           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11381                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11382                                        X86::R10D,X86::R11D,X86::R12D,
11383                                        X86::R13D,X86::R14D,X86::R15D,
11384                                        X86::EBP, X86::ESP, 0);
11385         else if (VT == MVT::i16)
11386           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
11387                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
11388                                        X86::R10W,X86::R11W,X86::R12W,
11389                                        X86::R13W,X86::R14W,X86::R15W,
11390                                        X86::BP,  X86::SP, 0);
11391         else if (VT == MVT::i8)
11392           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
11393                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11394                                        X86::R10B,X86::R11B,X86::R12B,
11395                                        X86::R13B,X86::R14B,X86::R15B,
11396                                        X86::BPL, X86::SPL, 0);
11397
11398         else if (VT == MVT::i64)
11399           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11400                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
11401                                        X86::R10, X86::R11, X86::R12,
11402                                        X86::R13, X86::R14, X86::R15,
11403                                        X86::RBP, X86::RSP, 0);
11404
11405         break;
11406       }
11407       // 32-bit fallthrough
11408     case 'Q':   // Q_REGS
11409       if (VT == MVT::i32)
11410         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11411       else if (VT == MVT::i16)
11412         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11413       else if (VT == MVT::i8)
11414         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11415       else if (VT == MVT::i64)
11416         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11417       break;
11418     }
11419   }
11420
11421   return std::vector<unsigned>();
11422 }
11423
11424 std::pair<unsigned, const TargetRegisterClass*>
11425 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11426                                                 EVT VT) const {
11427   // First, see if this is a constraint that directly corresponds to an LLVM
11428   // register class.
11429   if (Constraint.size() == 1) {
11430     // GCC Constraint Letters
11431     switch (Constraint[0]) {
11432     default: break;
11433     case 'r':   // GENERAL_REGS
11434     case 'l':   // INDEX_REGS
11435       if (VT == MVT::i8)
11436         return std::make_pair(0U, X86::GR8RegisterClass);
11437       if (VT == MVT::i16)
11438         return std::make_pair(0U, X86::GR16RegisterClass);
11439       if (VT == MVT::i32 || !Subtarget->is64Bit())
11440         return std::make_pair(0U, X86::GR32RegisterClass);
11441       return std::make_pair(0U, X86::GR64RegisterClass);
11442     case 'R':   // LEGACY_REGS
11443       if (VT == MVT::i8)
11444         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11445       if (VT == MVT::i16)
11446         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11447       if (VT == MVT::i32 || !Subtarget->is64Bit())
11448         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11449       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11450     case 'f':  // FP Stack registers.
11451       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11452       // value to the correct fpstack register class.
11453       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11454         return std::make_pair(0U, X86::RFP32RegisterClass);
11455       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11456         return std::make_pair(0U, X86::RFP64RegisterClass);
11457       return std::make_pair(0U, X86::RFP80RegisterClass);
11458     case 'y':   // MMX_REGS if MMX allowed.
11459       if (!Subtarget->hasMMX()) break;
11460       return std::make_pair(0U, X86::VR64RegisterClass);
11461     case 'Y':   // SSE_REGS if SSE2 allowed
11462       if (!Subtarget->hasSSE2()) break;
11463       // FALL THROUGH.
11464     case 'x':   // SSE_REGS if SSE1 allowed
11465       if (!Subtarget->hasSSE1()) break;
11466
11467       switch (VT.getSimpleVT().SimpleTy) {
11468       default: break;
11469       // Scalar SSE types.
11470       case MVT::f32:
11471       case MVT::i32:
11472         return std::make_pair(0U, X86::FR32RegisterClass);
11473       case MVT::f64:
11474       case MVT::i64:
11475         return std::make_pair(0U, X86::FR64RegisterClass);
11476       // Vector types.
11477       case MVT::v16i8:
11478       case MVT::v8i16:
11479       case MVT::v4i32:
11480       case MVT::v2i64:
11481       case MVT::v4f32:
11482       case MVT::v2f64:
11483         return std::make_pair(0U, X86::VR128RegisterClass);
11484       }
11485       break;
11486     }
11487   }
11488
11489   // Use the default implementation in TargetLowering to convert the register
11490   // constraint into a member of a register class.
11491   std::pair<unsigned, const TargetRegisterClass*> Res;
11492   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11493
11494   // Not found as a standard register?
11495   if (Res.second == 0) {
11496     // Map st(0) -> st(7) -> ST0
11497     if (Constraint.size() == 7 && Constraint[0] == '{' &&
11498         tolower(Constraint[1]) == 's' &&
11499         tolower(Constraint[2]) == 't' &&
11500         Constraint[3] == '(' &&
11501         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11502         Constraint[5] == ')' &&
11503         Constraint[6] == '}') {
11504
11505       Res.first = X86::ST0+Constraint[4]-'0';
11506       Res.second = X86::RFP80RegisterClass;
11507       return Res;
11508     }
11509
11510     // GCC allows "st(0)" to be called just plain "st".
11511     if (StringRef("{st}").equals_lower(Constraint)) {
11512       Res.first = X86::ST0;
11513       Res.second = X86::RFP80RegisterClass;
11514       return Res;
11515     }
11516
11517     // flags -> EFLAGS
11518     if (StringRef("{flags}").equals_lower(Constraint)) {
11519       Res.first = X86::EFLAGS;
11520       Res.second = X86::CCRRegisterClass;
11521       return Res;
11522     }
11523
11524     // 'A' means EAX + EDX.
11525     if (Constraint == "A") {
11526       Res.first = X86::EAX;
11527       Res.second = X86::GR32_ADRegisterClass;
11528       return Res;
11529     }
11530     return Res;
11531   }
11532
11533   // Otherwise, check to see if this is a register class of the wrong value
11534   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11535   // turn into {ax},{dx}.
11536   if (Res.second->hasType(VT))
11537     return Res;   // Correct type already, nothing to do.
11538
11539   // All of the single-register GCC register classes map their values onto
11540   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
11541   // really want an 8-bit or 32-bit register, map to the appropriate register
11542   // class and return the appropriate register.
11543   if (Res.second == X86::GR16RegisterClass) {
11544     if (VT == MVT::i8) {
11545       unsigned DestReg = 0;
11546       switch (Res.first) {
11547       default: break;
11548       case X86::AX: DestReg = X86::AL; break;
11549       case X86::DX: DestReg = X86::DL; break;
11550       case X86::CX: DestReg = X86::CL; break;
11551       case X86::BX: DestReg = X86::BL; break;
11552       }
11553       if (DestReg) {
11554         Res.first = DestReg;
11555         Res.second = X86::GR8RegisterClass;
11556       }
11557     } else if (VT == MVT::i32) {
11558       unsigned DestReg = 0;
11559       switch (Res.first) {
11560       default: break;
11561       case X86::AX: DestReg = X86::EAX; break;
11562       case X86::DX: DestReg = X86::EDX; break;
11563       case X86::CX: DestReg = X86::ECX; break;
11564       case X86::BX: DestReg = X86::EBX; break;
11565       case X86::SI: DestReg = X86::ESI; break;
11566       case X86::DI: DestReg = X86::EDI; break;
11567       case X86::BP: DestReg = X86::EBP; break;
11568       case X86::SP: DestReg = X86::ESP; break;
11569       }
11570       if (DestReg) {
11571         Res.first = DestReg;
11572         Res.second = X86::GR32RegisterClass;
11573       }
11574     } else if (VT == MVT::i64) {
11575       unsigned DestReg = 0;
11576       switch (Res.first) {
11577       default: break;
11578       case X86::AX: DestReg = X86::RAX; break;
11579       case X86::DX: DestReg = X86::RDX; break;
11580       case X86::CX: DestReg = X86::RCX; break;
11581       case X86::BX: DestReg = X86::RBX; break;
11582       case X86::SI: DestReg = X86::RSI; break;
11583       case X86::DI: DestReg = X86::RDI; break;
11584       case X86::BP: DestReg = X86::RBP; break;
11585       case X86::SP: DestReg = X86::RSP; break;
11586       }
11587       if (DestReg) {
11588         Res.first = DestReg;
11589         Res.second = X86::GR64RegisterClass;
11590       }
11591     }
11592   } else if (Res.second == X86::FR32RegisterClass ||
11593              Res.second == X86::FR64RegisterClass ||
11594              Res.second == X86::VR128RegisterClass) {
11595     // Handle references to XMM physical registers that got mapped into the
11596     // wrong class.  This can happen with constraints like {xmm0} where the
11597     // target independent register mapper will just pick the first match it can
11598     // find, ignoring the required type.
11599     if (VT == MVT::f32)
11600       Res.second = X86::FR32RegisterClass;
11601     else if (VT == MVT::f64)
11602       Res.second = X86::FR64RegisterClass;
11603     else if (X86::VR128RegisterClass->hasType(VT))
11604       Res.second = X86::VR128RegisterClass;
11605   }
11606
11607   return Res;
11608 }