convert a couple more places to use the new getStore()
[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; i64->MMX is Legal.
222       if (Subtarget->hasMMX() && !DisableMMX)
223         setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Custom);
224       else 
225         setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Expand);
226     }
227   }
228
229   // Scalar integer divide and remainder are lowered to use operations that
230   // produce two results, to match the available instructions. This exposes
231   // the two-result form to trivial CSE, which is able to combine x/y and x%y
232   // into a single instruction.
233   //
234   // Scalar integer multiply-high is also lowered to use two-result
235   // operations, to match the available instructions. However, plain multiply
236   // (low) operations are left as Legal, as there are single-result
237   // instructions for this in x86. Using the two-result multiply instructions
238   // when both high and low results are needed must be arranged by dagcombine.
239   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
240   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
241   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
242   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
243   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
244   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
245   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
246   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
247   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
248   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
249   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
250   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
251   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
252   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
253   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
254   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
255   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
256   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
257   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
258   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
259   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
260   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
261   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
262   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
263
264   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
265   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
266   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
267   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
268   if (Subtarget->is64Bit())
269     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
270   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
271   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
272   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
273   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
274   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
275   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
276   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
277   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
278
279   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
280   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
281   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
282   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
283   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
284   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
285   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
286   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
287   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
288   if (Subtarget->is64Bit()) {
289     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
290     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
291     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
292   }
293
294   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
295   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
296
297   // These should be promoted to a larger select which is supported.
298   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
299   // X86 wants to expand cmov itself.
300   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
301   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
302   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
303   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
304   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
305   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
306   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
307   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
308   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
309   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
310   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
311   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
312   if (Subtarget->is64Bit()) {
313     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
314     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
315   }
316   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
317
318   // Darwin ABI issue.
319   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
320   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
321   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
322   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
323   if (Subtarget->is64Bit())
324     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
325   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
326   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
327   if (Subtarget->is64Bit()) {
328     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
329     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
330     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
331     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
332     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
333   }
334   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
335   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
336   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
337   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
338   if (Subtarget->is64Bit()) {
339     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
340     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
341     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasSSE1())
345     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
346
347   // We may not have a libcall for MEMBARRIER so we should lower this.
348   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
349   
350   // On X86 and X86-64, atomic operations are lowered to locked instructions.
351   // Locked instructions, in turn, have implicit fence semantics (all memory
352   // operations are flushed before issuing the locked instruction, and they
353   // are not buffered), so we can fold away the common pattern of
354   // fence-atomic-fence.
355   setShouldFoldAtomicFences(true);
356
357   // Expand certain atomics
358   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
359   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
360   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
361   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
362
363   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
364   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
365   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
366   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
367
368   if (!Subtarget->is64Bit()) {
369     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
370     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
371     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
372     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
373     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
374     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
375     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
376   }
377
378   // FIXME - use subtarget debug flags
379   if (!Subtarget->isTargetDarwin() &&
380       !Subtarget->isTargetELF() &&
381       !Subtarget->isTargetCygMing()) {
382     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
383   }
384
385   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
386   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
387   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
388   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
389   if (Subtarget->is64Bit()) {
390     setExceptionPointerRegister(X86::RAX);
391     setExceptionSelectorRegister(X86::RDX);
392   } else {
393     setExceptionPointerRegister(X86::EAX);
394     setExceptionSelectorRegister(X86::EDX);
395   }
396   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
397   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
398
399   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
400
401   setOperationAction(ISD::TRAP, MVT::Other, Legal);
402
403   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
404   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
405   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
406   if (Subtarget->is64Bit()) {
407     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
408     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
409   } else {
410     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
411     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
412   }
413
414   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
415   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
416   if (Subtarget->is64Bit())
417     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
418   if (Subtarget->isTargetCygMing())
419     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
420   else
421     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
422
423   if (!UseSoftFloat && X86ScalarSSEf64) {
424     // f32 and f64 use SSE.
425     // Set up the FP register classes.
426     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
427     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
428
429     // Use ANDPD to simulate FABS.
430     setOperationAction(ISD::FABS , MVT::f64, Custom);
431     setOperationAction(ISD::FABS , MVT::f32, Custom);
432
433     // Use XORP to simulate FNEG.
434     setOperationAction(ISD::FNEG , MVT::f64, Custom);
435     setOperationAction(ISD::FNEG , MVT::f32, Custom);
436
437     // Use ANDPD and ORPD to simulate FCOPYSIGN.
438     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
439     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
440
441     // We don't support sin/cos/fmod
442     setOperationAction(ISD::FSIN , MVT::f64, Expand);
443     setOperationAction(ISD::FCOS , MVT::f64, Expand);
444     setOperationAction(ISD::FSIN , MVT::f32, Expand);
445     setOperationAction(ISD::FCOS , MVT::f32, Expand);
446
447     // Expand FP immediates into loads from the stack, except for the special
448     // cases we handle.
449     addLegalFPImmediate(APFloat(+0.0)); // xorpd
450     addLegalFPImmediate(APFloat(+0.0f)); // xorps
451   } else if (!UseSoftFloat && X86ScalarSSEf32) {
452     // Use SSE for f32, x87 for f64.
453     // Set up the FP register classes.
454     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
455     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
456
457     // Use ANDPS to simulate FABS.
458     setOperationAction(ISD::FABS , MVT::f32, Custom);
459
460     // Use XORP to simulate FNEG.
461     setOperationAction(ISD::FNEG , MVT::f32, Custom);
462
463     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
464
465     // Use ANDPS and ORPS to simulate FCOPYSIGN.
466     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
467     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
468
469     // We don't support sin/cos/fmod
470     setOperationAction(ISD::FSIN , MVT::f32, Expand);
471     setOperationAction(ISD::FCOS , MVT::f32, Expand);
472
473     // Special cases we handle for FP constants.
474     addLegalFPImmediate(APFloat(+0.0f)); // xorps
475     addLegalFPImmediate(APFloat(+0.0)); // FLD0
476     addLegalFPImmediate(APFloat(+1.0)); // FLD1
477     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
478     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
479
480     if (!UnsafeFPMath) {
481       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
482       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
483     }
484   } else if (!UseSoftFloat) {
485     // f32 and f64 in x87.
486     // Set up the FP register classes.
487     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
488     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
489
490     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
491     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
492     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
493     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
494
495     if (!UnsafeFPMath) {
496       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
497       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
498     }
499     addLegalFPImmediate(APFloat(+0.0)); // FLD0
500     addLegalFPImmediate(APFloat(+1.0)); // FLD1
501     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
502     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
503     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
504     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
505     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
506     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
507   }
508
509   // Long double always uses X87.
510   if (!UseSoftFloat) {
511     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
512     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
513     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
514     {
515       bool ignored;
516       APFloat TmpFlt(+0.0);
517       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
518                      &ignored);
519       addLegalFPImmediate(TmpFlt);  // FLD0
520       TmpFlt.changeSign();
521       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
522       APFloat TmpFlt2(+1.0);
523       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
524                       &ignored);
525       addLegalFPImmediate(TmpFlt2);  // FLD1
526       TmpFlt2.changeSign();
527       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
528     }
529
530     if (!UnsafeFPMath) {
531       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
532       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
533     }
534   }
535
536   // Always use a library call for pow.
537   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
538   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
539   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
540
541   setOperationAction(ISD::FLOG, MVT::f80, Expand);
542   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
543   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
544   setOperationAction(ISD::FEXP, MVT::f80, Expand);
545   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
546
547   // First set operation action for all vector types to either promote
548   // (for widening) or expand (for scalarization). Then we will selectively
549   // turn on ones that can be effectively codegen'd.
550   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
551        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
552     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
567     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
568     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
601     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
605     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
606          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
607       setTruncStoreAction((MVT::SimpleValueType)VT,
608                           (MVT::SimpleValueType)InnerVT, Expand);
609     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
610     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
611     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
612   }
613
614   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
615   // with -msoft-float, disable use of MMX as well.
616   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
617     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass, false);
618
619     // FIXME: Remove the rest of this stuff.
620     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
621     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
622     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
623     
624     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
625
626     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
627     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
628     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
629     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
630
631     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
632     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
633     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
634     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
635
636     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
637     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
638
639     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
640     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
641     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
642     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
643     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
644     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
645     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
646
647     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
648     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
649     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
650     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
651     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
652     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
653     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
654
655     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
656     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
657     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
658     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
659     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
660     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
661     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
662
663     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
664     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
665     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
666     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
667     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
668     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
669     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
670
671     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
672     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
673     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
674     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
675
676     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
677     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
678     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
679     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
680
681     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
682     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
683     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
684
685     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
686
687     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
688     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
689     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
690     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
691     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
692     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
693     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
694
695     if (!X86ScalarSSEf64 && Subtarget->is64Bit()) {
696       setOperationAction(ISD::BIT_CONVERT,        MVT::v8i8,  Custom);
697       setOperationAction(ISD::BIT_CONVERT,        MVT::v4i16, Custom);
698       setOperationAction(ISD::BIT_CONVERT,        MVT::v2i32, Custom);
699       setOperationAction(ISD::BIT_CONVERT,        MVT::v1i64, Custom);
700     }
701   }
702
703   if (!UseSoftFloat && Subtarget->hasSSE1()) {
704     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
705
706     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
707     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
708     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
709     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
710     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
711     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
712     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
713     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
714     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
715     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
716     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
717     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
718   }
719
720   if (!UseSoftFloat && Subtarget->hasSSE2()) {
721     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
722
723     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
724     // registers cannot be used even for integer operations.
725     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
726     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
727     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
728     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
729
730     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
731     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
732     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
733     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
734     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
735     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
736     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
737     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
738     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
739     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
740     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
741     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
742     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
743     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
744     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
745     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
746
747     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
748     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
749     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
750     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
751
752     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
753     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
754     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
755     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
756     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
757
758     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
759     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
760     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
761     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
762     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
763
764     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
765     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
766       EVT VT = (MVT::SimpleValueType)i;
767       // Do not attempt to custom lower non-power-of-2 vectors
768       if (!isPowerOf2_32(VT.getVectorNumElements()))
769         continue;
770       // Do not attempt to custom lower non-128-bit vectors
771       if (!VT.is128BitVector())
772         continue;
773       setOperationAction(ISD::BUILD_VECTOR,
774                          VT.getSimpleVT().SimpleTy, Custom);
775       setOperationAction(ISD::VECTOR_SHUFFLE,
776                          VT.getSimpleVT().SimpleTy, Custom);
777       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
778                          VT.getSimpleVT().SimpleTy, Custom);
779     }
780
781     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
782     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
783     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
784     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
785     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
786     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
787
788     if (Subtarget->is64Bit()) {
789       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
790       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
791     }
792
793     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
794     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
795       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
796       EVT VT = SVT;
797
798       // Do not attempt to promote non-128-bit vectors
799       if (!VT.is128BitVector())
800         continue;
801       
802       setOperationAction(ISD::AND,    SVT, Promote);
803       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
804       setOperationAction(ISD::OR,     SVT, Promote);
805       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
806       setOperationAction(ISD::XOR,    SVT, Promote);
807       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
808       setOperationAction(ISD::LOAD,   SVT, Promote);
809       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
810       setOperationAction(ISD::SELECT, SVT, Promote);
811       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
812     }
813
814     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
815
816     // Custom lower v2i64 and v2f64 selects.
817     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
818     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
819     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
820     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
821
822     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
823     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
824     if (!DisableMMX && Subtarget->hasMMX()) {
825       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
826       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
827     }
828   }
829
830   if (Subtarget->hasSSE41()) {
831     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
832     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
833     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
834     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
835     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
836     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
837     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
838     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
839     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
840     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
841
842     // FIXME: Do we need to handle scalar-to-vector here?
843     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
844
845     // Can turn SHL into an integer multiply.
846     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
847     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
848
849     // i8 and i16 vectors are custom , because the source register and source
850     // source memory operand types are not the same width.  f32 vectors are
851     // custom since the immediate controlling the insert encodes additional
852     // information.
853     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
854     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
855     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
856     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
857
858     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
859     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
860     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
861     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
862
863     if (Subtarget->is64Bit()) {
864       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
866     }
867   }
868
869   if (Subtarget->hasSSE42()) {
870     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
871   }
872
873   if (!UseSoftFloat && Subtarget->hasAVX()) {
874     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
875     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
876     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
877     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
878     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
879
880     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
881     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
882     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
883     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
884     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
885     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
886     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
887     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
888     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
889     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
891     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
892     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
893     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
894     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
895
896     // Operations to consider commented out -v16i16 v32i8
897     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
898     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
899     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
900     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
901     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
902     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
903     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
904     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
905     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
906     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
907     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
908     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
909     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
910     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
911
912     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
913     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
914     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
915     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
916
917     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
918     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
919     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
920     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
921     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
922
923     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
924     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
925     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
926     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
927     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
928     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
929
930 #if 0
931     // Not sure we want to do this since there are no 256-bit integer
932     // operations in AVX
933
934     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
935     // This includes 256-bit vectors
936     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
937       EVT VT = (MVT::SimpleValueType)i;
938
939       // Do not attempt to custom lower non-power-of-2 vectors
940       if (!isPowerOf2_32(VT.getVectorNumElements()))
941         continue;
942
943       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
944       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
945       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
946     }
947
948     if (Subtarget->is64Bit()) {
949       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
950       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
951     }
952 #endif
953
954 #if 0
955     // Not sure we want to do this since there are no 256-bit integer
956     // operations in AVX
957
958     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
959     // Including 256-bit vectors
960     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
961       EVT VT = (MVT::SimpleValueType)i;
962
963       if (!VT.is256BitVector()) {
964         continue;
965       }
966       setOperationAction(ISD::AND,    VT, Promote);
967       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
968       setOperationAction(ISD::OR,     VT, Promote);
969       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
970       setOperationAction(ISD::XOR,    VT, Promote);
971       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
972       setOperationAction(ISD::LOAD,   VT, Promote);
973       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
974       setOperationAction(ISD::SELECT, VT, Promote);
975       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
976     }
977
978     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
979 #endif
980   }
981
982   // We want to custom lower some of our intrinsics.
983   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
984
985   // Add/Sub/Mul with overflow operations are custom lowered.
986   setOperationAction(ISD::SADDO, MVT::i32, Custom);
987   setOperationAction(ISD::UADDO, MVT::i32, Custom);
988   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
989   setOperationAction(ISD::USUBO, MVT::i32, Custom);
990   setOperationAction(ISD::SMULO, MVT::i32, Custom);
991
992   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
993   // handle type legalization for these operations here.
994   //
995   // FIXME: We really should do custom legalization for addition and
996   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
997   // than generic legalization for 64-bit multiplication-with-overflow, though.
998   if (Subtarget->is64Bit()) {
999     setOperationAction(ISD::SADDO, MVT::i64, Custom);
1000     setOperationAction(ISD::UADDO, MVT::i64, Custom);
1001     setOperationAction(ISD::SSUBO, MVT::i64, Custom);
1002     setOperationAction(ISD::USUBO, MVT::i64, Custom);
1003     setOperationAction(ISD::SMULO, MVT::i64, Custom);
1004   }
1005
1006   if (!Subtarget->is64Bit()) {
1007     // These libcalls are not available in 32-bit.
1008     setLibcallName(RTLIB::SHL_I128, 0);
1009     setLibcallName(RTLIB::SRL_I128, 0);
1010     setLibcallName(RTLIB::SRA_I128, 0);
1011   }
1012
1013   // We have target-specific dag combine patterns for the following nodes:
1014   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1015   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1016   setTargetDAGCombine(ISD::BUILD_VECTOR);
1017   setTargetDAGCombine(ISD::SELECT);
1018   setTargetDAGCombine(ISD::SHL);
1019   setTargetDAGCombine(ISD::SRA);
1020   setTargetDAGCombine(ISD::SRL);
1021   setTargetDAGCombine(ISD::OR);
1022   setTargetDAGCombine(ISD::STORE);
1023   setTargetDAGCombine(ISD::ZERO_EXTEND);
1024   setTargetDAGCombine(ISD::ADD);
1025   if (Subtarget->is64Bit())
1026     setTargetDAGCombine(ISD::MUL);
1027
1028   computeRegisterProperties();
1029
1030   // FIXME: These should be based on subtarget info. Plus, the values should
1031   // be smaller when we are in optimizing for size mode.
1032   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1033   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1034   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1035   setPrefLoopAlignment(16);
1036   benefitFromCodePlacementOpt = true;
1037 }
1038
1039
1040 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1041   return MVT::i8;
1042 }
1043
1044
1045 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1046 /// the desired ByVal argument alignment.
1047 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1048   if (MaxAlign == 16)
1049     return;
1050   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1051     if (VTy->getBitWidth() == 128)
1052       MaxAlign = 16;
1053   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1054     unsigned EltAlign = 0;
1055     getMaxByValAlign(ATy->getElementType(), EltAlign);
1056     if (EltAlign > MaxAlign)
1057       MaxAlign = EltAlign;
1058   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1059     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1060       unsigned EltAlign = 0;
1061       getMaxByValAlign(STy->getElementType(i), EltAlign);
1062       if (EltAlign > MaxAlign)
1063         MaxAlign = EltAlign;
1064       if (MaxAlign == 16)
1065         break;
1066     }
1067   }
1068   return;
1069 }
1070
1071 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1072 /// function arguments in the caller parameter area. For X86, aggregates
1073 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1074 /// are at 4-byte boundaries.
1075 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1076   if (Subtarget->is64Bit()) {
1077     // Max of 8 and alignment of type.
1078     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1079     if (TyAlign > 8)
1080       return TyAlign;
1081     return 8;
1082   }
1083
1084   unsigned Align = 4;
1085   if (Subtarget->hasSSE1())
1086     getMaxByValAlign(Ty, Align);
1087   return Align;
1088 }
1089
1090 /// getOptimalMemOpType - Returns the target specific optimal type for load
1091 /// and store operations as a result of memset, memcpy, and memmove
1092 /// lowering. If DstAlign is zero that means it's safe to destination
1093 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1094 /// means there isn't a need to check it against alignment requirement,
1095 /// probably because the source does not need to be loaded. If
1096 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1097 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1098 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1099 /// constant so it does not need to be loaded.
1100 /// It returns EVT::Other if the type should be determined using generic
1101 /// target-independent logic.
1102 EVT
1103 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1104                                        unsigned DstAlign, unsigned SrcAlign,
1105                                        bool NonScalarIntSafe,
1106                                        bool MemcpyStrSrc,
1107                                        MachineFunction &MF) const {
1108   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1109   // linux.  This is because the stack realignment code can't handle certain
1110   // cases like PR2962.  This should be removed when PR2962 is fixed.
1111   const Function *F = MF.getFunction();
1112   if (NonScalarIntSafe &&
1113       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1114     if (Size >= 16 &&
1115         (Subtarget->isUnalignedMemAccessFast() ||
1116          ((DstAlign == 0 || DstAlign >= 16) &&
1117           (SrcAlign == 0 || SrcAlign >= 16))) &&
1118         Subtarget->getStackAlignment() >= 16) {
1119       if (Subtarget->hasSSE2())
1120         return MVT::v4i32;
1121       if (Subtarget->hasSSE1())
1122         return MVT::v4f32;
1123     } else if (!MemcpyStrSrc && Size >= 8 &&
1124                !Subtarget->is64Bit() &&
1125                Subtarget->getStackAlignment() >= 8 &&
1126                Subtarget->hasSSE2()) {
1127       // Do not use f64 to lower memcpy if source is string constant. It's
1128       // better to use i32 to avoid the loads.
1129       return MVT::f64;
1130     }
1131   }
1132   if (Subtarget->is64Bit() && Size >= 8)
1133     return MVT::i64;
1134   return MVT::i32;
1135 }
1136
1137 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1138 /// current function.  The returned value is a member of the
1139 /// MachineJumpTableInfo::JTEntryKind enum.
1140 unsigned X86TargetLowering::getJumpTableEncoding() const {
1141   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1142   // symbol.
1143   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1144       Subtarget->isPICStyleGOT())
1145     return MachineJumpTableInfo::EK_Custom32;
1146   
1147   // Otherwise, use the normal jump table encoding heuristics.
1148   return TargetLowering::getJumpTableEncoding();
1149 }
1150
1151 /// getPICBaseSymbol - Return the X86-32 PIC base.
1152 MCSymbol *
1153 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1154                                     MCContext &Ctx) const {
1155   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1156   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1157                                Twine(MF->getFunctionNumber())+"$pb");
1158 }
1159
1160
1161 const MCExpr *
1162 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1163                                              const MachineBasicBlock *MBB,
1164                                              unsigned uid,MCContext &Ctx) const{
1165   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1166          Subtarget->isPICStyleGOT());
1167   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1168   // entries.
1169   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1170                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1171 }
1172
1173 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1174 /// jumptable.
1175 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1176                                                     SelectionDAG &DAG) const {
1177   if (!Subtarget->is64Bit())
1178     // This doesn't have DebugLoc associated with it, but is not really the
1179     // same as a Register.
1180     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1181   return Table;
1182 }
1183
1184 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1185 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1186 /// MCExpr.
1187 const MCExpr *X86TargetLowering::
1188 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1189                              MCContext &Ctx) const {
1190   // X86-64 uses RIP relative addressing based on the jump table label.
1191   if (Subtarget->isPICStyleRIPRel())
1192     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1193
1194   // Otherwise, the reference is relative to the PIC base.
1195   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1196 }
1197
1198 /// getFunctionAlignment - Return the Log2 alignment of this function.
1199 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1200   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1201 }
1202
1203 std::pair<const TargetRegisterClass*, uint8_t>
1204 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1205   const TargetRegisterClass *RRC = 0;
1206   uint8_t Cost = 1;
1207   switch (VT.getSimpleVT().SimpleTy) {
1208   default:
1209     return TargetLowering::findRepresentativeClass(VT);
1210   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1211     RRC = (Subtarget->is64Bit()
1212            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1213     break;
1214   case MVT::v8i8: case MVT::v4i16:
1215   case MVT::v2i32: case MVT::v1i64: 
1216     RRC = X86::VR64RegisterClass;
1217     break;
1218   case MVT::f32: case MVT::f64:
1219   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1220   case MVT::v4f32: case MVT::v2f64:
1221   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1222   case MVT::v4f64:
1223     RRC = X86::VR128RegisterClass;
1224     break;
1225   }
1226   return std::make_pair(RRC, Cost);
1227 }
1228
1229 unsigned
1230 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1231                                        MachineFunction &MF) const {
1232   unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1233   switch (RC->getID()) {
1234   default:
1235     return 0;
1236   case X86::GR32RegClassID:
1237     return 4 - FPDiff;
1238   case X86::GR64RegClassID:
1239     return 8 - FPDiff;
1240   case X86::VR128RegClassID:
1241     return Subtarget->is64Bit() ? 10 : 4;
1242   case X86::VR64RegClassID:
1243     return 4;
1244   }
1245 }
1246
1247 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1248                                                unsigned &Offset) const {
1249   if (!Subtarget->isTargetLinux())
1250     return false;
1251
1252   if (Subtarget->is64Bit()) {
1253     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1254     Offset = 0x28;
1255     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1256       AddressSpace = 256;
1257     else
1258       AddressSpace = 257;
1259   } else {
1260     // %gs:0x14 on i386
1261     Offset = 0x14;
1262     AddressSpace = 256;
1263   }
1264   return true;
1265 }
1266
1267
1268 //===----------------------------------------------------------------------===//
1269 //               Return Value Calling Convention Implementation
1270 //===----------------------------------------------------------------------===//
1271
1272 #include "X86GenCallingConv.inc"
1273
1274 bool 
1275 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1276                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1277                         LLVMContext &Context) const {
1278   SmallVector<CCValAssign, 16> RVLocs;
1279   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1280                  RVLocs, Context);
1281   return CCInfo.CheckReturn(Outs, RetCC_X86);
1282 }
1283
1284 SDValue
1285 X86TargetLowering::LowerReturn(SDValue Chain,
1286                                CallingConv::ID CallConv, bool isVarArg,
1287                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1288                                const SmallVectorImpl<SDValue> &OutVals,
1289                                DebugLoc dl, SelectionDAG &DAG) const {
1290   MachineFunction &MF = DAG.getMachineFunction();
1291   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1292
1293   SmallVector<CCValAssign, 16> RVLocs;
1294   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1295                  RVLocs, *DAG.getContext());
1296   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1297
1298   // Add the regs to the liveout set for the function.
1299   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1300   for (unsigned i = 0; i != RVLocs.size(); ++i)
1301     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1302       MRI.addLiveOut(RVLocs[i].getLocReg());
1303
1304   SDValue Flag;
1305
1306   SmallVector<SDValue, 6> RetOps;
1307   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1308   // Operand #1 = Bytes To Pop
1309   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1310                    MVT::i16));
1311
1312   // Copy the result values into the output registers.
1313   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1314     CCValAssign &VA = RVLocs[i];
1315     assert(VA.isRegLoc() && "Can only return in registers!");
1316     SDValue ValToCopy = OutVals[i];
1317     EVT ValVT = ValToCopy.getValueType();
1318
1319     // If this is x86-64, and we disabled SSE, we can't return FP values
1320     if ((ValVT == MVT::f32 || ValVT == MVT::f64) &&
1321         (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1322       report_fatal_error("SSE register return with SSE disabled");
1323     }
1324     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1325     // llvm-gcc has never done it right and no one has noticed, so this
1326     // should be OK for now.
1327     if (ValVT == MVT::f64 &&
1328         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1329       report_fatal_error("SSE2 register return with SSE2 disabled");
1330
1331     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1332     // the RET instruction and handled by the FP Stackifier.
1333     if (VA.getLocReg() == X86::ST0 ||
1334         VA.getLocReg() == X86::ST1) {
1335       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1336       // change the value to the FP stack register class.
1337       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1338         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1339       RetOps.push_back(ValToCopy);
1340       // Don't emit a copytoreg.
1341       continue;
1342     }
1343
1344     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1345     // which is returned in RAX / RDX.
1346     if (Subtarget->is64Bit()) {
1347       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1348         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1349         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1350           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1351                                   ValToCopy);
1352           
1353           // If we don't have SSE2 available, convert to v4f32 so the generated
1354           // register is legal.
1355           if (!Subtarget->hasSSE2())
1356             ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32,ValToCopy);
1357         }
1358       }
1359     }
1360     
1361     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1362     Flag = Chain.getValue(1);
1363   }
1364
1365   // The x86-64 ABI for returning structs by value requires that we copy
1366   // the sret argument into %rax for the return. We saved the argument into
1367   // a virtual register in the entry block, so now we copy the value out
1368   // and into %rax.
1369   if (Subtarget->is64Bit() &&
1370       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1371     MachineFunction &MF = DAG.getMachineFunction();
1372     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1373     unsigned Reg = FuncInfo->getSRetReturnReg();
1374     assert(Reg && 
1375            "SRetReturnReg should have been set in LowerFormalArguments().");
1376     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1377
1378     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1379     Flag = Chain.getValue(1);
1380
1381     // RAX now acts like a return value.
1382     MRI.addLiveOut(X86::RAX);
1383   }
1384
1385   RetOps[0] = Chain;  // Update chain.
1386
1387   // Add the flag if we have it.
1388   if (Flag.getNode())
1389     RetOps.push_back(Flag);
1390
1391   return DAG.getNode(X86ISD::RET_FLAG, dl,
1392                      MVT::Other, &RetOps[0], RetOps.size());
1393 }
1394
1395 /// LowerCallResult - Lower the result values of a call into the
1396 /// appropriate copies out of appropriate physical registers.
1397 ///
1398 SDValue
1399 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1400                                    CallingConv::ID CallConv, bool isVarArg,
1401                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1402                                    DebugLoc dl, SelectionDAG &DAG,
1403                                    SmallVectorImpl<SDValue> &InVals) const {
1404
1405   // Assign locations to each value returned by this call.
1406   SmallVector<CCValAssign, 16> RVLocs;
1407   bool Is64Bit = Subtarget->is64Bit();
1408   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1409                  RVLocs, *DAG.getContext());
1410   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1411
1412   // Copy all of the result registers out of their specified physreg.
1413   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1414     CCValAssign &VA = RVLocs[i];
1415     EVT CopyVT = VA.getValVT();
1416
1417     // If this is x86-64, and we disabled SSE, we can't return FP values
1418     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1419         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1420       report_fatal_error("SSE register return with SSE disabled");
1421     }
1422
1423     SDValue Val;
1424
1425     // If this is a call to a function that returns an fp value on the floating
1426     // point stack, we must guarantee the the value is popped from the stack, so
1427     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1428     // if the return value is not used. We use the FpGET_ST0 instructions
1429     // instead.
1430     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1431       // If we prefer to use the value in xmm registers, copy it out as f80 and
1432       // use a truncate to move it from fp stack reg to xmm reg.
1433       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1434       bool isST0 = VA.getLocReg() == X86::ST0;
1435       unsigned Opc = 0;
1436       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1437       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1438       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1439       SDValue Ops[] = { Chain, InFlag };
1440       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1441                                          Ops, 2), 1);
1442       Val = Chain.getValue(0);
1443
1444       // Round the f80 to the right size, which also moves it to the appropriate
1445       // xmm register.
1446       if (CopyVT != VA.getValVT())
1447         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1448                           // This truncation won't change the value.
1449                           DAG.getIntPtrConstant(1));
1450     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1451       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1452       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1453         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1454                                    MVT::v2i64, InFlag).getValue(1);
1455         Val = Chain.getValue(0);
1456         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1457                           Val, DAG.getConstant(0, MVT::i64));
1458       } else {
1459         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1460                                    MVT::i64, InFlag).getValue(1);
1461         Val = Chain.getValue(0);
1462       }
1463       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1464     } else {
1465       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1466                                  CopyVT, InFlag).getValue(1);
1467       Val = Chain.getValue(0);
1468     }
1469     InFlag = Chain.getValue(2);
1470     InVals.push_back(Val);
1471   }
1472
1473   return Chain;
1474 }
1475
1476
1477 //===----------------------------------------------------------------------===//
1478 //                C & StdCall & Fast Calling Convention implementation
1479 //===----------------------------------------------------------------------===//
1480 //  StdCall calling convention seems to be standard for many Windows' API
1481 //  routines and around. It differs from C calling convention just a little:
1482 //  callee should clean up the stack, not caller. Symbols should be also
1483 //  decorated in some fancy way :) It doesn't support any vector arguments.
1484 //  For info on fast calling convention see Fast Calling Convention (tail call)
1485 //  implementation LowerX86_32FastCCCallTo.
1486
1487 /// CallIsStructReturn - Determines whether a call uses struct return
1488 /// semantics.
1489 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1490   if (Outs.empty())
1491     return false;
1492
1493   return Outs[0].Flags.isSRet();
1494 }
1495
1496 /// ArgsAreStructReturn - Determines whether a function uses struct
1497 /// return semantics.
1498 static bool
1499 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1500   if (Ins.empty())
1501     return false;
1502
1503   return Ins[0].Flags.isSRet();
1504 }
1505
1506 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1507 /// given CallingConvention value.
1508 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1509   if (Subtarget->is64Bit()) {
1510     if (CC == CallingConv::GHC)
1511       return CC_X86_64_GHC;
1512     else if (Subtarget->isTargetWin64())
1513       return CC_X86_Win64_C;
1514     else
1515       return CC_X86_64_C;
1516   }
1517
1518   if (CC == CallingConv::X86_FastCall)
1519     return CC_X86_32_FastCall;
1520   else if (CC == CallingConv::X86_ThisCall)
1521     return CC_X86_32_ThisCall;
1522   else if (CC == CallingConv::Fast)
1523     return CC_X86_32_FastCC;
1524   else if (CC == CallingConv::GHC)
1525     return CC_X86_32_GHC;
1526   else
1527     return CC_X86_32_C;
1528 }
1529
1530 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1531 /// by "Src" to address "Dst" with size and alignment information specified by
1532 /// the specific parameter attribute. The copy will be passed as a byval
1533 /// function parameter.
1534 static SDValue
1535 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1536                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1537                           DebugLoc dl) {
1538   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1539   
1540   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1541                        /*isVolatile*/false, /*AlwaysInline=*/true,
1542                        MachinePointerInfo(), MachinePointerInfo());
1543 }
1544
1545 /// IsTailCallConvention - Return true if the calling convention is one that
1546 /// supports tail call optimization.
1547 static bool IsTailCallConvention(CallingConv::ID CC) {
1548   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1549 }
1550
1551 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1552 /// a tailcall target by changing its ABI.
1553 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1554   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1555 }
1556
1557 SDValue
1558 X86TargetLowering::LowerMemArgument(SDValue Chain,
1559                                     CallingConv::ID CallConv,
1560                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1561                                     DebugLoc dl, SelectionDAG &DAG,
1562                                     const CCValAssign &VA,
1563                                     MachineFrameInfo *MFI,
1564                                     unsigned i) const {
1565   // Create the nodes corresponding to a load from this parameter slot.
1566   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1567   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1568   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1569   EVT ValVT;
1570
1571   // If value is passed by pointer we have address passed instead of the value
1572   // itself.
1573   if (VA.getLocInfo() == CCValAssign::Indirect)
1574     ValVT = VA.getLocVT();
1575   else
1576     ValVT = VA.getValVT();
1577
1578   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1579   // changed with more analysis.
1580   // In case of tail call optimization mark all arguments mutable. Since they
1581   // could be overwritten by lowering of arguments in case of a tail call.
1582   if (Flags.isByVal()) {
1583     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1584                                     VA.getLocMemOffset(), isImmutable);
1585     return DAG.getFrameIndex(FI, getPointerTy());
1586   } else {
1587     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1588                                     VA.getLocMemOffset(), isImmutable);
1589     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1590     return DAG.getLoad(ValVT, dl, Chain, FIN,
1591                        MachinePointerInfo::getFixedStack(FI),
1592                        false, false, 0);
1593   }
1594 }
1595
1596 SDValue
1597 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1598                                         CallingConv::ID CallConv,
1599                                         bool isVarArg,
1600                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1601                                         DebugLoc dl,
1602                                         SelectionDAG &DAG,
1603                                         SmallVectorImpl<SDValue> &InVals)
1604                                           const {
1605   MachineFunction &MF = DAG.getMachineFunction();
1606   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1607
1608   const Function* Fn = MF.getFunction();
1609   if (Fn->hasExternalLinkage() &&
1610       Subtarget->isTargetCygMing() &&
1611       Fn->getName() == "main")
1612     FuncInfo->setForceFramePointer(true);
1613
1614   MachineFrameInfo *MFI = MF.getFrameInfo();
1615   bool Is64Bit = Subtarget->is64Bit();
1616   bool IsWin64 = Subtarget->isTargetWin64();
1617
1618   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1619          "Var args not supported with calling convention fastcc or ghc");
1620
1621   // Assign locations to all of the incoming arguments.
1622   SmallVector<CCValAssign, 16> ArgLocs;
1623   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1624                  ArgLocs, *DAG.getContext());
1625   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1626
1627   unsigned LastVal = ~0U;
1628   SDValue ArgValue;
1629   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1630     CCValAssign &VA = ArgLocs[i];
1631     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1632     // places.
1633     assert(VA.getValNo() != LastVal &&
1634            "Don't support value assigned to multiple locs yet");
1635     LastVal = VA.getValNo();
1636
1637     if (VA.isRegLoc()) {
1638       EVT RegVT = VA.getLocVT();
1639       TargetRegisterClass *RC = NULL;
1640       if (RegVT == MVT::i32)
1641         RC = X86::GR32RegisterClass;
1642       else if (Is64Bit && RegVT == MVT::i64)
1643         RC = X86::GR64RegisterClass;
1644       else if (RegVT == MVT::f32)
1645         RC = X86::FR32RegisterClass;
1646       else if (RegVT == MVT::f64)
1647         RC = X86::FR64RegisterClass;
1648       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1649         RC = X86::VR256RegisterClass;
1650       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1651         RC = X86::VR128RegisterClass;
1652       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1653         RC = X86::VR64RegisterClass;
1654       else
1655         llvm_unreachable("Unknown argument type!");
1656
1657       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1658       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1659
1660       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1661       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1662       // right size.
1663       if (VA.getLocInfo() == CCValAssign::SExt)
1664         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1665                                DAG.getValueType(VA.getValVT()));
1666       else if (VA.getLocInfo() == CCValAssign::ZExt)
1667         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1668                                DAG.getValueType(VA.getValVT()));
1669       else if (VA.getLocInfo() == CCValAssign::BCvt)
1670         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1671
1672       if (VA.isExtInLoc()) {
1673         // Handle MMX values passed in XMM regs.
1674         if (RegVT.isVector()) {
1675           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1676                                  ArgValue, DAG.getConstant(0, MVT::i64));
1677           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1678         } else
1679           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1680       }
1681     } else {
1682       assert(VA.isMemLoc());
1683       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1684     }
1685
1686     // If value is passed via pointer - do a load.
1687     if (VA.getLocInfo() == CCValAssign::Indirect)
1688       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1689                              MachinePointerInfo(), false, false, 0);
1690
1691     InVals.push_back(ArgValue);
1692   }
1693
1694   // The x86-64 ABI for returning structs by value requires that we copy
1695   // the sret argument into %rax for the return. Save the argument into
1696   // a virtual register so that we can access it from the return points.
1697   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1698     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1699     unsigned Reg = FuncInfo->getSRetReturnReg();
1700     if (!Reg) {
1701       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1702       FuncInfo->setSRetReturnReg(Reg);
1703     }
1704     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1705     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1706   }
1707
1708   unsigned StackSize = CCInfo.getNextStackOffset();
1709   // Align stack specially for tail calls.
1710   if (FuncIsMadeTailCallSafe(CallConv))
1711     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1712
1713   // If the function takes variable number of arguments, make a frame index for
1714   // the start of the first vararg value... for expansion of llvm.va_start.
1715   if (isVarArg) {
1716     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1717                     CallConv != CallingConv::X86_ThisCall)) {
1718       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1719     }
1720     if (Is64Bit) {
1721       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1722
1723       // FIXME: We should really autogenerate these arrays
1724       static const unsigned GPR64ArgRegsWin64[] = {
1725         X86::RCX, X86::RDX, X86::R8,  X86::R9
1726       };
1727       static const unsigned XMMArgRegsWin64[] = {
1728         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1729       };
1730       static const unsigned GPR64ArgRegs64Bit[] = {
1731         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1732       };
1733       static const unsigned XMMArgRegs64Bit[] = {
1734         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1735         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1736       };
1737       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1738
1739       if (IsWin64) {
1740         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1741         GPR64ArgRegs = GPR64ArgRegsWin64;
1742         XMMArgRegs = XMMArgRegsWin64;
1743       } else {
1744         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1745         GPR64ArgRegs = GPR64ArgRegs64Bit;
1746         XMMArgRegs = XMMArgRegs64Bit;
1747       }
1748       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1749                                                        TotalNumIntRegs);
1750       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1751                                                        TotalNumXMMRegs);
1752
1753       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1754       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1755              "SSE register cannot be used when SSE is disabled!");
1756       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1757              "SSE register cannot be used when SSE is disabled!");
1758       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1759         // Kernel mode asks for SSE to be disabled, so don't push them
1760         // on the stack.
1761         TotalNumXMMRegs = 0;
1762
1763       // For X86-64, if there are vararg parameters that are passed via
1764       // registers, then we must store them to their spots on the stack so they
1765       // may be loaded by deferencing the result of va_next.
1766       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1767       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1768       FuncInfo->setRegSaveFrameIndex(
1769         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1770                                false));
1771
1772       // Store the integer parameter registers.
1773       SmallVector<SDValue, 8> MemOps;
1774       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1775                                         getPointerTy());
1776       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1777       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1778         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1779                                   DAG.getIntPtrConstant(Offset));
1780         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1781                                      X86::GR64RegisterClass);
1782         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1783         SDValue Store =
1784           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1785                        MachinePointerInfo::getFixedStack(
1786                          FuncInfo->getRegSaveFrameIndex(), Offset),
1787                        false, false, 0);
1788         MemOps.push_back(Store);
1789         Offset += 8;
1790       }
1791
1792       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1793         // Now store the XMM (fp + vector) parameter registers.
1794         SmallVector<SDValue, 11> SaveXMMOps;
1795         SaveXMMOps.push_back(Chain);
1796
1797         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1798         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1799         SaveXMMOps.push_back(ALVal);
1800
1801         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1802                                FuncInfo->getRegSaveFrameIndex()));
1803         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1804                                FuncInfo->getVarArgsFPOffset()));
1805
1806         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1807           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1808                                        X86::VR128RegisterClass);
1809           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1810           SaveXMMOps.push_back(Val);
1811         }
1812         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1813                                      MVT::Other,
1814                                      &SaveXMMOps[0], SaveXMMOps.size()));
1815       }
1816
1817       if (!MemOps.empty())
1818         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1819                             &MemOps[0], MemOps.size());
1820     }
1821   }
1822
1823   // Some CCs need callee pop.
1824   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1825     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1826   } else {
1827     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1828     // If this is an sret function, the return should pop the hidden pointer.
1829     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1830       FuncInfo->setBytesToPopOnReturn(4);
1831   }
1832
1833   if (!Is64Bit) {
1834     // RegSaveFrameIndex is X86-64 only.
1835     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1836     if (CallConv == CallingConv::X86_FastCall ||
1837         CallConv == CallingConv::X86_ThisCall)
1838       // fastcc functions can't have varargs.
1839       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1840   }
1841
1842   return Chain;
1843 }
1844
1845 SDValue
1846 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1847                                     SDValue StackPtr, SDValue Arg,
1848                                     DebugLoc dl, SelectionDAG &DAG,
1849                                     const CCValAssign &VA,
1850                                     ISD::ArgFlagsTy Flags) const {
1851   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1852   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1853   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1854   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1855   if (Flags.isByVal())
1856     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1857
1858   return DAG.getStore(Chain, dl, Arg, PtrOff,
1859                       MachinePointerInfo::getStack(LocMemOffset),
1860                       false, false, 0);
1861 }
1862
1863 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1864 /// optimization is performed and it is required.
1865 SDValue
1866 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1867                                            SDValue &OutRetAddr, SDValue Chain,
1868                                            bool IsTailCall, bool Is64Bit,
1869                                            int FPDiff, DebugLoc dl) const {
1870   // Adjust the Return address stack slot.
1871   EVT VT = getPointerTy();
1872   OutRetAddr = getReturnAddressFrameIndex(DAG);
1873
1874   // Load the "old" Return address.
1875   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1876                            false, false, 0);
1877   return SDValue(OutRetAddr.getNode(), 1);
1878 }
1879
1880 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1881 /// optimization is performed and it is required (FPDiff!=0).
1882 static SDValue
1883 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1884                          SDValue Chain, SDValue RetAddrFrIdx,
1885                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1886   // Store the return address to the appropriate stack slot.
1887   if (!FPDiff) return Chain;
1888   // Calculate the new stack slot for the return address.
1889   int SlotSize = Is64Bit ? 8 : 4;
1890   int NewReturnAddrFI =
1891     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1892   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1893   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1894   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1895                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1896                        false, false, 0);
1897   return Chain;
1898 }
1899
1900 SDValue
1901 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1902                              CallingConv::ID CallConv, bool isVarArg,
1903                              bool &isTailCall,
1904                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1905                              const SmallVectorImpl<SDValue> &OutVals,
1906                              const SmallVectorImpl<ISD::InputArg> &Ins,
1907                              DebugLoc dl, SelectionDAG &DAG,
1908                              SmallVectorImpl<SDValue> &InVals) const {
1909   MachineFunction &MF = DAG.getMachineFunction();
1910   bool Is64Bit        = Subtarget->is64Bit();
1911   bool IsStructRet    = CallIsStructReturn(Outs);
1912   bool IsSibcall      = false;
1913
1914   if (isTailCall) {
1915     // Check if it's really possible to do a tail call.
1916     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1917                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1918                                                    Outs, OutVals, Ins, DAG);
1919
1920     // Sibcalls are automatically detected tailcalls which do not require
1921     // ABI changes.
1922     if (!GuaranteedTailCallOpt && isTailCall)
1923       IsSibcall = true;
1924
1925     if (isTailCall)
1926       ++NumTailCalls;
1927   }
1928
1929   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1930          "Var args not supported with calling convention fastcc or ghc");
1931
1932   // Analyze operands of the call, assigning locations to each operand.
1933   SmallVector<CCValAssign, 16> ArgLocs;
1934   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1935                  ArgLocs, *DAG.getContext());
1936   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1937
1938   // Get a count of how many bytes are to be pushed on the stack.
1939   unsigned NumBytes = CCInfo.getNextStackOffset();
1940   if (IsSibcall)
1941     // This is a sibcall. The memory operands are available in caller's
1942     // own caller's stack.
1943     NumBytes = 0;
1944   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1945     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1946
1947   int FPDiff = 0;
1948   if (isTailCall && !IsSibcall) {
1949     // Lower arguments at fp - stackoffset + fpdiff.
1950     unsigned NumBytesCallerPushed =
1951       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1952     FPDiff = NumBytesCallerPushed - NumBytes;
1953
1954     // Set the delta of movement of the returnaddr stackslot.
1955     // But only set if delta is greater than previous delta.
1956     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1957       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1958   }
1959
1960   if (!IsSibcall)
1961     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1962
1963   SDValue RetAddrFrIdx;
1964   // Load return adress for tail calls.
1965   if (isTailCall && FPDiff)
1966     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1967                                     Is64Bit, FPDiff, dl);
1968
1969   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1970   SmallVector<SDValue, 8> MemOpChains;
1971   SDValue StackPtr;
1972
1973   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1974   // of tail call optimization arguments are handle later.
1975   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1976     CCValAssign &VA = ArgLocs[i];
1977     EVT RegVT = VA.getLocVT();
1978     SDValue Arg = OutVals[i];
1979     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1980     bool isByVal = Flags.isByVal();
1981
1982     // Promote the value if needed.
1983     switch (VA.getLocInfo()) {
1984     default: llvm_unreachable("Unknown loc info!");
1985     case CCValAssign::Full: break;
1986     case CCValAssign::SExt:
1987       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1988       break;
1989     case CCValAssign::ZExt:
1990       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1991       break;
1992     case CCValAssign::AExt:
1993       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1994         // Special case: passing MMX values in XMM registers.
1995         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1996         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1997         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1998       } else
1999         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2000       break;
2001     case CCValAssign::BCvt:
2002       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
2003       break;
2004     case CCValAssign::Indirect: {
2005       // Store the argument.
2006       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2007       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2008       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2009                            MachinePointerInfo::getFixedStack(FI),
2010                            false, false, 0);
2011       Arg = SpillSlot;
2012       break;
2013     }
2014     }
2015
2016     if (VA.isRegLoc()) {
2017       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2018       if (isVarArg && Subtarget->isTargetWin64()) {
2019         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2020         // shadow reg if callee is a varargs function.
2021         unsigned ShadowReg = 0;
2022         switch (VA.getLocReg()) {
2023         case X86::XMM0: ShadowReg = X86::RCX; break;
2024         case X86::XMM1: ShadowReg = X86::RDX; break;
2025         case X86::XMM2: ShadowReg = X86::R8; break;
2026         case X86::XMM3: ShadowReg = X86::R9; break;
2027         }
2028         if (ShadowReg)
2029           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2030       }
2031     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2032       assert(VA.isMemLoc());
2033       if (StackPtr.getNode() == 0)
2034         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2035       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2036                                              dl, DAG, VA, Flags));
2037     }
2038   }
2039
2040   if (!MemOpChains.empty())
2041     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2042                         &MemOpChains[0], MemOpChains.size());
2043
2044   // Build a sequence of copy-to-reg nodes chained together with token chain
2045   // and flag operands which copy the outgoing args into registers.
2046   SDValue InFlag;
2047   // Tail call byval lowering might overwrite argument registers so in case of
2048   // tail call optimization the copies to registers are lowered later.
2049   if (!isTailCall)
2050     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2051       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2052                                RegsToPass[i].second, InFlag);
2053       InFlag = Chain.getValue(1);
2054     }
2055
2056   if (Subtarget->isPICStyleGOT()) {
2057     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2058     // GOT pointer.
2059     if (!isTailCall) {
2060       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2061                                DAG.getNode(X86ISD::GlobalBaseReg,
2062                                            DebugLoc(), getPointerTy()),
2063                                InFlag);
2064       InFlag = Chain.getValue(1);
2065     } else {
2066       // If we are tail calling and generating PIC/GOT style code load the
2067       // address of the callee into ECX. The value in ecx is used as target of
2068       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2069       // for tail calls on PIC/GOT architectures. Normally we would just put the
2070       // address of GOT into ebx and then call target@PLT. But for tail calls
2071       // ebx would be restored (since ebx is callee saved) before jumping to the
2072       // target@PLT.
2073
2074       // Note: The actual moving to ECX is done further down.
2075       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2076       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2077           !G->getGlobal()->hasProtectedVisibility())
2078         Callee = LowerGlobalAddress(Callee, DAG);
2079       else if (isa<ExternalSymbolSDNode>(Callee))
2080         Callee = LowerExternalSymbol(Callee, DAG);
2081     }
2082   }
2083
2084   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2085     // From AMD64 ABI document:
2086     // For calls that may call functions that use varargs or stdargs
2087     // (prototype-less calls or calls to functions containing ellipsis (...) in
2088     // the declaration) %al is used as hidden argument to specify the number
2089     // of SSE registers used. The contents of %al do not need to match exactly
2090     // the number of registers, but must be an ubound on the number of SSE
2091     // registers used and is in the range 0 - 8 inclusive.
2092
2093     // Count the number of XMM registers allocated.
2094     static const unsigned XMMArgRegs[] = {
2095       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2096       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2097     };
2098     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2099     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2100            && "SSE registers cannot be used when SSE is disabled");
2101
2102     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2103                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2104     InFlag = Chain.getValue(1);
2105   }
2106
2107
2108   // For tail calls lower the arguments to the 'real' stack slot.
2109   if (isTailCall) {
2110     // Force all the incoming stack arguments to be loaded from the stack
2111     // before any new outgoing arguments are stored to the stack, because the
2112     // outgoing stack slots may alias the incoming argument stack slots, and
2113     // the alias isn't otherwise explicit. This is slightly more conservative
2114     // than necessary, because it means that each store effectively depends
2115     // on every argument instead of just those arguments it would clobber.
2116     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2117
2118     SmallVector<SDValue, 8> MemOpChains2;
2119     SDValue FIN;
2120     int FI = 0;
2121     // Do not flag preceeding copytoreg stuff together with the following stuff.
2122     InFlag = SDValue();
2123     if (GuaranteedTailCallOpt) {
2124       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2125         CCValAssign &VA = ArgLocs[i];
2126         if (VA.isRegLoc())
2127           continue;
2128         assert(VA.isMemLoc());
2129         SDValue Arg = OutVals[i];
2130         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2131         // Create frame index.
2132         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2133         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2134         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2135         FIN = DAG.getFrameIndex(FI, getPointerTy());
2136
2137         if (Flags.isByVal()) {
2138           // Copy relative to framepointer.
2139           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2140           if (StackPtr.getNode() == 0)
2141             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2142                                           getPointerTy());
2143           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2144
2145           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2146                                                            ArgChain,
2147                                                            Flags, DAG, dl));
2148         } else {
2149           // Store relative to framepointer.
2150           MemOpChains2.push_back(
2151             DAG.getStore(ArgChain, dl, Arg, FIN,
2152                          MachinePointerInfo::getFixedStack(FI),
2153                          false, false, 0));
2154         }
2155       }
2156     }
2157
2158     if (!MemOpChains2.empty())
2159       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2160                           &MemOpChains2[0], MemOpChains2.size());
2161
2162     // Copy arguments to their registers.
2163     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2164       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2165                                RegsToPass[i].second, InFlag);
2166       InFlag = Chain.getValue(1);
2167     }
2168     InFlag =SDValue();
2169
2170     // Store the return address to the appropriate stack slot.
2171     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2172                                      FPDiff, dl);
2173   }
2174
2175   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2176     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2177     // In the 64-bit large code model, we have to make all calls
2178     // through a register, since the call instruction's 32-bit
2179     // pc-relative offset may not be large enough to hold the whole
2180     // address.
2181   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2182     // If the callee is a GlobalAddress node (quite common, every direct call
2183     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2184     // it.
2185
2186     // We should use extra load for direct calls to dllimported functions in
2187     // non-JIT mode.
2188     const GlobalValue *GV = G->getGlobal();
2189     if (!GV->hasDLLImportLinkage()) {
2190       unsigned char OpFlags = 0;
2191
2192       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2193       // external symbols most go through the PLT in PIC mode.  If the symbol
2194       // has hidden or protected visibility, or if it is static or local, then
2195       // we don't need to use the PLT - we can directly call it.
2196       if (Subtarget->isTargetELF() &&
2197           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2198           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2199         OpFlags = X86II::MO_PLT;
2200       } else if (Subtarget->isPICStyleStubAny() &&
2201                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2202                Subtarget->getDarwinVers() < 9) {
2203         // PC-relative references to external symbols should go through $stub,
2204         // unless we're building with the leopard linker or later, which
2205         // automatically synthesizes these stubs.
2206         OpFlags = X86II::MO_DARWIN_STUB;
2207       }
2208
2209       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2210                                           G->getOffset(), OpFlags);
2211     }
2212   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2213     unsigned char OpFlags = 0;
2214
2215     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2216     // symbols should go through the PLT.
2217     if (Subtarget->isTargetELF() &&
2218         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2219       OpFlags = X86II::MO_PLT;
2220     } else if (Subtarget->isPICStyleStubAny() &&
2221              Subtarget->getDarwinVers() < 9) {
2222       // PC-relative references to external symbols should go through $stub,
2223       // unless we're building with the leopard linker or later, which
2224       // automatically synthesizes these stubs.
2225       OpFlags = X86II::MO_DARWIN_STUB;
2226     }
2227
2228     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2229                                          OpFlags);
2230   }
2231
2232   // Returns a chain & a flag for retval copy to use.
2233   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2234   SmallVector<SDValue, 8> Ops;
2235
2236   if (!IsSibcall && isTailCall) {
2237     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2238                            DAG.getIntPtrConstant(0, true), InFlag);
2239     InFlag = Chain.getValue(1);
2240   }
2241
2242   Ops.push_back(Chain);
2243   Ops.push_back(Callee);
2244
2245   if (isTailCall)
2246     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2247
2248   // Add argument registers to the end of the list so that they are known live
2249   // into the call.
2250   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2251     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2252                                   RegsToPass[i].second.getValueType()));
2253
2254   // Add an implicit use GOT pointer in EBX.
2255   if (!isTailCall && Subtarget->isPICStyleGOT())
2256     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2257
2258   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2259   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2260     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2261
2262   if (InFlag.getNode())
2263     Ops.push_back(InFlag);
2264
2265   if (isTailCall) {
2266     // We used to do:
2267     //// If this is the first return lowered for this function, add the regs
2268     //// to the liveout set for the function.
2269     // This isn't right, although it's probably harmless on x86; liveouts
2270     // should be computed from returns not tail calls.  Consider a void
2271     // function making a tail call to a function returning int.
2272     return DAG.getNode(X86ISD::TC_RETURN, dl,
2273                        NodeTys, &Ops[0], Ops.size());
2274   }
2275
2276   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2277   InFlag = Chain.getValue(1);
2278
2279   // Create the CALLSEQ_END node.
2280   unsigned NumBytesForCalleeToPush;
2281   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2282     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2283   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2284     // If this is a call to a struct-return function, the callee
2285     // pops the hidden struct pointer, so we have to push it back.
2286     // This is common for Darwin/X86, Linux & Mingw32 targets.
2287     NumBytesForCalleeToPush = 4;
2288   else
2289     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2290
2291   // Returns a flag for retval copy to use.
2292   if (!IsSibcall) {
2293     Chain = DAG.getCALLSEQ_END(Chain,
2294                                DAG.getIntPtrConstant(NumBytes, true),
2295                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2296                                                      true),
2297                                InFlag);
2298     InFlag = Chain.getValue(1);
2299   }
2300
2301   // Handle result values, copying them out of physregs into vregs that we
2302   // return.
2303   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2304                          Ins, dl, DAG, InVals);
2305 }
2306
2307
2308 //===----------------------------------------------------------------------===//
2309 //                Fast Calling Convention (tail call) implementation
2310 //===----------------------------------------------------------------------===//
2311
2312 //  Like std call, callee cleans arguments, convention except that ECX is
2313 //  reserved for storing the tail called function address. Only 2 registers are
2314 //  free for argument passing (inreg). Tail call optimization is performed
2315 //  provided:
2316 //                * tailcallopt is enabled
2317 //                * caller/callee are fastcc
2318 //  On X86_64 architecture with GOT-style position independent code only local
2319 //  (within module) calls are supported at the moment.
2320 //  To keep the stack aligned according to platform abi the function
2321 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2322 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2323 //  If a tail called function callee has more arguments than the caller the
2324 //  caller needs to make sure that there is room to move the RETADDR to. This is
2325 //  achieved by reserving an area the size of the argument delta right after the
2326 //  original REtADDR, but before the saved framepointer or the spilled registers
2327 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2328 //  stack layout:
2329 //    arg1
2330 //    arg2
2331 //    RETADDR
2332 //    [ new RETADDR
2333 //      move area ]
2334 //    (possible EBP)
2335 //    ESI
2336 //    EDI
2337 //    local1 ..
2338
2339 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2340 /// for a 16 byte align requirement.
2341 unsigned
2342 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2343                                                SelectionDAG& DAG) const {
2344   MachineFunction &MF = DAG.getMachineFunction();
2345   const TargetMachine &TM = MF.getTarget();
2346   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2347   unsigned StackAlignment = TFI.getStackAlignment();
2348   uint64_t AlignMask = StackAlignment - 1;
2349   int64_t Offset = StackSize;
2350   uint64_t SlotSize = TD->getPointerSize();
2351   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2352     // Number smaller than 12 so just add the difference.
2353     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2354   } else {
2355     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2356     Offset = ((~AlignMask) & Offset) + StackAlignment +
2357       (StackAlignment-SlotSize);
2358   }
2359   return Offset;
2360 }
2361
2362 /// MatchingStackOffset - Return true if the given stack call argument is
2363 /// already available in the same position (relatively) of the caller's
2364 /// incoming argument stack.
2365 static
2366 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2367                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2368                          const X86InstrInfo *TII) {
2369   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2370   int FI = INT_MAX;
2371   if (Arg.getOpcode() == ISD::CopyFromReg) {
2372     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2373     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2374       return false;
2375     MachineInstr *Def = MRI->getVRegDef(VR);
2376     if (!Def)
2377       return false;
2378     if (!Flags.isByVal()) {
2379       if (!TII->isLoadFromStackSlot(Def, FI))
2380         return false;
2381     } else {
2382       unsigned Opcode = Def->getOpcode();
2383       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2384           Def->getOperand(1).isFI()) {
2385         FI = Def->getOperand(1).getIndex();
2386         Bytes = Flags.getByValSize();
2387       } else
2388         return false;
2389     }
2390   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2391     if (Flags.isByVal())
2392       // ByVal argument is passed in as a pointer but it's now being
2393       // dereferenced. e.g.
2394       // define @foo(%struct.X* %A) {
2395       //   tail call @bar(%struct.X* byval %A)
2396       // }
2397       return false;
2398     SDValue Ptr = Ld->getBasePtr();
2399     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2400     if (!FINode)
2401       return false;
2402     FI = FINode->getIndex();
2403   } else
2404     return false;
2405
2406   assert(FI != INT_MAX);
2407   if (!MFI->isFixedObjectIndex(FI))
2408     return false;
2409   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2410 }
2411
2412 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2413 /// for tail call optimization. Targets which want to do tail call
2414 /// optimization should implement this function.
2415 bool
2416 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2417                                                      CallingConv::ID CalleeCC,
2418                                                      bool isVarArg,
2419                                                      bool isCalleeStructRet,
2420                                                      bool isCallerStructRet,
2421                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2422                                     const SmallVectorImpl<SDValue> &OutVals,
2423                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2424                                                      SelectionDAG& DAG) const {
2425   if (!IsTailCallConvention(CalleeCC) &&
2426       CalleeCC != CallingConv::C)
2427     return false;
2428
2429   // If -tailcallopt is specified, make fastcc functions tail-callable.
2430   const MachineFunction &MF = DAG.getMachineFunction();
2431   const Function *CallerF = DAG.getMachineFunction().getFunction();
2432   CallingConv::ID CallerCC = CallerF->getCallingConv();
2433   bool CCMatch = CallerCC == CalleeCC;
2434
2435   if (GuaranteedTailCallOpt) {
2436     if (IsTailCallConvention(CalleeCC) && CCMatch)
2437       return true;
2438     return false;
2439   }
2440
2441   // Look for obvious safe cases to perform tail call optimization that do not
2442   // require ABI changes. This is what gcc calls sibcall.
2443
2444   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2445   // emit a special epilogue.
2446   if (RegInfo->needsStackRealignment(MF))
2447     return false;
2448
2449   // Do not sibcall optimize vararg calls unless the call site is not passing
2450   // any arguments.
2451   if (isVarArg && !Outs.empty())
2452     return false;
2453
2454   // Also avoid sibcall optimization if either caller or callee uses struct
2455   // return semantics.
2456   if (isCalleeStructRet || isCallerStructRet)
2457     return false;
2458
2459   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2460   // Therefore if it's not used by the call it is not safe to optimize this into
2461   // a sibcall.
2462   bool Unused = false;
2463   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2464     if (!Ins[i].Used) {
2465       Unused = true;
2466       break;
2467     }
2468   }
2469   if (Unused) {
2470     SmallVector<CCValAssign, 16> RVLocs;
2471     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2472                    RVLocs, *DAG.getContext());
2473     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2474     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2475       CCValAssign &VA = RVLocs[i];
2476       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2477         return false;
2478     }
2479   }
2480
2481   // If the calling conventions do not match, then we'd better make sure the
2482   // results are returned in the same way as what the caller expects.
2483   if (!CCMatch) {
2484     SmallVector<CCValAssign, 16> RVLocs1;
2485     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2486                     RVLocs1, *DAG.getContext());
2487     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2488
2489     SmallVector<CCValAssign, 16> RVLocs2;
2490     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2491                     RVLocs2, *DAG.getContext());
2492     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2493
2494     if (RVLocs1.size() != RVLocs2.size())
2495       return false;
2496     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2497       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2498         return false;
2499       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2500         return false;
2501       if (RVLocs1[i].isRegLoc()) {
2502         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2503           return false;
2504       } else {
2505         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2506           return false;
2507       }
2508     }
2509   }
2510
2511   // If the callee takes no arguments then go on to check the results of the
2512   // call.
2513   if (!Outs.empty()) {
2514     // Check if stack adjustment is needed. For now, do not do this if any
2515     // argument is passed on the stack.
2516     SmallVector<CCValAssign, 16> ArgLocs;
2517     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2518                    ArgLocs, *DAG.getContext());
2519     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2520     if (CCInfo.getNextStackOffset()) {
2521       MachineFunction &MF = DAG.getMachineFunction();
2522       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2523         return false;
2524       if (Subtarget->isTargetWin64())
2525         // Win64 ABI has additional complications.
2526         return false;
2527
2528       // Check if the arguments are already laid out in the right way as
2529       // the caller's fixed stack objects.
2530       MachineFrameInfo *MFI = MF.getFrameInfo();
2531       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2532       const X86InstrInfo *TII =
2533         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2534       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2535         CCValAssign &VA = ArgLocs[i];
2536         SDValue Arg = OutVals[i];
2537         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2538         if (VA.getLocInfo() == CCValAssign::Indirect)
2539           return false;
2540         if (!VA.isRegLoc()) {
2541           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2542                                    MFI, MRI, TII))
2543             return false;
2544         }
2545       }
2546     }
2547
2548     // If the tailcall address may be in a register, then make sure it's
2549     // possible to register allocate for it. In 32-bit, the call address can
2550     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2551     // callee-saved registers are restored. These happen to be the same
2552     // registers used to pass 'inreg' arguments so watch out for those.
2553     if (!Subtarget->is64Bit() &&
2554         !isa<GlobalAddressSDNode>(Callee) &&
2555         !isa<ExternalSymbolSDNode>(Callee)) {
2556       unsigned NumInRegs = 0;
2557       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2558         CCValAssign &VA = ArgLocs[i];
2559         if (!VA.isRegLoc())
2560           continue;
2561         unsigned Reg = VA.getLocReg();
2562         switch (Reg) {
2563         default: break;
2564         case X86::EAX: case X86::EDX: case X86::ECX:
2565           if (++NumInRegs == 3)
2566             return false;
2567           break;
2568         }
2569       }
2570     }
2571   }
2572
2573   return true;
2574 }
2575
2576 FastISel *
2577 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2578   return X86::createFastISel(funcInfo);
2579 }
2580
2581
2582 //===----------------------------------------------------------------------===//
2583 //                           Other Lowering Hooks
2584 //===----------------------------------------------------------------------===//
2585
2586 static bool MayFoldLoad(SDValue Op) {
2587   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2588 }
2589
2590 static bool MayFoldIntoStore(SDValue Op) {
2591   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2592 }
2593
2594 static bool isTargetShuffle(unsigned Opcode) {
2595   switch(Opcode) {
2596   default: return false;
2597   case X86ISD::PSHUFD:
2598   case X86ISD::PSHUFHW:
2599   case X86ISD::PSHUFLW:
2600   case X86ISD::SHUFPD:
2601   case X86ISD::PALIGN:
2602   case X86ISD::SHUFPS:
2603   case X86ISD::MOVLHPS:
2604   case X86ISD::MOVLHPD:
2605   case X86ISD::MOVHLPS:
2606   case X86ISD::MOVLPS:
2607   case X86ISD::MOVLPD:
2608   case X86ISD::MOVSHDUP:
2609   case X86ISD::MOVSLDUP:
2610   case X86ISD::MOVDDUP:
2611   case X86ISD::MOVSS:
2612   case X86ISD::MOVSD:
2613   case X86ISD::UNPCKLPS:
2614   case X86ISD::UNPCKLPD:
2615   case X86ISD::PUNPCKLWD:
2616   case X86ISD::PUNPCKLBW:
2617   case X86ISD::PUNPCKLDQ:
2618   case X86ISD::PUNPCKLQDQ:
2619   case X86ISD::UNPCKHPS:
2620   case X86ISD::UNPCKHPD:
2621   case X86ISD::PUNPCKHWD:
2622   case X86ISD::PUNPCKHBW:
2623   case X86ISD::PUNPCKHDQ:
2624   case X86ISD::PUNPCKHQDQ:
2625     return true;
2626   }
2627   return false;
2628 }
2629
2630 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2631                                                SDValue V1, SelectionDAG &DAG) {
2632   switch(Opc) {
2633   default: llvm_unreachable("Unknown x86 shuffle node");
2634   case X86ISD::MOVSHDUP:
2635   case X86ISD::MOVSLDUP:
2636   case X86ISD::MOVDDUP:
2637     return DAG.getNode(Opc, dl, VT, V1);
2638   }
2639
2640   return SDValue();
2641 }
2642
2643 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2644                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2645   switch(Opc) {
2646   default: llvm_unreachable("Unknown x86 shuffle node");
2647   case X86ISD::PSHUFD:
2648   case X86ISD::PSHUFHW:
2649   case X86ISD::PSHUFLW:
2650     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2651   }
2652
2653   return SDValue();
2654 }
2655
2656 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2657                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2658   switch(Opc) {
2659   default: llvm_unreachable("Unknown x86 shuffle node");
2660   case X86ISD::PALIGN:
2661   case X86ISD::SHUFPD:
2662   case X86ISD::SHUFPS:
2663     return DAG.getNode(Opc, dl, VT, V1, V2,
2664                        DAG.getConstant(TargetMask, MVT::i8));
2665   }
2666   return SDValue();
2667 }
2668
2669 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2670                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2671   switch(Opc) {
2672   default: llvm_unreachable("Unknown x86 shuffle node");
2673   case X86ISD::MOVLHPS:
2674   case X86ISD::MOVLHPD:
2675   case X86ISD::MOVHLPS:
2676   case X86ISD::MOVLPS:
2677   case X86ISD::MOVLPD:
2678   case X86ISD::MOVSS:
2679   case X86ISD::MOVSD:
2680   case X86ISD::UNPCKLPS:
2681   case X86ISD::UNPCKLPD:
2682   case X86ISD::PUNPCKLWD:
2683   case X86ISD::PUNPCKLBW:
2684   case X86ISD::PUNPCKLDQ:
2685   case X86ISD::PUNPCKLQDQ:
2686   case X86ISD::UNPCKHPS:
2687   case X86ISD::UNPCKHPD:
2688   case X86ISD::PUNPCKHWD:
2689   case X86ISD::PUNPCKHBW:
2690   case X86ISD::PUNPCKHDQ:
2691   case X86ISD::PUNPCKHQDQ:
2692     return DAG.getNode(Opc, dl, VT, V1, V2);
2693   }
2694   return SDValue();
2695 }
2696
2697 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2698   MachineFunction &MF = DAG.getMachineFunction();
2699   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2700   int ReturnAddrIndex = FuncInfo->getRAIndex();
2701
2702   if (ReturnAddrIndex == 0) {
2703     // Set up a frame object for the return address.
2704     uint64_t SlotSize = TD->getPointerSize();
2705     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2706                                                            false);
2707     FuncInfo->setRAIndex(ReturnAddrIndex);
2708   }
2709
2710   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2711 }
2712
2713
2714 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2715                                        bool hasSymbolicDisplacement) {
2716   // Offset should fit into 32 bit immediate field.
2717   if (!isInt<32>(Offset))
2718     return false;
2719
2720   // If we don't have a symbolic displacement - we don't have any extra
2721   // restrictions.
2722   if (!hasSymbolicDisplacement)
2723     return true;
2724
2725   // FIXME: Some tweaks might be needed for medium code model.
2726   if (M != CodeModel::Small && M != CodeModel::Kernel)
2727     return false;
2728
2729   // For small code model we assume that latest object is 16MB before end of 31
2730   // bits boundary. We may also accept pretty large negative constants knowing
2731   // that all objects are in the positive half of address space.
2732   if (M == CodeModel::Small && Offset < 16*1024*1024)
2733     return true;
2734
2735   // For kernel code model we know that all object resist in the negative half
2736   // of 32bits address space. We may not accept negative offsets, since they may
2737   // be just off and we may accept pretty large positive ones.
2738   if (M == CodeModel::Kernel && Offset > 0)
2739     return true;
2740
2741   return false;
2742 }
2743
2744 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2745 /// specific condition code, returning the condition code and the LHS/RHS of the
2746 /// comparison to make.
2747 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2748                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2749   if (!isFP) {
2750     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2751       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2752         // X > -1   -> X == 0, jump !sign.
2753         RHS = DAG.getConstant(0, RHS.getValueType());
2754         return X86::COND_NS;
2755       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2756         // X < 0   -> X == 0, jump on sign.
2757         return X86::COND_S;
2758       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2759         // X < 1   -> X <= 0
2760         RHS = DAG.getConstant(0, RHS.getValueType());
2761         return X86::COND_LE;
2762       }
2763     }
2764
2765     switch (SetCCOpcode) {
2766     default: llvm_unreachable("Invalid integer condition!");
2767     case ISD::SETEQ:  return X86::COND_E;
2768     case ISD::SETGT:  return X86::COND_G;
2769     case ISD::SETGE:  return X86::COND_GE;
2770     case ISD::SETLT:  return X86::COND_L;
2771     case ISD::SETLE:  return X86::COND_LE;
2772     case ISD::SETNE:  return X86::COND_NE;
2773     case ISD::SETULT: return X86::COND_B;
2774     case ISD::SETUGT: return X86::COND_A;
2775     case ISD::SETULE: return X86::COND_BE;
2776     case ISD::SETUGE: return X86::COND_AE;
2777     }
2778   }
2779
2780   // First determine if it is required or is profitable to flip the operands.
2781
2782   // If LHS is a foldable load, but RHS is not, flip the condition.
2783   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2784       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2785     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2786     std::swap(LHS, RHS);
2787   }
2788
2789   switch (SetCCOpcode) {
2790   default: break;
2791   case ISD::SETOLT:
2792   case ISD::SETOLE:
2793   case ISD::SETUGT:
2794   case ISD::SETUGE:
2795     std::swap(LHS, RHS);
2796     break;
2797   }
2798
2799   // On a floating point condition, the flags are set as follows:
2800   // ZF  PF  CF   op
2801   //  0 | 0 | 0 | X > Y
2802   //  0 | 0 | 1 | X < Y
2803   //  1 | 0 | 0 | X == Y
2804   //  1 | 1 | 1 | unordered
2805   switch (SetCCOpcode) {
2806   default: llvm_unreachable("Condcode should be pre-legalized away");
2807   case ISD::SETUEQ:
2808   case ISD::SETEQ:   return X86::COND_E;
2809   case ISD::SETOLT:              // flipped
2810   case ISD::SETOGT:
2811   case ISD::SETGT:   return X86::COND_A;
2812   case ISD::SETOLE:              // flipped
2813   case ISD::SETOGE:
2814   case ISD::SETGE:   return X86::COND_AE;
2815   case ISD::SETUGT:              // flipped
2816   case ISD::SETULT:
2817   case ISD::SETLT:   return X86::COND_B;
2818   case ISD::SETUGE:              // flipped
2819   case ISD::SETULE:
2820   case ISD::SETLE:   return X86::COND_BE;
2821   case ISD::SETONE:
2822   case ISD::SETNE:   return X86::COND_NE;
2823   case ISD::SETUO:   return X86::COND_P;
2824   case ISD::SETO:    return X86::COND_NP;
2825   case ISD::SETOEQ:
2826   case ISD::SETUNE:  return X86::COND_INVALID;
2827   }
2828 }
2829
2830 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2831 /// code. Current x86 isa includes the following FP cmov instructions:
2832 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2833 static bool hasFPCMov(unsigned X86CC) {
2834   switch (X86CC) {
2835   default:
2836     return false;
2837   case X86::COND_B:
2838   case X86::COND_BE:
2839   case X86::COND_E:
2840   case X86::COND_P:
2841   case X86::COND_A:
2842   case X86::COND_AE:
2843   case X86::COND_NE:
2844   case X86::COND_NP:
2845     return true;
2846   }
2847 }
2848
2849 /// isFPImmLegal - Returns true if the target can instruction select the
2850 /// specified FP immediate natively. If false, the legalizer will
2851 /// materialize the FP immediate as a load from a constant pool.
2852 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2853   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2854     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2855       return true;
2856   }
2857   return false;
2858 }
2859
2860 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2861 /// the specified range (L, H].
2862 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2863   return (Val < 0) || (Val >= Low && Val < Hi);
2864 }
2865
2866 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2867 /// specified value.
2868 static bool isUndefOrEqual(int Val, int CmpVal) {
2869   if (Val < 0 || Val == CmpVal)
2870     return true;
2871   return false;
2872 }
2873
2874 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2875 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2876 /// the second operand.
2877 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2878   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2879     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2880   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2881     return (Mask[0] < 2 && Mask[1] < 2);
2882   return false;
2883 }
2884
2885 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2886   SmallVector<int, 8> M;
2887   N->getMask(M);
2888   return ::isPSHUFDMask(M, N->getValueType(0));
2889 }
2890
2891 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2892 /// is suitable for input to PSHUFHW.
2893 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2894   if (VT != MVT::v8i16)
2895     return false;
2896
2897   // Lower quadword copied in order or undef.
2898   for (int i = 0; i != 4; ++i)
2899     if (Mask[i] >= 0 && Mask[i] != i)
2900       return false;
2901
2902   // Upper quadword shuffled.
2903   for (int i = 4; i != 8; ++i)
2904     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2905       return false;
2906
2907   return true;
2908 }
2909
2910 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2911   SmallVector<int, 8> M;
2912   N->getMask(M);
2913   return ::isPSHUFHWMask(M, N->getValueType(0));
2914 }
2915
2916 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2917 /// is suitable for input to PSHUFLW.
2918 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2919   if (VT != MVT::v8i16)
2920     return false;
2921
2922   // Upper quadword copied in order.
2923   for (int i = 4; i != 8; ++i)
2924     if (Mask[i] >= 0 && Mask[i] != i)
2925       return false;
2926
2927   // Lower quadword shuffled.
2928   for (int i = 0; i != 4; ++i)
2929     if (Mask[i] >= 4)
2930       return false;
2931
2932   return true;
2933 }
2934
2935 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2936   SmallVector<int, 8> M;
2937   N->getMask(M);
2938   return ::isPSHUFLWMask(M, N->getValueType(0));
2939 }
2940
2941 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2942 /// is suitable for input to PALIGNR.
2943 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2944                           bool hasSSSE3) {
2945   int i, e = VT.getVectorNumElements();
2946   
2947   // Do not handle v2i64 / v2f64 shuffles with palignr.
2948   if (e < 4 || !hasSSSE3)
2949     return false;
2950   
2951   for (i = 0; i != e; ++i)
2952     if (Mask[i] >= 0)
2953       break;
2954   
2955   // All undef, not a palignr.
2956   if (i == e)
2957     return false;
2958
2959   // Determine if it's ok to perform a palignr with only the LHS, since we
2960   // don't have access to the actual shuffle elements to see if RHS is undef.
2961   bool Unary = Mask[i] < (int)e;
2962   bool NeedsUnary = false;
2963
2964   int s = Mask[i] - i;
2965   
2966   // Check the rest of the elements to see if they are consecutive.
2967   for (++i; i != e; ++i) {
2968     int m = Mask[i];
2969     if (m < 0) 
2970       continue;
2971     
2972     Unary = Unary && (m < (int)e);
2973     NeedsUnary = NeedsUnary || (m < s);
2974
2975     if (NeedsUnary && !Unary)
2976       return false;
2977     if (Unary && m != ((s+i) & (e-1)))
2978       return false;
2979     if (!Unary && m != (s+i))
2980       return false;
2981   }
2982   return true;
2983 }
2984
2985 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2986   SmallVector<int, 8> M;
2987   N->getMask(M);
2988   return ::isPALIGNRMask(M, N->getValueType(0), true);
2989 }
2990
2991 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2992 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2993 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2994   int NumElems = VT.getVectorNumElements();
2995   if (NumElems != 2 && NumElems != 4)
2996     return false;
2997
2998   int Half = NumElems / 2;
2999   for (int i = 0; i < Half; ++i)
3000     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3001       return false;
3002   for (int i = Half; i < NumElems; ++i)
3003     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3004       return false;
3005
3006   return true;
3007 }
3008
3009 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3010   SmallVector<int, 8> M;
3011   N->getMask(M);
3012   return ::isSHUFPMask(M, N->getValueType(0));
3013 }
3014
3015 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3016 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3017 /// half elements to come from vector 1 (which would equal the dest.) and
3018 /// the upper half to come from vector 2.
3019 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3020   int NumElems = VT.getVectorNumElements();
3021
3022   if (NumElems != 2 && NumElems != 4)
3023     return false;
3024
3025   int Half = NumElems / 2;
3026   for (int i = 0; i < Half; ++i)
3027     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3028       return false;
3029   for (int i = Half; i < NumElems; ++i)
3030     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3031       return false;
3032   return true;
3033 }
3034
3035 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3036   SmallVector<int, 8> M;
3037   N->getMask(M);
3038   return isCommutedSHUFPMask(M, N->getValueType(0));
3039 }
3040
3041 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3042 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3043 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3044   if (N->getValueType(0).getVectorNumElements() != 4)
3045     return false;
3046
3047   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3048   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3049          isUndefOrEqual(N->getMaskElt(1), 7) &&
3050          isUndefOrEqual(N->getMaskElt(2), 2) &&
3051          isUndefOrEqual(N->getMaskElt(3), 3);
3052 }
3053
3054 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3055 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3056 /// <2, 3, 2, 3>
3057 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3058   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3059   
3060   if (NumElems != 4)
3061     return false;
3062   
3063   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3064   isUndefOrEqual(N->getMaskElt(1), 3) &&
3065   isUndefOrEqual(N->getMaskElt(2), 2) &&
3066   isUndefOrEqual(N->getMaskElt(3), 3);
3067 }
3068
3069 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3070 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3071 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3072   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3073
3074   if (NumElems != 2 && NumElems != 4)
3075     return false;
3076
3077   for (unsigned i = 0; i < NumElems/2; ++i)
3078     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3079       return false;
3080
3081   for (unsigned i = NumElems/2; i < NumElems; ++i)
3082     if (!isUndefOrEqual(N->getMaskElt(i), i))
3083       return false;
3084
3085   return true;
3086 }
3087
3088 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3089 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3090 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3091   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3092
3093   if (NumElems != 2 && NumElems != 4)
3094     return false;
3095
3096   for (unsigned i = 0; i < NumElems/2; ++i)
3097     if (!isUndefOrEqual(N->getMaskElt(i), i))
3098       return false;
3099
3100   for (unsigned i = 0; i < NumElems/2; ++i)
3101     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3102       return false;
3103
3104   return true;
3105 }
3106
3107 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3108 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3109 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3110                          bool V2IsSplat = false) {
3111   int NumElts = VT.getVectorNumElements();
3112   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3113     return false;
3114
3115   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3116     int BitI  = Mask[i];
3117     int BitI1 = Mask[i+1];
3118     if (!isUndefOrEqual(BitI, j))
3119       return false;
3120     if (V2IsSplat) {
3121       if (!isUndefOrEqual(BitI1, NumElts))
3122         return false;
3123     } else {
3124       if (!isUndefOrEqual(BitI1, j + NumElts))
3125         return false;
3126     }
3127   }
3128   return true;
3129 }
3130
3131 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3132   SmallVector<int, 8> M;
3133   N->getMask(M);
3134   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3135 }
3136
3137 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3138 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3139 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3140                          bool V2IsSplat = false) {
3141   int NumElts = VT.getVectorNumElements();
3142   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3143     return false;
3144
3145   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3146     int BitI  = Mask[i];
3147     int BitI1 = Mask[i+1];
3148     if (!isUndefOrEqual(BitI, j + NumElts/2))
3149       return false;
3150     if (V2IsSplat) {
3151       if (isUndefOrEqual(BitI1, NumElts))
3152         return false;
3153     } else {
3154       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3155         return false;
3156     }
3157   }
3158   return true;
3159 }
3160
3161 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3162   SmallVector<int, 8> M;
3163   N->getMask(M);
3164   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3165 }
3166
3167 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3168 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3169 /// <0, 0, 1, 1>
3170 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3171   int NumElems = VT.getVectorNumElements();
3172   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3173     return false;
3174
3175   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3176     int BitI  = Mask[i];
3177     int BitI1 = Mask[i+1];
3178     if (!isUndefOrEqual(BitI, j))
3179       return false;
3180     if (!isUndefOrEqual(BitI1, j))
3181       return false;
3182   }
3183   return true;
3184 }
3185
3186 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3187   SmallVector<int, 8> M;
3188   N->getMask(M);
3189   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3190 }
3191
3192 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3193 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3194 /// <2, 2, 3, 3>
3195 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3196   int NumElems = VT.getVectorNumElements();
3197   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3198     return false;
3199
3200   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3201     int BitI  = Mask[i];
3202     int BitI1 = Mask[i+1];
3203     if (!isUndefOrEqual(BitI, j))
3204       return false;
3205     if (!isUndefOrEqual(BitI1, j))
3206       return false;
3207   }
3208   return true;
3209 }
3210
3211 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3212   SmallVector<int, 8> M;
3213   N->getMask(M);
3214   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3215 }
3216
3217 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3218 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3219 /// MOVSD, and MOVD, i.e. setting the lowest element.
3220 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3221   if (VT.getVectorElementType().getSizeInBits() < 32)
3222     return false;
3223
3224   int NumElts = VT.getVectorNumElements();
3225
3226   if (!isUndefOrEqual(Mask[0], NumElts))
3227     return false;
3228
3229   for (int i = 1; i < NumElts; ++i)
3230     if (!isUndefOrEqual(Mask[i], i))
3231       return false;
3232
3233   return true;
3234 }
3235
3236 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3237   SmallVector<int, 8> M;
3238   N->getMask(M);
3239   return ::isMOVLMask(M, N->getValueType(0));
3240 }
3241
3242 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3243 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3244 /// element of vector 2 and the other elements to come from vector 1 in order.
3245 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3246                                bool V2IsSplat = false, bool V2IsUndef = false) {
3247   int NumOps = VT.getVectorNumElements();
3248   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3249     return false;
3250
3251   if (!isUndefOrEqual(Mask[0], 0))
3252     return false;
3253
3254   for (int i = 1; i < NumOps; ++i)
3255     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3256           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3257           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3258       return false;
3259
3260   return true;
3261 }
3262
3263 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3264                            bool V2IsUndef = false) {
3265   SmallVector<int, 8> M;
3266   N->getMask(M);
3267   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3268 }
3269
3270 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3271 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3272 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3273   if (N->getValueType(0).getVectorNumElements() != 4)
3274     return false;
3275
3276   // Expect 1, 1, 3, 3
3277   for (unsigned i = 0; i < 2; ++i) {
3278     int Elt = N->getMaskElt(i);
3279     if (Elt >= 0 && Elt != 1)
3280       return false;
3281   }
3282
3283   bool HasHi = false;
3284   for (unsigned i = 2; i < 4; ++i) {
3285     int Elt = N->getMaskElt(i);
3286     if (Elt >= 0 && Elt != 3)
3287       return false;
3288     if (Elt == 3)
3289       HasHi = true;
3290   }
3291   // Don't use movshdup if it can be done with a shufps.
3292   // FIXME: verify that matching u, u, 3, 3 is what we want.
3293   return HasHi;
3294 }
3295
3296 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3297 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3298 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3299   if (N->getValueType(0).getVectorNumElements() != 4)
3300     return false;
3301
3302   // Expect 0, 0, 2, 2
3303   for (unsigned i = 0; i < 2; ++i)
3304     if (N->getMaskElt(i) > 0)
3305       return false;
3306
3307   bool HasHi = false;
3308   for (unsigned i = 2; i < 4; ++i) {
3309     int Elt = N->getMaskElt(i);
3310     if (Elt >= 0 && Elt != 2)
3311       return false;
3312     if (Elt == 2)
3313       HasHi = true;
3314   }
3315   // Don't use movsldup if it can be done with a shufps.
3316   return HasHi;
3317 }
3318
3319 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3320 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3321 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3322   int e = N->getValueType(0).getVectorNumElements() / 2;
3323
3324   for (int i = 0; i < e; ++i)
3325     if (!isUndefOrEqual(N->getMaskElt(i), i))
3326       return false;
3327   for (int i = 0; i < e; ++i)
3328     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3329       return false;
3330   return true;
3331 }
3332
3333 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3334 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3335 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3336   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3337   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3338
3339   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3340   unsigned Mask = 0;
3341   for (int i = 0; i < NumOperands; ++i) {
3342     int Val = SVOp->getMaskElt(NumOperands-i-1);
3343     if (Val < 0) Val = 0;
3344     if (Val >= NumOperands) Val -= NumOperands;
3345     Mask |= Val;
3346     if (i != NumOperands - 1)
3347       Mask <<= Shift;
3348   }
3349   return Mask;
3350 }
3351
3352 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3353 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3354 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3355   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3356   unsigned Mask = 0;
3357   // 8 nodes, but we only care about the last 4.
3358   for (unsigned i = 7; i >= 4; --i) {
3359     int Val = SVOp->getMaskElt(i);
3360     if (Val >= 0)
3361       Mask |= (Val - 4);
3362     if (i != 4)
3363       Mask <<= 2;
3364   }
3365   return Mask;
3366 }
3367
3368 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3369 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3370 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3371   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3372   unsigned Mask = 0;
3373   // 8 nodes, but we only care about the first 4.
3374   for (int i = 3; i >= 0; --i) {
3375     int Val = SVOp->getMaskElt(i);
3376     if (Val >= 0)
3377       Mask |= Val;
3378     if (i != 0)
3379       Mask <<= 2;
3380   }
3381   return Mask;
3382 }
3383
3384 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3385 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3386 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3387   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3388   EVT VVT = N->getValueType(0);
3389   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3390   int Val = 0;
3391
3392   unsigned i, e;
3393   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3394     Val = SVOp->getMaskElt(i);
3395     if (Val >= 0)
3396       break;
3397   }
3398   return (Val - i) * EltSize;
3399 }
3400
3401 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3402 /// constant +0.0.
3403 bool X86::isZeroNode(SDValue Elt) {
3404   return ((isa<ConstantSDNode>(Elt) &&
3405            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3406           (isa<ConstantFPSDNode>(Elt) &&
3407            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3408 }
3409
3410 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3411 /// their permute mask.
3412 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3413                                     SelectionDAG &DAG) {
3414   EVT VT = SVOp->getValueType(0);
3415   unsigned NumElems = VT.getVectorNumElements();
3416   SmallVector<int, 8> MaskVec;
3417
3418   for (unsigned i = 0; i != NumElems; ++i) {
3419     int idx = SVOp->getMaskElt(i);
3420     if (idx < 0)
3421       MaskVec.push_back(idx);
3422     else if (idx < (int)NumElems)
3423       MaskVec.push_back(idx + NumElems);
3424     else
3425       MaskVec.push_back(idx - NumElems);
3426   }
3427   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3428                               SVOp->getOperand(0), &MaskVec[0]);
3429 }
3430
3431 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3432 /// the two vector operands have swapped position.
3433 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3434   unsigned NumElems = VT.getVectorNumElements();
3435   for (unsigned i = 0; i != NumElems; ++i) {
3436     int idx = Mask[i];
3437     if (idx < 0)
3438       continue;
3439     else if (idx < (int)NumElems)
3440       Mask[i] = idx + NumElems;
3441     else
3442       Mask[i] = idx - NumElems;
3443   }
3444 }
3445
3446 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3447 /// match movhlps. The lower half elements should come from upper half of
3448 /// V1 (and in order), and the upper half elements should come from the upper
3449 /// half of V2 (and in order).
3450 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3451   if (Op->getValueType(0).getVectorNumElements() != 4)
3452     return false;
3453   for (unsigned i = 0, e = 2; i != e; ++i)
3454     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3455       return false;
3456   for (unsigned i = 2; i != 4; ++i)
3457     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3458       return false;
3459   return true;
3460 }
3461
3462 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3463 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3464 /// required.
3465 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3466   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3467     return false;
3468   N = N->getOperand(0).getNode();
3469   if (!ISD::isNON_EXTLoad(N))
3470     return false;
3471   if (LD)
3472     *LD = cast<LoadSDNode>(N);
3473   return true;
3474 }
3475
3476 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3477 /// match movlp{s|d}. The lower half elements should come from lower half of
3478 /// V1 (and in order), and the upper half elements should come from the upper
3479 /// half of V2 (and in order). And since V1 will become the source of the
3480 /// MOVLP, it must be either a vector load or a scalar load to vector.
3481 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3482                                ShuffleVectorSDNode *Op) {
3483   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3484     return false;
3485   // Is V2 is a vector load, don't do this transformation. We will try to use
3486   // load folding shufps op.
3487   if (ISD::isNON_EXTLoad(V2))
3488     return false;
3489
3490   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3491
3492   if (NumElems != 2 && NumElems != 4)
3493     return false;
3494   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3495     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3496       return false;
3497   for (unsigned i = NumElems/2; i != NumElems; ++i)
3498     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3499       return false;
3500   return true;
3501 }
3502
3503 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3504 /// all the same.
3505 static bool isSplatVector(SDNode *N) {
3506   if (N->getOpcode() != ISD::BUILD_VECTOR)
3507     return false;
3508
3509   SDValue SplatValue = N->getOperand(0);
3510   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3511     if (N->getOperand(i) != SplatValue)
3512       return false;
3513   return true;
3514 }
3515
3516 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3517 /// to an zero vector.
3518 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3519 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3520   SDValue V1 = N->getOperand(0);
3521   SDValue V2 = N->getOperand(1);
3522   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3523   for (unsigned i = 0; i != NumElems; ++i) {
3524     int Idx = N->getMaskElt(i);
3525     if (Idx >= (int)NumElems) {
3526       unsigned Opc = V2.getOpcode();
3527       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3528         continue;
3529       if (Opc != ISD::BUILD_VECTOR ||
3530           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3531         return false;
3532     } else if (Idx >= 0) {
3533       unsigned Opc = V1.getOpcode();
3534       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3535         continue;
3536       if (Opc != ISD::BUILD_VECTOR ||
3537           !X86::isZeroNode(V1.getOperand(Idx)))
3538         return false;
3539     }
3540   }
3541   return true;
3542 }
3543
3544 /// getZeroVector - Returns a vector of specified type with all zero elements.
3545 ///
3546 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3547                              DebugLoc dl) {
3548   assert(VT.isVector() && "Expected a vector type");
3549
3550   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted
3551   // to their dest type. This ensures they get CSE'd.
3552   SDValue Vec;
3553   if (VT.getSizeInBits() == 64) { // MMX
3554     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3555     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3556   } else if (VT.getSizeInBits() == 128) {
3557     if (HasSSE2) {  // SSE2
3558       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3559       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3560     } else { // SSE1
3561       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3562       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3563     }
3564   } else if (VT.getSizeInBits() == 256) { // AVX
3565     // 256-bit logic and arithmetic instructions in AVX are
3566     // all floating-point, no support for integer ops. Default
3567     // to emitting fp zeroed vectors then.
3568     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3569     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3570     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3571   }
3572   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3573 }
3574
3575 /// getOnesVector - Returns a vector of specified type with all bits set.
3576 ///
3577 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3578   assert(VT.isVector() && "Expected a vector type");
3579
3580   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3581   // type.  This ensures they get CSE'd.
3582   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3583   SDValue Vec;
3584   if (VT.getSizeInBits() == 64) // MMX
3585     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3586   else // SSE
3587     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3588   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3589 }
3590
3591
3592 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3593 /// that point to V2 points to its first element.
3594 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3595   EVT VT = SVOp->getValueType(0);
3596   unsigned NumElems = VT.getVectorNumElements();
3597
3598   bool Changed = false;
3599   SmallVector<int, 8> MaskVec;
3600   SVOp->getMask(MaskVec);
3601
3602   for (unsigned i = 0; i != NumElems; ++i) {
3603     if (MaskVec[i] > (int)NumElems) {
3604       MaskVec[i] = NumElems;
3605       Changed = true;
3606     }
3607   }
3608   if (Changed)
3609     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3610                                 SVOp->getOperand(1), &MaskVec[0]);
3611   return SDValue(SVOp, 0);
3612 }
3613
3614 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3615 /// operation of specified width.
3616 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3617                        SDValue V2) {
3618   unsigned NumElems = VT.getVectorNumElements();
3619   SmallVector<int, 8> Mask;
3620   Mask.push_back(NumElems);
3621   for (unsigned i = 1; i != NumElems; ++i)
3622     Mask.push_back(i);
3623   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3624 }
3625
3626 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3627 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3628                           SDValue V2) {
3629   unsigned NumElems = VT.getVectorNumElements();
3630   SmallVector<int, 8> Mask;
3631   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3632     Mask.push_back(i);
3633     Mask.push_back(i + NumElems);
3634   }
3635   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3636 }
3637
3638 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3639 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3640                           SDValue V2) {
3641   unsigned NumElems = VT.getVectorNumElements();
3642   unsigned Half = NumElems/2;
3643   SmallVector<int, 8> Mask;
3644   for (unsigned i = 0; i != Half; ++i) {
3645     Mask.push_back(i + Half);
3646     Mask.push_back(i + NumElems + Half);
3647   }
3648   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3649 }
3650
3651 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3652 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3653   EVT PVT = MVT::v4f32;
3654   EVT VT = SV->getValueType(0);
3655   DebugLoc dl = SV->getDebugLoc();
3656   SDValue V1 = SV->getOperand(0);
3657   int NumElems = VT.getVectorNumElements();
3658   int EltNo = SV->getSplatIndex();
3659
3660   // unpack elements to the correct location
3661   while (NumElems > 4) {
3662     if (EltNo < NumElems/2) {
3663       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3664     } else {
3665       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3666       EltNo -= NumElems/2;
3667     }
3668     NumElems >>= 1;
3669   }
3670
3671   // Perform the splat.
3672   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3673   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3674   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3675   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3676 }
3677
3678 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3679 /// vector of zero or undef vector.  This produces a shuffle where the low
3680 /// element of V2 is swizzled into the zero/undef vector, landing at element
3681 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3682 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3683                                              bool isZero, bool HasSSE2,
3684                                              SelectionDAG &DAG) {
3685   EVT VT = V2.getValueType();
3686   SDValue V1 = isZero
3687     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3688   unsigned NumElems = VT.getVectorNumElements();
3689   SmallVector<int, 16> MaskVec;
3690   for (unsigned i = 0; i != NumElems; ++i)
3691     // If this is the insertion idx, put the low elt of V2 here.
3692     MaskVec.push_back(i == Idx ? NumElems : i);
3693   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3694 }
3695
3696 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3697 /// element of the result of the vector shuffle.
3698 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3699                             unsigned Depth) {
3700   if (Depth == 6)
3701     return SDValue();  // Limit search depth.
3702
3703   SDValue V = SDValue(N, 0);
3704   EVT VT = V.getValueType();
3705   unsigned Opcode = V.getOpcode();
3706
3707   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3708   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3709     Index = SV->getMaskElt(Index);
3710
3711     if (Index < 0)
3712       return DAG.getUNDEF(VT.getVectorElementType());
3713
3714     int NumElems = VT.getVectorNumElements();
3715     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3716     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3717   }
3718
3719   // Recurse into target specific vector shuffles to find scalars.
3720   if (isTargetShuffle(Opcode)) {
3721     int NumElems = VT.getVectorNumElements();
3722     SmallVector<unsigned, 16> ShuffleMask;
3723     SDValue ImmN;
3724
3725     switch(Opcode) {
3726     case X86ISD::SHUFPS:
3727     case X86ISD::SHUFPD:
3728       ImmN = N->getOperand(N->getNumOperands()-1);
3729       DecodeSHUFPSMask(NumElems,
3730                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3731                        ShuffleMask);
3732       break;
3733     case X86ISD::PUNPCKHBW:
3734     case X86ISD::PUNPCKHWD:
3735     case X86ISD::PUNPCKHDQ:
3736     case X86ISD::PUNPCKHQDQ:
3737       DecodePUNPCKHMask(NumElems, ShuffleMask);
3738       break;
3739     case X86ISD::UNPCKHPS:
3740     case X86ISD::UNPCKHPD:
3741       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3742       break;
3743     case X86ISD::PUNPCKLBW:
3744     case X86ISD::PUNPCKLWD:
3745     case X86ISD::PUNPCKLDQ:
3746     case X86ISD::PUNPCKLQDQ:
3747       DecodePUNPCKLMask(NumElems, ShuffleMask);
3748       break;
3749     case X86ISD::UNPCKLPS:
3750     case X86ISD::UNPCKLPD:
3751       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3752       break;
3753     case X86ISD::MOVHLPS:
3754       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3755       break;
3756     case X86ISD::MOVLHPS:
3757       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3758       break;
3759     case X86ISD::PSHUFD:
3760       ImmN = N->getOperand(N->getNumOperands()-1);
3761       DecodePSHUFMask(NumElems,
3762                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3763                       ShuffleMask);
3764       break;
3765     case X86ISD::PSHUFHW:
3766       ImmN = N->getOperand(N->getNumOperands()-1);
3767       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3768                         ShuffleMask);
3769       break;
3770     case X86ISD::PSHUFLW:
3771       ImmN = N->getOperand(N->getNumOperands()-1);
3772       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3773                         ShuffleMask);
3774       break;
3775     case X86ISD::MOVSS:
3776     case X86ISD::MOVSD: {
3777       // The index 0 always comes from the first element of the second source,
3778       // this is why MOVSS and MOVSD are used in the first place. The other
3779       // elements come from the other positions of the first source vector.
3780       unsigned OpNum = (Index == 0) ? 1 : 0;
3781       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3782                                  Depth+1);
3783     }
3784     default:
3785       assert("not implemented for target shuffle node");
3786       return SDValue();
3787     }
3788
3789     Index = ShuffleMask[Index];
3790     if (Index < 0)
3791       return DAG.getUNDEF(VT.getVectorElementType());
3792
3793     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3794     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3795                                Depth+1);
3796   }
3797
3798   // Actual nodes that may contain scalar elements
3799   if (Opcode == ISD::BIT_CONVERT) {
3800     V = V.getOperand(0);
3801     EVT SrcVT = V.getValueType();
3802     unsigned NumElems = VT.getVectorNumElements();
3803
3804     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3805       return SDValue();
3806   }
3807
3808   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3809     return (Index == 0) ? V.getOperand(0)
3810                           : DAG.getUNDEF(VT.getVectorElementType());
3811
3812   if (V.getOpcode() == ISD::BUILD_VECTOR)
3813     return V.getOperand(Index);
3814
3815   return SDValue();
3816 }
3817
3818 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3819 /// shuffle operation which come from a consecutively from a zero. The
3820 /// search can start in two diferent directions, from left or right.
3821 static
3822 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3823                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3824   int i = 0;
3825
3826   while (i < NumElems) {
3827     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3828     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3829     if (!(Elt.getNode() &&
3830          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3831       break;
3832     ++i;
3833   }
3834
3835   return i;
3836 }
3837
3838 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3839 /// MaskE correspond consecutively to elements from one of the vector operands,
3840 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3841 static
3842 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3843                               int OpIdx, int NumElems, unsigned &OpNum) {
3844   bool SeenV1 = false;
3845   bool SeenV2 = false;
3846
3847   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3848     int Idx = SVOp->getMaskElt(i);
3849     // Ignore undef indicies
3850     if (Idx < 0)
3851       continue;
3852
3853     if (Idx < NumElems)
3854       SeenV1 = true;
3855     else
3856       SeenV2 = true;
3857
3858     // Only accept consecutive elements from the same vector
3859     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3860       return false;
3861   }
3862
3863   OpNum = SeenV1 ? 0 : 1;
3864   return true;
3865 }
3866
3867 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3868 /// logical left shift of a vector.
3869 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3870                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3871   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3872   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3873               false /* check zeros from right */, DAG);
3874   unsigned OpSrc;
3875
3876   if (!NumZeros)
3877     return false;
3878
3879   // Considering the elements in the mask that are not consecutive zeros,
3880   // check if they consecutively come from only one of the source vectors.
3881   //
3882   //               V1 = {X, A, B, C}     0
3883   //                         \  \  \    /
3884   //   vector_shuffle V1, V2 <1, 2, 3, X>
3885   //
3886   if (!isShuffleMaskConsecutive(SVOp,
3887             0,                   // Mask Start Index
3888             NumElems-NumZeros-1, // Mask End Index
3889             NumZeros,            // Where to start looking in the src vector
3890             NumElems,            // Number of elements in vector
3891             OpSrc))              // Which source operand ?
3892     return false;
3893
3894   isLeft = false;
3895   ShAmt = NumZeros;
3896   ShVal = SVOp->getOperand(OpSrc);
3897   return true;
3898 }
3899
3900 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3901 /// logical left shift of a vector.
3902 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3903                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3904   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3905   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3906               true /* check zeros from left */, DAG);
3907   unsigned OpSrc;
3908
3909   if (!NumZeros)
3910     return false;
3911
3912   // Considering the elements in the mask that are not consecutive zeros,
3913   // check if they consecutively come from only one of the source vectors.
3914   //
3915   //                           0    { A, B, X, X } = V2
3916   //                          / \    /  /
3917   //   vector_shuffle V1, V2 <X, X, 4, 5>
3918   //
3919   if (!isShuffleMaskConsecutive(SVOp,
3920             NumZeros,     // Mask Start Index
3921             NumElems-1,   // Mask End Index
3922             0,            // Where to start looking in the src vector
3923             NumElems,     // Number of elements in vector
3924             OpSrc))       // Which source operand ?
3925     return false;
3926
3927   isLeft = true;
3928   ShAmt = NumZeros;
3929   ShVal = SVOp->getOperand(OpSrc);
3930   return true;
3931 }
3932
3933 /// isVectorShift - Returns true if the shuffle can be implemented as a
3934 /// logical left or right shift of a vector.
3935 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3936                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3937   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3938       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3939     return true;
3940
3941   return false;
3942 }
3943
3944 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3945 ///
3946 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3947                                        unsigned NumNonZero, unsigned NumZero,
3948                                        SelectionDAG &DAG,
3949                                        const TargetLowering &TLI) {
3950   if (NumNonZero > 8)
3951     return SDValue();
3952
3953   DebugLoc dl = Op.getDebugLoc();
3954   SDValue V(0, 0);
3955   bool First = true;
3956   for (unsigned i = 0; i < 16; ++i) {
3957     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3958     if (ThisIsNonZero && First) {
3959       if (NumZero)
3960         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3961       else
3962         V = DAG.getUNDEF(MVT::v8i16);
3963       First = false;
3964     }
3965
3966     if ((i & 1) != 0) {
3967       SDValue ThisElt(0, 0), LastElt(0, 0);
3968       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3969       if (LastIsNonZero) {
3970         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3971                               MVT::i16, Op.getOperand(i-1));
3972       }
3973       if (ThisIsNonZero) {
3974         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3975         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3976                               ThisElt, DAG.getConstant(8, MVT::i8));
3977         if (LastIsNonZero)
3978           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3979       } else
3980         ThisElt = LastElt;
3981
3982       if (ThisElt.getNode())
3983         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3984                         DAG.getIntPtrConstant(i/2));
3985     }
3986   }
3987
3988   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3989 }
3990
3991 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3992 ///
3993 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3994                                      unsigned NumNonZero, unsigned NumZero,
3995                                      SelectionDAG &DAG,
3996                                      const TargetLowering &TLI) {
3997   if (NumNonZero > 4)
3998     return SDValue();
3999
4000   DebugLoc dl = Op.getDebugLoc();
4001   SDValue V(0, 0);
4002   bool First = true;
4003   for (unsigned i = 0; i < 8; ++i) {
4004     bool isNonZero = (NonZeros & (1 << i)) != 0;
4005     if (isNonZero) {
4006       if (First) {
4007         if (NumZero)
4008           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4009         else
4010           V = DAG.getUNDEF(MVT::v8i16);
4011         First = false;
4012       }
4013       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4014                       MVT::v8i16, V, Op.getOperand(i),
4015                       DAG.getIntPtrConstant(i));
4016     }
4017   }
4018
4019   return V;
4020 }
4021
4022 /// getVShift - Return a vector logical shift node.
4023 ///
4024 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4025                          unsigned NumBits, SelectionDAG &DAG,
4026                          const TargetLowering &TLI, DebugLoc dl) {
4027   bool isMMX = VT.getSizeInBits() == 64;
4028   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
4029   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4030   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
4031   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4032                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4033                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4034 }
4035
4036 SDValue
4037 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4038                                           SelectionDAG &DAG) const {
4039   
4040   // Check if the scalar load can be widened into a vector load. And if
4041   // the address is "base + cst" see if the cst can be "absorbed" into
4042   // the shuffle mask.
4043   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4044     SDValue Ptr = LD->getBasePtr();
4045     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4046       return SDValue();
4047     EVT PVT = LD->getValueType(0);
4048     if (PVT != MVT::i32 && PVT != MVT::f32)
4049       return SDValue();
4050
4051     int FI = -1;
4052     int64_t Offset = 0;
4053     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4054       FI = FINode->getIndex();
4055       Offset = 0;
4056     } else if (Ptr.getOpcode() == ISD::ADD &&
4057                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4058                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4059       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4060       Offset = Ptr.getConstantOperandVal(1);
4061       Ptr = Ptr.getOperand(0);
4062     } else {
4063       return SDValue();
4064     }
4065
4066     SDValue Chain = LD->getChain();
4067     // Make sure the stack object alignment is at least 16.
4068     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4069     if (DAG.InferPtrAlignment(Ptr) < 16) {
4070       if (MFI->isFixedObjectIndex(FI)) {
4071         // Can't change the alignment. FIXME: It's possible to compute
4072         // the exact stack offset and reference FI + adjust offset instead.
4073         // If someone *really* cares about this. That's the way to implement it.
4074         return SDValue();
4075       } else {
4076         MFI->setObjectAlignment(FI, 16);
4077       }
4078     }
4079
4080     // (Offset % 16) must be multiple of 4. Then address is then
4081     // Ptr + (Offset & ~15).
4082     if (Offset < 0)
4083       return SDValue();
4084     if ((Offset % 16) & 3)
4085       return SDValue();
4086     int64_t StartOffset = Offset & ~15;
4087     if (StartOffset)
4088       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4089                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4090
4091     int EltNo = (Offset - StartOffset) >> 2;
4092     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4093     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4094     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4095                              LD->getPointerInfo().getWithOffset(StartOffset),
4096                              false, false, 0);
4097     // Canonicalize it to a v4i32 shuffle.
4098     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4099     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4100                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4101                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4102   }
4103
4104   return SDValue();
4105 }
4106
4107 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
4108 /// vector of type 'VT', see if the elements can be replaced by a single large 
4109 /// load which has the same value as a build_vector whose operands are 'elts'.
4110 ///
4111 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4112 /// 
4113 /// FIXME: we'd also like to handle the case where the last elements are zero
4114 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4115 /// There's even a handy isZeroNode for that purpose.
4116 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4117                                         DebugLoc &dl, SelectionDAG &DAG) {
4118   EVT EltVT = VT.getVectorElementType();
4119   unsigned NumElems = Elts.size();
4120   
4121   LoadSDNode *LDBase = NULL;
4122   unsigned LastLoadedElt = -1U;
4123   
4124   // For each element in the initializer, see if we've found a load or an undef.
4125   // If we don't find an initial load element, or later load elements are 
4126   // non-consecutive, bail out.
4127   for (unsigned i = 0; i < NumElems; ++i) {
4128     SDValue Elt = Elts[i];
4129     
4130     if (!Elt.getNode() ||
4131         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4132       return SDValue();
4133     if (!LDBase) {
4134       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4135         return SDValue();
4136       LDBase = cast<LoadSDNode>(Elt.getNode());
4137       LastLoadedElt = i;
4138       continue;
4139     }
4140     if (Elt.getOpcode() == ISD::UNDEF)
4141       continue;
4142
4143     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4144     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4145       return SDValue();
4146     LastLoadedElt = i;
4147   }
4148
4149   // If we have found an entire vector of loads and undefs, then return a large
4150   // load of the entire vector width starting at the base pointer.  If we found
4151   // consecutive loads for the low half, generate a vzext_load node.
4152   if (LastLoadedElt == NumElems - 1) {
4153     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4154       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
4155                          LDBase->getPointerInfo(),
4156                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4157     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
4158                        LDBase->getPointerInfo(),
4159                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4160                        LDBase->getAlignment());
4161   } else if (NumElems == 4 && LastLoadedElt == 1) {
4162     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4163     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4164     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
4165     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
4166   }
4167   return SDValue();
4168 }
4169
4170 SDValue
4171 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4172   DebugLoc dl = Op.getDebugLoc();
4173   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4174   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4175   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4176   // is present, so AllOnes is ignored.
4177   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4178       (Op.getValueType().getSizeInBits() != 256 &&
4179        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4180     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
4181     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4182     // eliminated on x86-32 hosts.
4183     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
4184       return Op;
4185
4186     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4187       return getOnesVector(Op.getValueType(), DAG, dl);
4188     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4189   }
4190
4191   EVT VT = Op.getValueType();
4192   EVT ExtVT = VT.getVectorElementType();
4193   unsigned EVTBits = ExtVT.getSizeInBits();
4194
4195   unsigned NumElems = Op.getNumOperands();
4196   unsigned NumZero  = 0;
4197   unsigned NumNonZero = 0;
4198   unsigned NonZeros = 0;
4199   bool IsAllConstants = true;
4200   SmallSet<SDValue, 8> Values;
4201   for (unsigned i = 0; i < NumElems; ++i) {
4202     SDValue Elt = Op.getOperand(i);
4203     if (Elt.getOpcode() == ISD::UNDEF)
4204       continue;
4205     Values.insert(Elt);
4206     if (Elt.getOpcode() != ISD::Constant &&
4207         Elt.getOpcode() != ISD::ConstantFP)
4208       IsAllConstants = false;
4209     if (X86::isZeroNode(Elt))
4210       NumZero++;
4211     else {
4212       NonZeros |= (1 << i);
4213       NumNonZero++;
4214     }
4215   }
4216
4217   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4218   if (NumNonZero == 0)
4219     return DAG.getUNDEF(VT);
4220
4221   // Special case for single non-zero, non-undef, element.
4222   if (NumNonZero == 1) {
4223     unsigned Idx = CountTrailingZeros_32(NonZeros);
4224     SDValue Item = Op.getOperand(Idx);
4225
4226     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4227     // the value are obviously zero, truncate the value to i32 and do the
4228     // insertion that way.  Only do this if the value is non-constant or if the
4229     // value is a constant being inserted into element 0.  It is cheaper to do
4230     // a constant pool load than it is to do a movd + shuffle.
4231     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4232         (!IsAllConstants || Idx == 0)) {
4233       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4234         // Handle MMX and SSE both.
4235         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
4236         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
4237
4238         // Truncate the value (which may itself be a constant) to i32, and
4239         // convert it to a vector with movd (S2V+shuffle to zero extend).
4240         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4241         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4242         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4243                                            Subtarget->hasSSE2(), DAG);
4244
4245         // Now we have our 32-bit value zero extended in the low element of
4246         // a vector.  If Idx != 0, swizzle it into place.
4247         if (Idx != 0) {
4248           SmallVector<int, 4> Mask;
4249           Mask.push_back(Idx);
4250           for (unsigned i = 1; i != VecElts; ++i)
4251             Mask.push_back(i);
4252           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4253                                       DAG.getUNDEF(Item.getValueType()),
4254                                       &Mask[0]);
4255         }
4256         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4257       }
4258     }
4259
4260     // If we have a constant or non-constant insertion into the low element of
4261     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4262     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4263     // depending on what the source datatype is.
4264     if (Idx == 0) {
4265       if (NumZero == 0) {
4266         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4267       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4268           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4269         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4270         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4271         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4272                                            DAG);
4273       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4274         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4275         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
4276         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4277         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4278                                            Subtarget->hasSSE2(), DAG);
4279         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4280       }
4281     }
4282
4283     // Is it a vector logical left shift?
4284     if (NumElems == 2 && Idx == 1 &&
4285         X86::isZeroNode(Op.getOperand(0)) &&
4286         !X86::isZeroNode(Op.getOperand(1))) {
4287       unsigned NumBits = VT.getSizeInBits();
4288       return getVShift(true, VT,
4289                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4290                                    VT, Op.getOperand(1)),
4291                        NumBits/2, DAG, *this, dl);
4292     }
4293
4294     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4295       return SDValue();
4296
4297     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4298     // is a non-constant being inserted into an element other than the low one,
4299     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4300     // movd/movss) to move this into the low element, then shuffle it into
4301     // place.
4302     if (EVTBits == 32) {
4303       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4304
4305       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4306       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4307                                          Subtarget->hasSSE2(), DAG);
4308       SmallVector<int, 8> MaskVec;
4309       for (unsigned i = 0; i < NumElems; i++)
4310         MaskVec.push_back(i == Idx ? 0 : 1);
4311       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4312     }
4313   }
4314
4315   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4316   if (Values.size() == 1) {
4317     if (EVTBits == 32) {
4318       // Instead of a shuffle like this:
4319       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4320       // Check if it's possible to issue this instead.
4321       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4322       unsigned Idx = CountTrailingZeros_32(NonZeros);
4323       SDValue Item = Op.getOperand(Idx);
4324       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4325         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4326     }
4327     return SDValue();
4328   }
4329
4330   // A vector full of immediates; various special cases are already
4331   // handled, so this is best done with a single constant-pool load.
4332   if (IsAllConstants)
4333     return SDValue();
4334
4335   // Let legalizer expand 2-wide build_vectors.
4336   if (EVTBits == 64) {
4337     if (NumNonZero == 1) {
4338       // One half is zero or undef.
4339       unsigned Idx = CountTrailingZeros_32(NonZeros);
4340       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4341                                  Op.getOperand(Idx));
4342       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4343                                          Subtarget->hasSSE2(), DAG);
4344     }
4345     return SDValue();
4346   }
4347
4348   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4349   if (EVTBits == 8 && NumElems == 16) {
4350     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4351                                         *this);
4352     if (V.getNode()) return V;
4353   }
4354
4355   if (EVTBits == 16 && NumElems == 8) {
4356     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4357                                       *this);
4358     if (V.getNode()) return V;
4359   }
4360
4361   // If element VT is == 32 bits, turn it into a number of shuffles.
4362   SmallVector<SDValue, 8> V;
4363   V.resize(NumElems);
4364   if (NumElems == 4 && NumZero > 0) {
4365     for (unsigned i = 0; i < 4; ++i) {
4366       bool isZero = !(NonZeros & (1 << i));
4367       if (isZero)
4368         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4369       else
4370         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4371     }
4372
4373     for (unsigned i = 0; i < 2; ++i) {
4374       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4375         default: break;
4376         case 0:
4377           V[i] = V[i*2];  // Must be a zero vector.
4378           break;
4379         case 1:
4380           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4381           break;
4382         case 2:
4383           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4384           break;
4385         case 3:
4386           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4387           break;
4388       }
4389     }
4390
4391     SmallVector<int, 8> MaskVec;
4392     bool Reverse = (NonZeros & 0x3) == 2;
4393     for (unsigned i = 0; i < 2; ++i)
4394       MaskVec.push_back(Reverse ? 1-i : i);
4395     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4396     for (unsigned i = 0; i < 2; ++i)
4397       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4398     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4399   }
4400
4401   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4402     // Check for a build vector of consecutive loads.
4403     for (unsigned i = 0; i < NumElems; ++i)
4404       V[i] = Op.getOperand(i);
4405     
4406     // Check for elements which are consecutive loads.
4407     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4408     if (LD.getNode())
4409       return LD;
4410     
4411     // For SSE 4.1, use insertps to put the high elements into the low element. 
4412     if (getSubtarget()->hasSSE41()) {
4413       SDValue Result;
4414       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4415         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4416       else
4417         Result = DAG.getUNDEF(VT);
4418       
4419       for (unsigned i = 1; i < NumElems; ++i) {
4420         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4421         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4422                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4423       }
4424       return Result;
4425     }
4426     
4427     // Otherwise, expand into a number of unpckl*, start by extending each of
4428     // our (non-undef) elements to the full vector width with the element in the
4429     // bottom slot of the vector (which generates no code for SSE).
4430     for (unsigned i = 0; i < NumElems; ++i) {
4431       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4432         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4433       else
4434         V[i] = DAG.getUNDEF(VT);
4435     }
4436
4437     // Next, we iteratively mix elements, e.g. for v4f32:
4438     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4439     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4440     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4441     unsigned EltStride = NumElems >> 1;
4442     while (EltStride != 0) {
4443       for (unsigned i = 0; i < EltStride; ++i) {
4444         // If V[i+EltStride] is undef and this is the first round of mixing,
4445         // then it is safe to just drop this shuffle: V[i] is already in the
4446         // right place, the one element (since it's the first round) being
4447         // inserted as undef can be dropped.  This isn't safe for successive
4448         // rounds because they will permute elements within both vectors.
4449         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4450             EltStride == NumElems/2)
4451           continue;
4452         
4453         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4454       }
4455       EltStride >>= 1;
4456     }
4457     return V[0];
4458   }
4459   return SDValue();
4460 }
4461
4462 SDValue
4463 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4464   // We support concatenate two MMX registers and place them in a MMX
4465   // register.  This is better than doing a stack convert.
4466   DebugLoc dl = Op.getDebugLoc();
4467   EVT ResVT = Op.getValueType();
4468   assert(Op.getNumOperands() == 2);
4469   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4470          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4471   int Mask[2];
4472   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4473   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4474   InVec = Op.getOperand(1);
4475   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4476     unsigned NumElts = ResVT.getVectorNumElements();
4477     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4478     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4479                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4480   } else {
4481     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4482     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4483     Mask[0] = 0; Mask[1] = 2;
4484     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4485   }
4486   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4487 }
4488
4489 // v8i16 shuffles - Prefer shuffles in the following order:
4490 // 1. [all]   pshuflw, pshufhw, optional move
4491 // 2. [ssse3] 1 x pshufb
4492 // 3. [ssse3] 2 x pshufb + 1 x por
4493 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4494 SDValue
4495 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4496                                             SelectionDAG &DAG) const {
4497   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4498   SDValue V1 = SVOp->getOperand(0);
4499   SDValue V2 = SVOp->getOperand(1);
4500   DebugLoc dl = SVOp->getDebugLoc();
4501   SmallVector<int, 8> MaskVals;
4502
4503   // Determine if more than 1 of the words in each of the low and high quadwords
4504   // of the result come from the same quadword of one of the two inputs.  Undef
4505   // mask values count as coming from any quadword, for better codegen.
4506   SmallVector<unsigned, 4> LoQuad(4);
4507   SmallVector<unsigned, 4> HiQuad(4);
4508   BitVector InputQuads(4);
4509   for (unsigned i = 0; i < 8; ++i) {
4510     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4511     int EltIdx = SVOp->getMaskElt(i);
4512     MaskVals.push_back(EltIdx);
4513     if (EltIdx < 0) {
4514       ++Quad[0];
4515       ++Quad[1];
4516       ++Quad[2];
4517       ++Quad[3];
4518       continue;
4519     }
4520     ++Quad[EltIdx / 4];
4521     InputQuads.set(EltIdx / 4);
4522   }
4523
4524   int BestLoQuad = -1;
4525   unsigned MaxQuad = 1;
4526   for (unsigned i = 0; i < 4; ++i) {
4527     if (LoQuad[i] > MaxQuad) {
4528       BestLoQuad = i;
4529       MaxQuad = LoQuad[i];
4530     }
4531   }
4532
4533   int BestHiQuad = -1;
4534   MaxQuad = 1;
4535   for (unsigned i = 0; i < 4; ++i) {
4536     if (HiQuad[i] > MaxQuad) {
4537       BestHiQuad = i;
4538       MaxQuad = HiQuad[i];
4539     }
4540   }
4541
4542   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4543   // of the two input vectors, shuffle them into one input vector so only a
4544   // single pshufb instruction is necessary. If There are more than 2 input
4545   // quads, disable the next transformation since it does not help SSSE3.
4546   bool V1Used = InputQuads[0] || InputQuads[1];
4547   bool V2Used = InputQuads[2] || InputQuads[3];
4548   if (Subtarget->hasSSSE3()) {
4549     if (InputQuads.count() == 2 && V1Used && V2Used) {
4550       BestLoQuad = InputQuads.find_first();
4551       BestHiQuad = InputQuads.find_next(BestLoQuad);
4552     }
4553     if (InputQuads.count() > 2) {
4554       BestLoQuad = -1;
4555       BestHiQuad = -1;
4556     }
4557   }
4558
4559   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4560   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4561   // words from all 4 input quadwords.
4562   SDValue NewV;
4563   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4564     SmallVector<int, 8> MaskV;
4565     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4566     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4567     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4568                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4569                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4570     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4571
4572     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4573     // source words for the shuffle, to aid later transformations.
4574     bool AllWordsInNewV = true;
4575     bool InOrder[2] = { true, true };
4576     for (unsigned i = 0; i != 8; ++i) {
4577       int idx = MaskVals[i];
4578       if (idx != (int)i)
4579         InOrder[i/4] = false;
4580       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4581         continue;
4582       AllWordsInNewV = false;
4583       break;
4584     }
4585
4586     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4587     if (AllWordsInNewV) {
4588       for (int i = 0; i != 8; ++i) {
4589         int idx = MaskVals[i];
4590         if (idx < 0)
4591           continue;
4592         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4593         if ((idx != i) && idx < 4)
4594           pshufhw = false;
4595         if ((idx != i) && idx > 3)
4596           pshuflw = false;
4597       }
4598       V1 = NewV;
4599       V2Used = false;
4600       BestLoQuad = 0;
4601       BestHiQuad = 1;
4602     }
4603
4604     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4605     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4606     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4607       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4608       unsigned TargetMask = 0;
4609       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4610                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4611       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4612                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4613       V1 = NewV.getOperand(0);
4614       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4615     }
4616   }
4617
4618   // If we have SSSE3, and all words of the result are from 1 input vector,
4619   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4620   // is present, fall back to case 4.
4621   if (Subtarget->hasSSSE3()) {
4622     SmallVector<SDValue,16> pshufbMask;
4623
4624     // If we have elements from both input vectors, set the high bit of the
4625     // shuffle mask element to zero out elements that come from V2 in the V1
4626     // mask, and elements that come from V1 in the V2 mask, so that the two
4627     // results can be OR'd together.
4628     bool TwoInputs = V1Used && V2Used;
4629     for (unsigned i = 0; i != 8; ++i) {
4630       int EltIdx = MaskVals[i] * 2;
4631       if (TwoInputs && (EltIdx >= 16)) {
4632         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4633         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4634         continue;
4635       }
4636       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4637       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4638     }
4639     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4640     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4641                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4642                                  MVT::v16i8, &pshufbMask[0], 16));
4643     if (!TwoInputs)
4644       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4645
4646     // Calculate the shuffle mask for the second input, shuffle it, and
4647     // OR it with the first shuffled input.
4648     pshufbMask.clear();
4649     for (unsigned i = 0; i != 8; ++i) {
4650       int EltIdx = MaskVals[i] * 2;
4651       if (EltIdx < 16) {
4652         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4653         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4654         continue;
4655       }
4656       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4657       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4658     }
4659     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4660     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4661                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4662                                  MVT::v16i8, &pshufbMask[0], 16));
4663     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4664     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4665   }
4666
4667   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4668   // and update MaskVals with new element order.
4669   BitVector InOrder(8);
4670   if (BestLoQuad >= 0) {
4671     SmallVector<int, 8> MaskV;
4672     for (int i = 0; i != 4; ++i) {
4673       int idx = MaskVals[i];
4674       if (idx < 0) {
4675         MaskV.push_back(-1);
4676         InOrder.set(i);
4677       } else if ((idx / 4) == BestLoQuad) {
4678         MaskV.push_back(idx & 3);
4679         InOrder.set(i);
4680       } else {
4681         MaskV.push_back(-1);
4682       }
4683     }
4684     for (unsigned i = 4; i != 8; ++i)
4685       MaskV.push_back(i);
4686     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4687                                 &MaskV[0]);
4688
4689     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4690       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4691                                NewV.getOperand(0),
4692                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4693                                DAG);
4694   }
4695
4696   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4697   // and update MaskVals with the new element order.
4698   if (BestHiQuad >= 0) {
4699     SmallVector<int, 8> MaskV;
4700     for (unsigned i = 0; i != 4; ++i)
4701       MaskV.push_back(i);
4702     for (unsigned i = 4; i != 8; ++i) {
4703       int idx = MaskVals[i];
4704       if (idx < 0) {
4705         MaskV.push_back(-1);
4706         InOrder.set(i);
4707       } else if ((idx / 4) == BestHiQuad) {
4708         MaskV.push_back((idx & 3) + 4);
4709         InOrder.set(i);
4710       } else {
4711         MaskV.push_back(-1);
4712       }
4713     }
4714     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4715                                 &MaskV[0]);
4716
4717     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4718       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4719                               NewV.getOperand(0),
4720                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4721                               DAG);
4722   }
4723
4724   // In case BestHi & BestLo were both -1, which means each quadword has a word
4725   // from each of the four input quadwords, calculate the InOrder bitvector now
4726   // before falling through to the insert/extract cleanup.
4727   if (BestLoQuad == -1 && BestHiQuad == -1) {
4728     NewV = V1;
4729     for (int i = 0; i != 8; ++i)
4730       if (MaskVals[i] < 0 || MaskVals[i] == i)
4731         InOrder.set(i);
4732   }
4733
4734   // The other elements are put in the right place using pextrw and pinsrw.
4735   for (unsigned i = 0; i != 8; ++i) {
4736     if (InOrder[i])
4737       continue;
4738     int EltIdx = MaskVals[i];
4739     if (EltIdx < 0)
4740       continue;
4741     SDValue ExtOp = (EltIdx < 8)
4742     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4743                   DAG.getIntPtrConstant(EltIdx))
4744     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4745                   DAG.getIntPtrConstant(EltIdx - 8));
4746     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4747                        DAG.getIntPtrConstant(i));
4748   }
4749   return NewV;
4750 }
4751
4752 // v16i8 shuffles - Prefer shuffles in the following order:
4753 // 1. [ssse3] 1 x pshufb
4754 // 2. [ssse3] 2 x pshufb + 1 x por
4755 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4756 static
4757 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4758                                  SelectionDAG &DAG,
4759                                  const X86TargetLowering &TLI) {
4760   SDValue V1 = SVOp->getOperand(0);
4761   SDValue V2 = SVOp->getOperand(1);
4762   DebugLoc dl = SVOp->getDebugLoc();
4763   SmallVector<int, 16> MaskVals;
4764   SVOp->getMask(MaskVals);
4765
4766   // If we have SSSE3, case 1 is generated when all result bytes come from
4767   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4768   // present, fall back to case 3.
4769   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4770   bool V1Only = true;
4771   bool V2Only = true;
4772   for (unsigned i = 0; i < 16; ++i) {
4773     int EltIdx = MaskVals[i];
4774     if (EltIdx < 0)
4775       continue;
4776     if (EltIdx < 16)
4777       V2Only = false;
4778     else
4779       V1Only = false;
4780   }
4781
4782   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4783   if (TLI.getSubtarget()->hasSSSE3()) {
4784     SmallVector<SDValue,16> pshufbMask;
4785
4786     // If all result elements are from one input vector, then only translate
4787     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4788     //
4789     // Otherwise, we have elements from both input vectors, and must zero out
4790     // elements that come from V2 in the first mask, and V1 in the second mask
4791     // so that we can OR them together.
4792     bool TwoInputs = !(V1Only || V2Only);
4793     for (unsigned i = 0; i != 16; ++i) {
4794       int EltIdx = MaskVals[i];
4795       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4796         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4797         continue;
4798       }
4799       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4800     }
4801     // If all the elements are from V2, assign it to V1 and return after
4802     // building the first pshufb.
4803     if (V2Only)
4804       V1 = V2;
4805     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4806                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4807                                  MVT::v16i8, &pshufbMask[0], 16));
4808     if (!TwoInputs)
4809       return V1;
4810
4811     // Calculate the shuffle mask for the second input, shuffle it, and
4812     // OR it with the first shuffled input.
4813     pshufbMask.clear();
4814     for (unsigned i = 0; i != 16; ++i) {
4815       int EltIdx = MaskVals[i];
4816       if (EltIdx < 16) {
4817         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4818         continue;
4819       }
4820       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4821     }
4822     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4823                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4824                                  MVT::v16i8, &pshufbMask[0], 16));
4825     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4826   }
4827
4828   // No SSSE3 - Calculate in place words and then fix all out of place words
4829   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4830   // the 16 different words that comprise the two doublequadword input vectors.
4831   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4832   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4833   SDValue NewV = V2Only ? V2 : V1;
4834   for (int i = 0; i != 8; ++i) {
4835     int Elt0 = MaskVals[i*2];
4836     int Elt1 = MaskVals[i*2+1];
4837
4838     // This word of the result is all undef, skip it.
4839     if (Elt0 < 0 && Elt1 < 0)
4840       continue;
4841
4842     // This word of the result is already in the correct place, skip it.
4843     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4844       continue;
4845     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4846       continue;
4847
4848     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4849     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4850     SDValue InsElt;
4851
4852     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4853     // using a single extract together, load it and store it.
4854     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4855       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4856                            DAG.getIntPtrConstant(Elt1 / 2));
4857       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4858                         DAG.getIntPtrConstant(i));
4859       continue;
4860     }
4861
4862     // If Elt1 is defined, extract it from the appropriate source.  If the
4863     // source byte is not also odd, shift the extracted word left 8 bits
4864     // otherwise clear the bottom 8 bits if we need to do an or.
4865     if (Elt1 >= 0) {
4866       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4867                            DAG.getIntPtrConstant(Elt1 / 2));
4868       if ((Elt1 & 1) == 0)
4869         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4870                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4871       else if (Elt0 >= 0)
4872         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4873                              DAG.getConstant(0xFF00, MVT::i16));
4874     }
4875     // If Elt0 is defined, extract it from the appropriate source.  If the
4876     // source byte is not also even, shift the extracted word right 8 bits. If
4877     // Elt1 was also defined, OR the extracted values together before
4878     // inserting them in the result.
4879     if (Elt0 >= 0) {
4880       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4881                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4882       if ((Elt0 & 1) != 0)
4883         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4884                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4885       else if (Elt1 >= 0)
4886         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4887                              DAG.getConstant(0x00FF, MVT::i16));
4888       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4889                          : InsElt0;
4890     }
4891     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4892                        DAG.getIntPtrConstant(i));
4893   }
4894   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4895 }
4896
4897 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4898 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4899 /// done when every pair / quad of shuffle mask elements point to elements in
4900 /// the right sequence. e.g.
4901 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4902 static
4903 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4904                                  SelectionDAG &DAG, DebugLoc dl) {
4905   EVT VT = SVOp->getValueType(0);
4906   SDValue V1 = SVOp->getOperand(0);
4907   SDValue V2 = SVOp->getOperand(1);
4908   unsigned NumElems = VT.getVectorNumElements();
4909   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4910   EVT NewVT;
4911   switch (VT.getSimpleVT().SimpleTy) {
4912   default: assert(false && "Unexpected!");
4913   case MVT::v4f32: NewVT = MVT::v2f64; break;
4914   case MVT::v4i32: NewVT = MVT::v2i64; break;
4915   case MVT::v8i16: NewVT = MVT::v4i32; break;
4916   case MVT::v16i8: NewVT = MVT::v4i32; break;
4917   }
4918
4919   int Scale = NumElems / NewWidth;
4920   SmallVector<int, 8> MaskVec;
4921   for (unsigned i = 0; i < NumElems; i += Scale) {
4922     int StartIdx = -1;
4923     for (int j = 0; j < Scale; ++j) {
4924       int EltIdx = SVOp->getMaskElt(i+j);
4925       if (EltIdx < 0)
4926         continue;
4927       if (StartIdx == -1)
4928         StartIdx = EltIdx - (EltIdx % Scale);
4929       if (EltIdx != StartIdx + j)
4930         return SDValue();
4931     }
4932     if (StartIdx == -1)
4933       MaskVec.push_back(-1);
4934     else
4935       MaskVec.push_back(StartIdx / Scale);
4936   }
4937
4938   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4939   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4940   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4941 }
4942
4943 /// getVZextMovL - Return a zero-extending vector move low node.
4944 ///
4945 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4946                             SDValue SrcOp, SelectionDAG &DAG,
4947                             const X86Subtarget *Subtarget, DebugLoc dl) {
4948   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4949     LoadSDNode *LD = NULL;
4950     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4951       LD = dyn_cast<LoadSDNode>(SrcOp);
4952     if (!LD) {
4953       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4954       // instead.
4955       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4956       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4957           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4958           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4959           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4960         // PR2108
4961         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4962         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4963                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4964                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4965                                                    OpVT,
4966                                                    SrcOp.getOperand(0)
4967                                                           .getOperand(0))));
4968       }
4969     }
4970   }
4971
4972   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4973                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4974                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4975                                              OpVT, SrcOp)));
4976 }
4977
4978 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4979 /// shuffles.
4980 static SDValue
4981 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4982   SDValue V1 = SVOp->getOperand(0);
4983   SDValue V2 = SVOp->getOperand(1);
4984   DebugLoc dl = SVOp->getDebugLoc();
4985   EVT VT = SVOp->getValueType(0);
4986
4987   SmallVector<std::pair<int, int>, 8> Locs;
4988   Locs.resize(4);
4989   SmallVector<int, 8> Mask1(4U, -1);
4990   SmallVector<int, 8> PermMask;
4991   SVOp->getMask(PermMask);
4992
4993   unsigned NumHi = 0;
4994   unsigned NumLo = 0;
4995   for (unsigned i = 0; i != 4; ++i) {
4996     int Idx = PermMask[i];
4997     if (Idx < 0) {
4998       Locs[i] = std::make_pair(-1, -1);
4999     } else {
5000       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5001       if (Idx < 4) {
5002         Locs[i] = std::make_pair(0, NumLo);
5003         Mask1[NumLo] = Idx;
5004         NumLo++;
5005       } else {
5006         Locs[i] = std::make_pair(1, NumHi);
5007         if (2+NumHi < 4)
5008           Mask1[2+NumHi] = Idx;
5009         NumHi++;
5010       }
5011     }
5012   }
5013
5014   if (NumLo <= 2 && NumHi <= 2) {
5015     // If no more than two elements come from either vector. This can be
5016     // implemented with two shuffles. First shuffle gather the elements.
5017     // The second shuffle, which takes the first shuffle as both of its
5018     // vector operands, put the elements into the right order.
5019     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5020
5021     SmallVector<int, 8> Mask2(4U, -1);
5022
5023     for (unsigned i = 0; i != 4; ++i) {
5024       if (Locs[i].first == -1)
5025         continue;
5026       else {
5027         unsigned Idx = (i < 2) ? 0 : 4;
5028         Idx += Locs[i].first * 2 + Locs[i].second;
5029         Mask2[i] = Idx;
5030       }
5031     }
5032
5033     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5034   } else if (NumLo == 3 || NumHi == 3) {
5035     // Otherwise, we must have three elements from one vector, call it X, and
5036     // one element from the other, call it Y.  First, use a shufps to build an
5037     // intermediate vector with the one element from Y and the element from X
5038     // that will be in the same half in the final destination (the indexes don't
5039     // matter). Then, use a shufps to build the final vector, taking the half
5040     // containing the element from Y from the intermediate, and the other half
5041     // from X.
5042     if (NumHi == 3) {
5043       // Normalize it so the 3 elements come from V1.
5044       CommuteVectorShuffleMask(PermMask, VT);
5045       std::swap(V1, V2);
5046     }
5047
5048     // Find the element from V2.
5049     unsigned HiIndex;
5050     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5051       int Val = PermMask[HiIndex];
5052       if (Val < 0)
5053         continue;
5054       if (Val >= 4)
5055         break;
5056     }
5057
5058     Mask1[0] = PermMask[HiIndex];
5059     Mask1[1] = -1;
5060     Mask1[2] = PermMask[HiIndex^1];
5061     Mask1[3] = -1;
5062     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5063
5064     if (HiIndex >= 2) {
5065       Mask1[0] = PermMask[0];
5066       Mask1[1] = PermMask[1];
5067       Mask1[2] = HiIndex & 1 ? 6 : 4;
5068       Mask1[3] = HiIndex & 1 ? 4 : 6;
5069       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5070     } else {
5071       Mask1[0] = HiIndex & 1 ? 2 : 0;
5072       Mask1[1] = HiIndex & 1 ? 0 : 2;
5073       Mask1[2] = PermMask[2];
5074       Mask1[3] = PermMask[3];
5075       if (Mask1[2] >= 0)
5076         Mask1[2] += 4;
5077       if (Mask1[3] >= 0)
5078         Mask1[3] += 4;
5079       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5080     }
5081   }
5082
5083   // Break it into (shuffle shuffle_hi, shuffle_lo).
5084   Locs.clear();
5085   SmallVector<int,8> LoMask(4U, -1);
5086   SmallVector<int,8> HiMask(4U, -1);
5087
5088   SmallVector<int,8> *MaskPtr = &LoMask;
5089   unsigned MaskIdx = 0;
5090   unsigned LoIdx = 0;
5091   unsigned HiIdx = 2;
5092   for (unsigned i = 0; i != 4; ++i) {
5093     if (i == 2) {
5094       MaskPtr = &HiMask;
5095       MaskIdx = 1;
5096       LoIdx = 0;
5097       HiIdx = 2;
5098     }
5099     int Idx = PermMask[i];
5100     if (Idx < 0) {
5101       Locs[i] = std::make_pair(-1, -1);
5102     } else if (Idx < 4) {
5103       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5104       (*MaskPtr)[LoIdx] = Idx;
5105       LoIdx++;
5106     } else {
5107       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5108       (*MaskPtr)[HiIdx] = Idx;
5109       HiIdx++;
5110     }
5111   }
5112
5113   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5114   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5115   SmallVector<int, 8> MaskOps;
5116   for (unsigned i = 0; i != 4; ++i) {
5117     if (Locs[i].first == -1) {
5118       MaskOps.push_back(-1);
5119     } else {
5120       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5121       MaskOps.push_back(Idx);
5122     }
5123   }
5124   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5125 }
5126
5127 static bool MayFoldVectorLoad(SDValue V) {
5128   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5129     V = V.getOperand(0);
5130   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5131     V = V.getOperand(0);
5132   if (MayFoldLoad(V))
5133     return true;
5134   return false;
5135 }
5136
5137 // FIXME: the version above should always be used. Since there's
5138 // a bug where several vector shuffles can't be folded because the
5139 // DAG is not updated during lowering and a node claims to have two
5140 // uses while it only has one, use this version, and let isel match
5141 // another instruction if the load really happens to have more than
5142 // one use. Remove this version after this bug get fixed.
5143 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5144   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5145     V = V.getOperand(0);
5146   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5147     V = V.getOperand(0);
5148   if (ISD::isNormalLoad(V.getNode()))
5149     return true;
5150   return false;
5151 }
5152
5153 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5154 /// a vector extract, and if both can be later optimized into a single load.
5155 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5156 /// here because otherwise a target specific shuffle node is going to be
5157 /// emitted for this shuffle, and the optimization not done.
5158 /// FIXME: This is probably not the best approach, but fix the problem
5159 /// until the right path is decided.
5160 static
5161 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5162                                          const TargetLowering &TLI) {
5163   EVT VT = V.getValueType();
5164   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5165
5166   // Be sure that the vector shuffle is present in a pattern like this:
5167   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5168   if (!V.hasOneUse())
5169     return false;
5170
5171   SDNode *N = *V.getNode()->use_begin();
5172   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5173     return false;
5174
5175   SDValue EltNo = N->getOperand(1);
5176   if (!isa<ConstantSDNode>(EltNo))
5177     return false;
5178
5179   // If the bit convert changed the number of elements, it is unsafe
5180   // to examine the mask.
5181   bool HasShuffleIntoBitcast = false;
5182   if (V.getOpcode() == ISD::BIT_CONVERT) {
5183     EVT SrcVT = V.getOperand(0).getValueType();
5184     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5185       return false;
5186     V = V.getOperand(0);
5187     HasShuffleIntoBitcast = true;
5188   }
5189
5190   // Select the input vector, guarding against out of range extract vector.
5191   unsigned NumElems = VT.getVectorNumElements();
5192   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5193   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5194   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5195
5196   // Skip one more bit_convert if necessary
5197   if (V.getOpcode() == ISD::BIT_CONVERT)
5198     V = V.getOperand(0);
5199
5200   if (ISD::isNormalLoad(V.getNode())) {
5201     // Is the original load suitable?
5202     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5203
5204     // FIXME: avoid the multi-use bug that is preventing lots of
5205     // of foldings to be detected, this is still wrong of course, but
5206     // give the temporary desired behavior, and if it happens that
5207     // the load has real more uses, during isel it will not fold, and
5208     // will generate poor code.
5209     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5210       return false;
5211
5212     if (!HasShuffleIntoBitcast)
5213       return true;
5214
5215     // If there's a bitcast before the shuffle, check if the load type and
5216     // alignment is valid.
5217     unsigned Align = LN0->getAlignment();
5218     unsigned NewAlign =
5219       TLI.getTargetData()->getABITypeAlignment(
5220                                     VT.getTypeForEVT(*DAG.getContext()));
5221
5222     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5223       return false;
5224   }
5225
5226   return true;
5227 }
5228
5229 static
5230 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5231                         bool HasSSE2) {
5232   SDValue V1 = Op.getOperand(0);
5233   SDValue V2 = Op.getOperand(1);
5234   EVT VT = Op.getValueType();
5235
5236   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5237
5238   if (HasSSE2 && VT == MVT::v2f64)
5239     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5240
5241   // v4f32 or v4i32
5242   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5243 }
5244
5245 static
5246 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5247   SDValue V1 = Op.getOperand(0);
5248   SDValue V2 = Op.getOperand(1);
5249   EVT VT = Op.getValueType();
5250
5251   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5252          "unsupported shuffle type");
5253
5254   if (V2.getOpcode() == ISD::UNDEF)
5255     V2 = V1;
5256
5257   // v4i32 or v4f32
5258   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5259 }
5260
5261 static
5262 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5263   SDValue V1 = Op.getOperand(0);
5264   SDValue V2 = Op.getOperand(1);
5265   EVT VT = Op.getValueType();
5266   unsigned NumElems = VT.getVectorNumElements();
5267
5268   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5269   // operand of these instructions is only memory, so check if there's a
5270   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5271   // same masks.
5272   bool CanFoldLoad = false;
5273
5274   // Trivial case, when V2 comes from a load.
5275   if (MayFoldVectorLoad(V2))
5276     CanFoldLoad = true;
5277
5278   // When V1 is a load, it can be folded later into a store in isel, example:
5279   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5280   //    turns into:
5281   //  (MOVLPSmr addr:$src1, VR128:$src2)
5282   // So, recognize this potential and also use MOVLPS or MOVLPD
5283   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5284     CanFoldLoad = true;
5285
5286   if (CanFoldLoad) {
5287     if (HasSSE2 && NumElems == 2)
5288       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5289
5290     if (NumElems == 4)
5291       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5292   }
5293
5294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5295   // movl and movlp will both match v2i64, but v2i64 is never matched by
5296   // movl earlier because we make it strict to avoid messing with the movlp load
5297   // folding logic (see the code above getMOVLP call). Match it here then,
5298   // this is horrible, but will stay like this until we move all shuffle
5299   // matching to x86 specific nodes. Note that for the 1st condition all
5300   // types are matched with movsd.
5301   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5302     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5303   else if (HasSSE2)
5304     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5305
5306
5307   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5308
5309   // Invert the operand order and use SHUFPS to match it.
5310   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5311                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5312 }
5313
5314 static inline unsigned getUNPCKLOpcode(EVT VT) {
5315   switch(VT.getSimpleVT().SimpleTy) {
5316   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5317   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5318   case MVT::v4f32: return X86ISD::UNPCKLPS;
5319   case MVT::v2f64: return X86ISD::UNPCKLPD;
5320   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5321   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5322   default:
5323     llvm_unreachable("Unknow type for unpckl");
5324   }
5325   return 0;
5326 }
5327
5328 static inline unsigned getUNPCKHOpcode(EVT VT) {
5329   switch(VT.getSimpleVT().SimpleTy) {
5330   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5331   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5332   case MVT::v4f32: return X86ISD::UNPCKHPS;
5333   case MVT::v2f64: return X86ISD::UNPCKHPD;
5334   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5335   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5336   default:
5337     llvm_unreachable("Unknow type for unpckh");
5338   }
5339   return 0;
5340 }
5341
5342 static
5343 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5344                                const TargetLowering &TLI,
5345                                const X86Subtarget *Subtarget) {
5346   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5347   EVT VT = Op.getValueType();
5348   DebugLoc dl = Op.getDebugLoc();
5349   SDValue V1 = Op.getOperand(0);
5350   SDValue V2 = Op.getOperand(1);
5351
5352   if (isZeroShuffle(SVOp))
5353     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5354
5355   // Handle splat operations
5356   if (SVOp->isSplat()) {
5357     // Special case, this is the only place now where it's
5358     // allowed to return a vector_shuffle operation without
5359     // using a target specific node, because *hopefully* it
5360     // will be optimized away by the dag combiner.
5361     if (VT.getVectorNumElements() <= 4 &&
5362         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5363       return Op;
5364
5365     // Handle splats by matching through known masks
5366     if (VT.getVectorNumElements() <= 4)
5367       return SDValue();
5368
5369     // Canonize all of the remaining to v4f32.
5370     return PromoteSplat(SVOp, DAG);
5371   }
5372
5373   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5374   // do it!
5375   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5376     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5377     if (NewOp.getNode())
5378       return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5379   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5380     // FIXME: Figure out a cleaner way to do this.
5381     // Try to make use of movq to zero out the top part.
5382     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5383       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5384       if (NewOp.getNode()) {
5385         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5386           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5387                               DAG, Subtarget, dl);
5388       }
5389     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5390       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5391       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5392         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5393                             DAG, Subtarget, dl);
5394     }
5395   }
5396   return SDValue();
5397 }
5398
5399 SDValue
5400 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5401   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5402   SDValue V1 = Op.getOperand(0);
5403   SDValue V2 = Op.getOperand(1);
5404   EVT VT = Op.getValueType();
5405   DebugLoc dl = Op.getDebugLoc();
5406   unsigned NumElems = VT.getVectorNumElements();
5407   bool isMMX = VT.getSizeInBits() == 64;
5408   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5409   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5410   bool V1IsSplat = false;
5411   bool V2IsSplat = false;
5412   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5413   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5414   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5415   MachineFunction &MF = DAG.getMachineFunction();
5416   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5417
5418   // FIXME: this is somehow handled during isel by MMX pattern fragments. Remove
5419   // the check or come up with another solution when all MMX move to intrinsics,
5420   // but don't allow this to be considered legal, we don't want vector_shuffle
5421   // operations to be matched during isel anymore.
5422   if (isMMX && SVOp->isSplat())
5423     return Op;
5424
5425   // Vector shuffle lowering takes 3 steps:
5426   //
5427   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5428   //    narrowing and commutation of operands should be handled.
5429   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5430   //    shuffle nodes.
5431   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5432   //    so the shuffle can be broken into other shuffles and the legalizer can
5433   //    try the lowering again.
5434   //
5435   // The general ideia is that no vector_shuffle operation should be left to
5436   // be matched during isel, all of them must be converted to a target specific
5437   // node here.
5438
5439   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5440   // narrowing and commutation of operands should be handled. The actual code
5441   // doesn't include all of those, work in progress...
5442   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5443   if (NewOp.getNode())
5444     return NewOp;
5445
5446   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5447   // unpckh_undef). Only use pshufd if speed is more important than size.
5448   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5449     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5450       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5451   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5452     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5453       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5454
5455   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5456       RelaxedMayFoldVectorLoad(V1) && !isMMX)
5457     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
5458
5459   if (!isMMX && X86::isMOVHLPS_v_undef_Mask(SVOp))
5460     return getMOVHighToLow(Op, dl, DAG);
5461
5462   // Use to match splats
5463   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5464       (VT == MVT::v2f64 || VT == MVT::v2i64))
5465     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5466
5467   if (X86::isPSHUFDMask(SVOp)) {
5468     // The actual implementation will match the mask in the if above and then
5469     // during isel it can match several different instructions, not only pshufd
5470     // as its name says, sad but true, emulate the behavior for now...
5471     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5472         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5473
5474     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5475
5476     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5477       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5478
5479     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5480       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5481                                   TargetMask, DAG);
5482
5483     if (VT == MVT::v4f32)
5484       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5485                                   TargetMask, DAG);
5486   }
5487
5488   // Check if this can be converted into a logical shift.
5489   bool isLeft = false;
5490   unsigned ShAmt = 0;
5491   SDValue ShVal;
5492   bool isShift = getSubtarget()->hasSSE2() &&
5493     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5494   if (isShift && ShVal.hasOneUse()) {
5495     // If the shifted value has multiple uses, it may be cheaper to use
5496     // v_set0 + movlhps or movhlps, etc.
5497     EVT EltVT = VT.getVectorElementType();
5498     ShAmt *= EltVT.getSizeInBits();
5499     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5500   }
5501
5502   if (X86::isMOVLMask(SVOp)) {
5503     if (V1IsUndef)
5504       return V2;
5505     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5506       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5507     if (!isMMX && !X86::isMOVLPMask(SVOp)) {
5508       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5509         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5510
5511       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5512         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5513     }
5514   }
5515
5516   // FIXME: fold these into legal mask.
5517   if (!isMMX) {
5518     if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5519       return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5520
5521     if (X86::isMOVHLPSMask(SVOp))
5522       return getMOVHighToLow(Op, dl, DAG);
5523
5524     if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5525       return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5526
5527     if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5528       return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5529
5530     if (X86::isMOVLPMask(SVOp))
5531       return getMOVLP(Op, dl, DAG, HasSSE2);
5532   }
5533
5534   if (ShouldXformToMOVHLPS(SVOp) ||
5535       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5536     return CommuteVectorShuffle(SVOp, DAG);
5537
5538   if (isShift) {
5539     // No better options. Use a vshl / vsrl.
5540     EVT EltVT = VT.getVectorElementType();
5541     ShAmt *= EltVT.getSizeInBits();
5542     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5543   }
5544
5545   bool Commuted = false;
5546   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5547   // 1,1,1,1 -> v8i16 though.
5548   V1IsSplat = isSplatVector(V1.getNode());
5549   V2IsSplat = isSplatVector(V2.getNode());
5550
5551   // Canonicalize the splat or undef, if present, to be on the RHS.
5552   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5553     Op = CommuteVectorShuffle(SVOp, DAG);
5554     SVOp = cast<ShuffleVectorSDNode>(Op);
5555     V1 = SVOp->getOperand(0);
5556     V2 = SVOp->getOperand(1);
5557     std::swap(V1IsSplat, V2IsSplat);
5558     std::swap(V1IsUndef, V2IsUndef);
5559     Commuted = true;
5560   }
5561
5562   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5563     // Shuffling low element of v1 into undef, just return v1.
5564     if (V2IsUndef)
5565       return V1;
5566     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5567     // the instruction selector will not match, so get a canonical MOVL with
5568     // swapped operands to undo the commute.
5569     return getMOVL(DAG, dl, VT, V2, V1);
5570   }
5571
5572   if (X86::isUNPCKLMask(SVOp))
5573     return (isMMX) ?
5574       Op : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5575
5576   if (X86::isUNPCKHMask(SVOp))
5577     return (isMMX) ?
5578       Op : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5579
5580   if (V2IsSplat) {
5581     // Normalize mask so all entries that point to V2 points to its first
5582     // element then try to match unpck{h|l} again. If match, return a
5583     // new vector_shuffle with the corrected mask.
5584     SDValue NewMask = NormalizeMask(SVOp, DAG);
5585     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5586     if (NSVOp != SVOp) {
5587       if (X86::isUNPCKLMask(NSVOp, true)) {
5588         return NewMask;
5589       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5590         return NewMask;
5591       }
5592     }
5593   }
5594
5595   if (Commuted) {
5596     // Commute is back and try unpck* again.
5597     // FIXME: this seems wrong.
5598     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5599     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5600
5601     if (X86::isUNPCKLMask(NewSVOp))
5602       return (isMMX) ?
5603         NewOp : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5604
5605     if (X86::isUNPCKHMask(NewSVOp))
5606       return (isMMX) ?
5607         NewOp : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5608   }
5609
5610   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
5611
5612   // Normalize the node to match x86 shuffle ops if needed
5613   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5614     return CommuteVectorShuffle(SVOp, DAG);
5615
5616   // The checks below are all present in isShuffleMaskLegal, but they are
5617   // inlined here right now to enable us to directly emit target specific
5618   // nodes, and remove one by one until they don't return Op anymore.
5619   SmallVector<int, 16> M;
5620   SVOp->getMask(M);
5621
5622   if (isPALIGNRMask(M, VT, HasSSSE3))
5623     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5624                                 X86::getShufflePALIGNRImmediate(SVOp),
5625                                 DAG);
5626
5627   // Only a few shuffle masks are handled for 64-bit vectors (MMX), and
5628   // 64-bit vectors which made to this point can't be handled, they are
5629   // expanded.
5630   if (isMMX)
5631     return SDValue();
5632
5633   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5634       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5635     if (VT == MVT::v2f64)
5636       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5637     if (VT == MVT::v2i64)
5638       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5639   }
5640
5641   if (isPSHUFHWMask(M, VT))
5642     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5643                                 X86::getShufflePSHUFHWImmediate(SVOp),
5644                                 DAG);
5645
5646   if (isPSHUFLWMask(M, VT))
5647     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5648                                 X86::getShufflePSHUFLWImmediate(SVOp),
5649                                 DAG);
5650
5651   if (isSHUFPMask(M, VT)) {
5652     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5653     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5654       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5655                                   TargetMask, DAG);
5656     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5657       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5658                                   TargetMask, DAG);
5659   }
5660
5661   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5662     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5663       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5664   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5665     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5666       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5667
5668   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5669   if (VT == MVT::v8i16) {
5670     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5671     if (NewOp.getNode())
5672       return NewOp;
5673   }
5674
5675   if (VT == MVT::v16i8) {
5676     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5677     if (NewOp.getNode())
5678       return NewOp;
5679   }
5680
5681   // Handle all 4 wide cases with a number of shuffles except for MMX.
5682   if (NumElems == 4 && !isMMX)
5683     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5684
5685   return SDValue();
5686 }
5687
5688 SDValue
5689 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5690                                                 SelectionDAG &DAG) const {
5691   EVT VT = Op.getValueType();
5692   DebugLoc dl = Op.getDebugLoc();
5693   if (VT.getSizeInBits() == 8) {
5694     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5695                                     Op.getOperand(0), Op.getOperand(1));
5696     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5697                                     DAG.getValueType(VT));
5698     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5699   } else if (VT.getSizeInBits() == 16) {
5700     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5701     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5702     if (Idx == 0)
5703       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5704                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5705                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5706                                                  MVT::v4i32,
5707                                                  Op.getOperand(0)),
5708                                      Op.getOperand(1)));
5709     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5710                                     Op.getOperand(0), Op.getOperand(1));
5711     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5712                                     DAG.getValueType(VT));
5713     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5714   } else if (VT == MVT::f32) {
5715     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5716     // the result back to FR32 register. It's only worth matching if the
5717     // result has a single use which is a store or a bitcast to i32.  And in
5718     // the case of a store, it's not worth it if the index is a constant 0,
5719     // because a MOVSSmr can be used instead, which is smaller and faster.
5720     if (!Op.hasOneUse())
5721       return SDValue();
5722     SDNode *User = *Op.getNode()->use_begin();
5723     if ((User->getOpcode() != ISD::STORE ||
5724          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5725           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5726         (User->getOpcode() != ISD::BIT_CONVERT ||
5727          User->getValueType(0) != MVT::i32))
5728       return SDValue();
5729     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5730                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5731                                               Op.getOperand(0)),
5732                                               Op.getOperand(1));
5733     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5734   } else if (VT == MVT::i32) {
5735     // ExtractPS works with constant index.
5736     if (isa<ConstantSDNode>(Op.getOperand(1)))
5737       return Op;
5738   }
5739   return SDValue();
5740 }
5741
5742
5743 SDValue
5744 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5745                                            SelectionDAG &DAG) const {
5746   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5747     return SDValue();
5748
5749   if (Subtarget->hasSSE41()) {
5750     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5751     if (Res.getNode())
5752       return Res;
5753   }
5754
5755   EVT VT = Op.getValueType();
5756   DebugLoc dl = Op.getDebugLoc();
5757   // TODO: handle v16i8.
5758   if (VT.getSizeInBits() == 16) {
5759     SDValue Vec = Op.getOperand(0);
5760     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5761     if (Idx == 0)
5762       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5763                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5764                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5765                                                  MVT::v4i32, Vec),
5766                                      Op.getOperand(1)));
5767     // Transform it so it match pextrw which produces a 32-bit result.
5768     EVT EltVT = MVT::i32;
5769     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5770                                     Op.getOperand(0), Op.getOperand(1));
5771     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5772                                     DAG.getValueType(VT));
5773     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5774   } else if (VT.getSizeInBits() == 32) {
5775     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5776     if (Idx == 0)
5777       return Op;
5778
5779     // SHUFPS the element to the lowest double word, then movss.
5780     int Mask[4] = { Idx, -1, -1, -1 };
5781     EVT VVT = Op.getOperand(0).getValueType();
5782     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5783                                        DAG.getUNDEF(VVT), Mask);
5784     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5785                        DAG.getIntPtrConstant(0));
5786   } else if (VT.getSizeInBits() == 64) {
5787     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5788     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5789     //        to match extract_elt for f64.
5790     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5791     if (Idx == 0)
5792       return Op;
5793
5794     // UNPCKHPD the element to the lowest double word, then movsd.
5795     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5796     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5797     int Mask[2] = { 1, -1 };
5798     EVT VVT = Op.getOperand(0).getValueType();
5799     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5800                                        DAG.getUNDEF(VVT), Mask);
5801     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5802                        DAG.getIntPtrConstant(0));
5803   }
5804
5805   return SDValue();
5806 }
5807
5808 SDValue
5809 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5810                                                SelectionDAG &DAG) const {
5811   EVT VT = Op.getValueType();
5812   EVT EltVT = VT.getVectorElementType();
5813   DebugLoc dl = Op.getDebugLoc();
5814
5815   SDValue N0 = Op.getOperand(0);
5816   SDValue N1 = Op.getOperand(1);
5817   SDValue N2 = Op.getOperand(2);
5818
5819   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5820       isa<ConstantSDNode>(N2)) {
5821     unsigned Opc;
5822     if (VT == MVT::v8i16)
5823       Opc = X86ISD::PINSRW;
5824     else if (VT == MVT::v4i16)
5825       Opc = X86ISD::MMX_PINSRW;
5826     else if (VT == MVT::v16i8)
5827       Opc = X86ISD::PINSRB;
5828     else
5829       Opc = X86ISD::PINSRB;
5830
5831     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5832     // argument.
5833     if (N1.getValueType() != MVT::i32)
5834       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5835     if (N2.getValueType() != MVT::i32)
5836       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5837     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5838   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5839     // Bits [7:6] of the constant are the source select.  This will always be
5840     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5841     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5842     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5843     // Bits [5:4] of the constant are the destination select.  This is the
5844     //  value of the incoming immediate.
5845     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5846     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5847     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5848     // Create this as a scalar to vector..
5849     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5850     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5851   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5852     // PINSR* works with constant index.
5853     return Op;
5854   }
5855   return SDValue();
5856 }
5857
5858 SDValue
5859 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5860   EVT VT = Op.getValueType();
5861   EVT EltVT = VT.getVectorElementType();
5862
5863   if (Subtarget->hasSSE41())
5864     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5865
5866   if (EltVT == MVT::i8)
5867     return SDValue();
5868
5869   DebugLoc dl = Op.getDebugLoc();
5870   SDValue N0 = Op.getOperand(0);
5871   SDValue N1 = Op.getOperand(1);
5872   SDValue N2 = Op.getOperand(2);
5873
5874   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5875     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5876     // as its second argument.
5877     if (N1.getValueType() != MVT::i32)
5878       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5879     if (N2.getValueType() != MVT::i32)
5880       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5881     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5882                        dl, VT, N0, N1, N2);
5883   }
5884   return SDValue();
5885 }
5886
5887 SDValue
5888 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5889   DebugLoc dl = Op.getDebugLoc();
5890   
5891   if (Op.getValueType() == MVT::v1i64 &&
5892       Op.getOperand(0).getValueType() == MVT::i64)
5893     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5894
5895   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5896   EVT VT = MVT::v2i32;
5897   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5898   default: break;
5899   case MVT::v16i8:
5900   case MVT::v8i16:
5901     VT = MVT::v4i32;
5902     break;
5903   }
5904   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5905                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5906 }
5907
5908 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5909 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5910 // one of the above mentioned nodes. It has to be wrapped because otherwise
5911 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5912 // be used to form addressing mode. These wrapped nodes will be selected
5913 // into MOV32ri.
5914 SDValue
5915 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5916   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
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.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5933                                              CP->getAlignment(),
5934                                              CP->getOffset(), OpFlag);
5935   DebugLoc DL = CP->getDebugLoc();
5936   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5937   // With PIC, the address is actually $g + Offset.
5938   if (OpFlag) {
5939     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5940                          DAG.getNode(X86ISD::GlobalBaseReg,
5941                                      DebugLoc(), getPointerTy()),
5942                          Result);
5943   }
5944
5945   return Result;
5946 }
5947
5948 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5949   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5950
5951   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5952   // global base reg.
5953   unsigned char OpFlag = 0;
5954   unsigned WrapperKind = X86ISD::Wrapper;
5955   CodeModel::Model M = getTargetMachine().getCodeModel();
5956
5957   if (Subtarget->isPICStyleRIPRel() &&
5958       (M == CodeModel::Small || M == CodeModel::Kernel))
5959     WrapperKind = X86ISD::WrapperRIP;
5960   else if (Subtarget->isPICStyleGOT())
5961     OpFlag = X86II::MO_GOTOFF;
5962   else if (Subtarget->isPICStyleStubPIC())
5963     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5964
5965   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5966                                           OpFlag);
5967   DebugLoc DL = JT->getDebugLoc();
5968   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5969
5970   // With PIC, the address is actually $g + Offset.
5971   if (OpFlag) {
5972     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5973                          DAG.getNode(X86ISD::GlobalBaseReg,
5974                                      DebugLoc(), getPointerTy()),
5975                          Result);
5976   }
5977
5978   return Result;
5979 }
5980
5981 SDValue
5982 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5983   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5984
5985   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5986   // global base reg.
5987   unsigned char OpFlag = 0;
5988   unsigned WrapperKind = X86ISD::Wrapper;
5989   CodeModel::Model M = getTargetMachine().getCodeModel();
5990
5991   if (Subtarget->isPICStyleRIPRel() &&
5992       (M == CodeModel::Small || M == CodeModel::Kernel))
5993     WrapperKind = X86ISD::WrapperRIP;
5994   else if (Subtarget->isPICStyleGOT())
5995     OpFlag = X86II::MO_GOTOFF;
5996   else if (Subtarget->isPICStyleStubPIC())
5997     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5998
5999   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6000
6001   DebugLoc DL = Op.getDebugLoc();
6002   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6003
6004
6005   // With PIC, the address is actually $g + Offset.
6006   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6007       !Subtarget->is64Bit()) {
6008     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6009                          DAG.getNode(X86ISD::GlobalBaseReg,
6010                                      DebugLoc(), getPointerTy()),
6011                          Result);
6012   }
6013
6014   return Result;
6015 }
6016
6017 SDValue
6018 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6019   // Create the TargetBlockAddressAddress node.
6020   unsigned char OpFlags =
6021     Subtarget->ClassifyBlockAddressReference();
6022   CodeModel::Model M = getTargetMachine().getCodeModel();
6023   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6024   DebugLoc dl = Op.getDebugLoc();
6025   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6026                                        /*isTarget=*/true, OpFlags);
6027
6028   if (Subtarget->isPICStyleRIPRel() &&
6029       (M == CodeModel::Small || M == CodeModel::Kernel))
6030     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6031   else
6032     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6033
6034   // With PIC, the address is actually $g + Offset.
6035   if (isGlobalRelativeToPICBase(OpFlags)) {
6036     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6037                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6038                          Result);
6039   }
6040
6041   return Result;
6042 }
6043
6044 SDValue
6045 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6046                                       int64_t Offset,
6047                                       SelectionDAG &DAG) const {
6048   // Create the TargetGlobalAddress node, folding in the constant
6049   // offset if it is legal.
6050   unsigned char OpFlags =
6051     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6052   CodeModel::Model M = getTargetMachine().getCodeModel();
6053   SDValue Result;
6054   if (OpFlags == X86II::MO_NO_FLAG &&
6055       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6056     // A direct static reference to a global.
6057     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6058     Offset = 0;
6059   } else {
6060     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6061   }
6062
6063   if (Subtarget->isPICStyleRIPRel() &&
6064       (M == CodeModel::Small || M == CodeModel::Kernel))
6065     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6066   else
6067     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6068
6069   // With PIC, the address is actually $g + Offset.
6070   if (isGlobalRelativeToPICBase(OpFlags)) {
6071     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6072                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6073                          Result);
6074   }
6075
6076   // For globals that require a load from a stub to get the address, emit the
6077   // load.
6078   if (isGlobalStubReference(OpFlags))
6079     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6080                          MachinePointerInfo::getGOT(), false, false, 0);
6081
6082   // If there was a non-zero offset that we didn't fold, create an explicit
6083   // addition for it.
6084   if (Offset != 0)
6085     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6086                          DAG.getConstant(Offset, getPointerTy()));
6087
6088   return Result;
6089 }
6090
6091 SDValue
6092 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6093   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6094   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6095   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6096 }
6097
6098 static SDValue
6099 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6100            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6101            unsigned char OperandFlags) {
6102   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6103   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6104   DebugLoc dl = GA->getDebugLoc();
6105   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6106                                            GA->getValueType(0),
6107                                            GA->getOffset(),
6108                                            OperandFlags);
6109   if (InFlag) {
6110     SDValue Ops[] = { Chain,  TGA, *InFlag };
6111     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6112   } else {
6113     SDValue Ops[]  = { Chain, TGA };
6114     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6115   }
6116
6117   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6118   MFI->setAdjustsStack(true);
6119
6120   SDValue Flag = Chain.getValue(1);
6121   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6122 }
6123
6124 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6125 static SDValue
6126 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6127                                 const EVT PtrVT) {
6128   SDValue InFlag;
6129   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6130   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6131                                      DAG.getNode(X86ISD::GlobalBaseReg,
6132                                                  DebugLoc(), PtrVT), InFlag);
6133   InFlag = Chain.getValue(1);
6134
6135   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6136 }
6137
6138 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6139 static SDValue
6140 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6141                                 const EVT PtrVT) {
6142   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6143                     X86::RAX, X86II::MO_TLSGD);
6144 }
6145
6146 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6147 // "local exec" model.
6148 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6149                                    const EVT PtrVT, TLSModel::Model model,
6150                                    bool is64Bit) {
6151   DebugLoc dl = GA->getDebugLoc();
6152   // Get the Thread Pointer
6153   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
6154                              DebugLoc(), PtrVT,
6155                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
6156                                              MVT::i32));
6157
6158   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
6159                                       MachinePointerInfo(), false, false, 0);
6160
6161   unsigned char OperandFlags = 0;
6162   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6163   // initialexec.
6164   unsigned WrapperKind = X86ISD::Wrapper;
6165   if (model == TLSModel::LocalExec) {
6166     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6167   } else if (is64Bit) {
6168     assert(model == TLSModel::InitialExec);
6169     OperandFlags = X86II::MO_GOTTPOFF;
6170     WrapperKind = X86ISD::WrapperRIP;
6171   } else {
6172     assert(model == TLSModel::InitialExec);
6173     OperandFlags = X86II::MO_INDNTPOFF;
6174   }
6175
6176   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6177   // exec)
6178   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 
6179                                            GA->getValueType(0),
6180                                            GA->getOffset(), OperandFlags);
6181   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6182
6183   if (model == TLSModel::InitialExec)
6184     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6185                          MachinePointerInfo::getGOT(), false, false, 0);
6186
6187   // The address of the thread local variable is the add of the thread
6188   // pointer with the offset of the variable.
6189   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6190 }
6191
6192 SDValue
6193 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6194   
6195   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6196   const GlobalValue *GV = GA->getGlobal();
6197
6198   if (Subtarget->isTargetELF()) {
6199     // TODO: implement the "local dynamic" model
6200     // TODO: implement the "initial exec"model for pic executables
6201     
6202     // If GV is an alias then use the aliasee for determining
6203     // thread-localness.
6204     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6205       GV = GA->resolveAliasedGlobal(false);
6206     
6207     TLSModel::Model model 
6208       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6209     
6210     switch (model) {
6211       case TLSModel::GeneralDynamic:
6212       case TLSModel::LocalDynamic: // not implemented
6213         if (Subtarget->is64Bit())
6214           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6215         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6216         
6217       case TLSModel::InitialExec:
6218       case TLSModel::LocalExec:
6219         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6220                                    Subtarget->is64Bit());
6221     }
6222   } else if (Subtarget->isTargetDarwin()) {
6223     // Darwin only has one model of TLS.  Lower to that.
6224     unsigned char OpFlag = 0;
6225     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6226                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6227     
6228     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6229     // global base reg.
6230     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6231                   !Subtarget->is64Bit();
6232     if (PIC32)
6233       OpFlag = X86II::MO_TLVP_PIC_BASE;
6234     else
6235       OpFlag = X86II::MO_TLVP;
6236     DebugLoc DL = Op.getDebugLoc();    
6237     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6238                                                 getPointerTy(),
6239                                                 GA->getOffset(), OpFlag);
6240     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6241   
6242     // With PIC32, the address is actually $g + Offset.
6243     if (PIC32)
6244       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6245                            DAG.getNode(X86ISD::GlobalBaseReg,
6246                                        DebugLoc(), getPointerTy()),
6247                            Offset);
6248     
6249     // Lowering the machine isd will make sure everything is in the right
6250     // location.
6251     SDValue Args[] = { Offset };
6252     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6253     
6254     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6255     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6256     MFI->setAdjustsStack(true);
6257
6258     // And our return value (tls address) is in the standard call return value
6259     // location.
6260     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6261     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6262   }
6263   
6264   assert(false &&
6265          "TLS not implemented for this target.");
6266
6267   llvm_unreachable("Unreachable");
6268   return SDValue();
6269 }
6270
6271
6272 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6273 /// take a 2 x i32 value to shift plus a shift amount.
6274 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6275   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6276   EVT VT = Op.getValueType();
6277   unsigned VTBits = VT.getSizeInBits();
6278   DebugLoc dl = Op.getDebugLoc();
6279   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6280   SDValue ShOpLo = Op.getOperand(0);
6281   SDValue ShOpHi = Op.getOperand(1);
6282   SDValue ShAmt  = Op.getOperand(2);
6283   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6284                                      DAG.getConstant(VTBits - 1, MVT::i8))
6285                        : DAG.getConstant(0, VT);
6286
6287   SDValue Tmp2, Tmp3;
6288   if (Op.getOpcode() == ISD::SHL_PARTS) {
6289     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6290     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6291   } else {
6292     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6293     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6294   }
6295
6296   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6297                                 DAG.getConstant(VTBits, MVT::i8));
6298   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6299                              AndNode, DAG.getConstant(0, MVT::i8));
6300
6301   SDValue Hi, Lo;
6302   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6303   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6304   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6305
6306   if (Op.getOpcode() == ISD::SHL_PARTS) {
6307     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6308     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6309   } else {
6310     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6311     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6312   }
6313
6314   SDValue Ops[2] = { Lo, Hi };
6315   return DAG.getMergeValues(Ops, 2, dl);
6316 }
6317
6318 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6319                                            SelectionDAG &DAG) const {
6320   EVT SrcVT = Op.getOperand(0).getValueType();
6321
6322   if (SrcVT.isVector()) {
6323     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
6324       return Op;
6325     }
6326     return SDValue();
6327   }
6328
6329   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6330          "Unknown SINT_TO_FP to lower!");
6331
6332   // These are really Legal; return the operand so the caller accepts it as
6333   // Legal.
6334   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6335     return Op;
6336   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6337       Subtarget->is64Bit()) {
6338     return Op;
6339   }
6340
6341   DebugLoc dl = Op.getDebugLoc();
6342   unsigned Size = SrcVT.getSizeInBits()/8;
6343   MachineFunction &MF = DAG.getMachineFunction();
6344   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6345   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6346   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6347                                StackSlot,
6348                                MachinePointerInfo::getFixedStack(SSFI),
6349                                false, false, 0);
6350   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6351 }
6352
6353 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6354                                      SDValue StackSlot, 
6355                                      SelectionDAG &DAG) const {
6356   // Build the FILD
6357   DebugLoc dl = Op.getDebugLoc();
6358   SDVTList Tys;
6359   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6360   if (useSSE)
6361     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6362   else
6363     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6364   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6365   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
6366                                Tys, Ops, array_lengthof(Ops));
6367
6368   if (useSSE) {
6369     Chain = Result.getValue(1);
6370     SDValue InFlag = Result.getValue(2);
6371
6372     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6373     // shouldn't be necessary except that RFP cannot be live across
6374     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6375     MachineFunction &MF = DAG.getMachineFunction();
6376     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6377     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6378     Tys = DAG.getVTList(MVT::Other);
6379     SDValue Ops[] = {
6380       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6381     };
6382     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
6383     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
6384                          MachinePointerInfo::getFixedStack(SSFI),
6385                          false, false, 0);
6386   }
6387
6388   return Result;
6389 }
6390
6391 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6392 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6393                                                SelectionDAG &DAG) const {
6394   // This algorithm is not obvious. Here it is in C code, more or less:
6395   /*
6396     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6397       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6398       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6399
6400       // Copy ints to xmm registers.
6401       __m128i xh = _mm_cvtsi32_si128( hi );
6402       __m128i xl = _mm_cvtsi32_si128( lo );
6403
6404       // Combine into low half of a single xmm register.
6405       __m128i x = _mm_unpacklo_epi32( xh, xl );
6406       __m128d d;
6407       double sd;
6408
6409       // Merge in appropriate exponents to give the integer bits the right
6410       // magnitude.
6411       x = _mm_unpacklo_epi32( x, exp );
6412
6413       // Subtract away the biases to deal with the IEEE-754 double precision
6414       // implicit 1.
6415       d = _mm_sub_pd( (__m128d) x, bias );
6416
6417       // All conversions up to here are exact. The correctly rounded result is
6418       // calculated using the current rounding mode using the following
6419       // horizontal add.
6420       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6421       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6422                                 // store doesn't really need to be here (except
6423                                 // maybe to zero the other double)
6424       return sd;
6425     }
6426   */
6427
6428   DebugLoc dl = Op.getDebugLoc();
6429   LLVMContext *Context = DAG.getContext();
6430
6431   // Build some magic constants.
6432   std::vector<Constant*> CV0;
6433   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6434   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6435   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6436   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6437   Constant *C0 = ConstantVector::get(CV0);
6438   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6439
6440   std::vector<Constant*> CV1;
6441   CV1.push_back(
6442     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6443   CV1.push_back(
6444     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6445   Constant *C1 = ConstantVector::get(CV1);
6446   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6447
6448   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6449                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6450                                         Op.getOperand(0),
6451                                         DAG.getIntPtrConstant(1)));
6452   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6453                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6454                                         Op.getOperand(0),
6455                                         DAG.getIntPtrConstant(0)));
6456   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6457   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6458                               MachinePointerInfo::getConstantPool(),
6459                               false, false, 16);
6460   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6461   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6462   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6463                               MachinePointerInfo::getConstantPool(),
6464                               false, false, 16);
6465   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6466
6467   // Add the halves; easiest way is to swap them into another reg first.
6468   int ShufMask[2] = { 1, -1 };
6469   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6470                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6471   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6472   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6473                      DAG.getIntPtrConstant(0));
6474 }
6475
6476 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6477 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6478                                                SelectionDAG &DAG) const {
6479   DebugLoc dl = Op.getDebugLoc();
6480   // FP constant to bias correct the final result.
6481   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6482                                    MVT::f64);
6483
6484   // Load the 32-bit value into an XMM register.
6485   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6486                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6487                                          Op.getOperand(0),
6488                                          DAG.getIntPtrConstant(0)));
6489
6490   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6491                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6492                      DAG.getIntPtrConstant(0));
6493
6494   // Or the load with the bias.
6495   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6496                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6497                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6498                                                    MVT::v2f64, Load)),
6499                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6500                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6501                                                    MVT::v2f64, Bias)));
6502   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6503                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6504                    DAG.getIntPtrConstant(0));
6505
6506   // Subtract the bias.
6507   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6508
6509   // Handle final rounding.
6510   EVT DestVT = Op.getValueType();
6511
6512   if (DestVT.bitsLT(MVT::f64)) {
6513     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6514                        DAG.getIntPtrConstant(0));
6515   } else if (DestVT.bitsGT(MVT::f64)) {
6516     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6517   }
6518
6519   // Handle final rounding.
6520   return Sub;
6521 }
6522
6523 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6524                                            SelectionDAG &DAG) const {
6525   SDValue N0 = Op.getOperand(0);
6526   DebugLoc dl = Op.getDebugLoc();
6527
6528   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6529   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6530   // the optimization here.
6531   if (DAG.SignBitIsZero(N0))
6532     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6533
6534   EVT SrcVT = N0.getValueType();
6535   EVT DstVT = Op.getValueType();
6536   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6537     return LowerUINT_TO_FP_i64(Op, DAG);
6538   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6539     return LowerUINT_TO_FP_i32(Op, DAG);
6540
6541   // Make a 64-bit buffer, and use it to build an FILD.
6542   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6543   if (SrcVT == MVT::i32) {
6544     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6545     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6546                                      getPointerTy(), StackSlot, WordOff);
6547     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6548                                   StackSlot, MachinePointerInfo(),
6549                                   false, false, 0);
6550     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6551                                   OffsetSlot, MachinePointerInfo(),
6552                                   false, false, 0);
6553     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6554     return Fild;
6555   }
6556
6557   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6558   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6559                                 StackSlot, MachinePointerInfo(),
6560                                false, false, 0);
6561   // For i64 source, we need to add the appropriate power of 2 if the input
6562   // was negative.  This is the same as the optimization in
6563   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6564   // we must be careful to do the computation in x87 extended precision, not
6565   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6566   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6567   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6568   SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
6569
6570   APInt FF(32, 0x5F800000ULL);
6571
6572   // Check whether the sign bit is set.
6573   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6574                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6575                                  ISD::SETLT);
6576
6577   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6578   SDValue FudgePtr = DAG.getConstantPool(
6579                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6580                                          getPointerTy());
6581
6582   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6583   SDValue Zero = DAG.getIntPtrConstant(0);
6584   SDValue Four = DAG.getIntPtrConstant(4);
6585   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6586                                Zero, Four);
6587   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6588
6589   // Load the value out, extending it from f32 to f80.
6590   // FIXME: Avoid the extend by constructing the right constant pool?
6591   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6592                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6593                                  MVT::f32, false, false, 4);
6594   // Extend everything to 80 bits to force it to be done on x87.
6595   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6596   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6597 }
6598
6599 std::pair<SDValue,SDValue> X86TargetLowering::
6600 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6601   DebugLoc dl = Op.getDebugLoc();
6602
6603   EVT DstTy = Op.getValueType();
6604
6605   if (!IsSigned) {
6606     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6607     DstTy = MVT::i64;
6608   }
6609
6610   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6611          DstTy.getSimpleVT() >= MVT::i16 &&
6612          "Unknown FP_TO_SINT to lower!");
6613
6614   // These are really Legal.
6615   if (DstTy == MVT::i32 &&
6616       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6617     return std::make_pair(SDValue(), SDValue());
6618   if (Subtarget->is64Bit() &&
6619       DstTy == MVT::i64 &&
6620       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6621     return std::make_pair(SDValue(), SDValue());
6622
6623   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6624   // stack slot.
6625   MachineFunction &MF = DAG.getMachineFunction();
6626   unsigned MemSize = DstTy.getSizeInBits()/8;
6627   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6628   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6629
6630   unsigned Opc;
6631   switch (DstTy.getSimpleVT().SimpleTy) {
6632   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6633   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6634   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6635   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6636   }
6637
6638   SDValue Chain = DAG.getEntryNode();
6639   SDValue Value = Op.getOperand(0);
6640   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
6641     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6642     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
6643                          MachinePointerInfo::getFixedStack(SSFI),
6644                          false, false, 0);
6645     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6646     SDValue Ops[] = {
6647       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
6648     };
6649     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
6650     Chain = Value.getValue(1);
6651     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6652     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6653   }
6654
6655   // Build the FP_TO_INT*_IN_MEM
6656   SDValue Ops[] = { Chain, Value, StackSlot };
6657   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
6658
6659   return std::make_pair(FIST, StackSlot);
6660 }
6661
6662 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6663                                            SelectionDAG &DAG) const {
6664   if (Op.getValueType().isVector()) {
6665     if (Op.getValueType() == MVT::v2i32 &&
6666         Op.getOperand(0).getValueType() == MVT::v2f64) {
6667       return Op;
6668     }
6669     return SDValue();
6670   }
6671
6672   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6673   SDValue FIST = Vals.first, StackSlot = Vals.second;
6674   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6675   if (FIST.getNode() == 0) return Op;
6676
6677   // Load the result.
6678   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6679                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6680 }
6681
6682 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6683                                            SelectionDAG &DAG) const {
6684   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6685   SDValue FIST = Vals.first, StackSlot = Vals.second;
6686   assert(FIST.getNode() && "Unexpected failure");
6687
6688   // Load the result.
6689   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6690                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6691 }
6692
6693 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6694                                      SelectionDAG &DAG) const {
6695   LLVMContext *Context = DAG.getContext();
6696   DebugLoc dl = Op.getDebugLoc();
6697   EVT VT = Op.getValueType();
6698   EVT EltVT = VT;
6699   if (VT.isVector())
6700     EltVT = VT.getVectorElementType();
6701   std::vector<Constant*> CV;
6702   if (EltVT == MVT::f64) {
6703     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6704     CV.push_back(C);
6705     CV.push_back(C);
6706   } else {
6707     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6708     CV.push_back(C);
6709     CV.push_back(C);
6710     CV.push_back(C);
6711     CV.push_back(C);
6712   }
6713   Constant *C = ConstantVector::get(CV);
6714   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6715   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6716                              MachinePointerInfo::getConstantPool(),
6717                              false, false, 16);
6718   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6719 }
6720
6721 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6722   LLVMContext *Context = DAG.getContext();
6723   DebugLoc dl = Op.getDebugLoc();
6724   EVT VT = Op.getValueType();
6725   EVT EltVT = VT;
6726   if (VT.isVector())
6727     EltVT = VT.getVectorElementType();
6728   std::vector<Constant*> CV;
6729   if (EltVT == MVT::f64) {
6730     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6731     CV.push_back(C);
6732     CV.push_back(C);
6733   } else {
6734     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6735     CV.push_back(C);
6736     CV.push_back(C);
6737     CV.push_back(C);
6738     CV.push_back(C);
6739   }
6740   Constant *C = ConstantVector::get(CV);
6741   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6742   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6743                              MachinePointerInfo::getConstantPool(),
6744                              false, false, 16);
6745   if (VT.isVector()) {
6746     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6747                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6748                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6749                                 Op.getOperand(0)),
6750                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6751   } else {
6752     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6753   }
6754 }
6755
6756 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6757   LLVMContext *Context = DAG.getContext();
6758   SDValue Op0 = Op.getOperand(0);
6759   SDValue Op1 = Op.getOperand(1);
6760   DebugLoc dl = Op.getDebugLoc();
6761   EVT VT = Op.getValueType();
6762   EVT SrcVT = Op1.getValueType();
6763
6764   // If second operand is smaller, extend it first.
6765   if (SrcVT.bitsLT(VT)) {
6766     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6767     SrcVT = VT;
6768   }
6769   // And if it is bigger, shrink it first.
6770   if (SrcVT.bitsGT(VT)) {
6771     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6772     SrcVT = VT;
6773   }
6774
6775   // At this point the operands and the result should have the same
6776   // type, and that won't be f80 since that is not custom lowered.
6777
6778   // First get the sign bit of second operand.
6779   std::vector<Constant*> CV;
6780   if (SrcVT == MVT::f64) {
6781     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6782     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6783   } else {
6784     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6785     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6786     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6787     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6788   }
6789   Constant *C = ConstantVector::get(CV);
6790   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6791   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6792                               MachinePointerInfo::getConstantPool(),
6793                               false, false, 16);
6794   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6795
6796   // Shift sign bit right or left if the two operands have different types.
6797   if (SrcVT.bitsGT(VT)) {
6798     // Op0 is MVT::f32, Op1 is MVT::f64.
6799     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6800     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6801                           DAG.getConstant(32, MVT::i32));
6802     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6803     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6804                           DAG.getIntPtrConstant(0));
6805   }
6806
6807   // Clear first operand sign bit.
6808   CV.clear();
6809   if (VT == MVT::f64) {
6810     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6811     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6812   } else {
6813     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6814     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6815     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6816     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6817   }
6818   C = ConstantVector::get(CV);
6819   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6820   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6821                               MachinePointerInfo::getConstantPool(),
6822                               false, false, 16);
6823   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6824
6825   // Or the value with the sign bit.
6826   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6827 }
6828
6829 /// Emit nodes that will be selected as "test Op0,Op0", or something
6830 /// equivalent.
6831 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6832                                     SelectionDAG &DAG) const {
6833   DebugLoc dl = Op.getDebugLoc();
6834
6835   // CF and OF aren't always set the way we want. Determine which
6836   // of these we need.
6837   bool NeedCF = false;
6838   bool NeedOF = false;
6839   switch (X86CC) {
6840   default: break;
6841   case X86::COND_A: case X86::COND_AE:
6842   case X86::COND_B: case X86::COND_BE:
6843     NeedCF = true;
6844     break;
6845   case X86::COND_G: case X86::COND_GE:
6846   case X86::COND_L: case X86::COND_LE:
6847   case X86::COND_O: case X86::COND_NO:
6848     NeedOF = true;
6849     break;
6850   }
6851
6852   // See if we can use the EFLAGS value from the operand instead of
6853   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6854   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6855   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6856     // Emit a CMP with 0, which is the TEST pattern.
6857     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6858                        DAG.getConstant(0, Op.getValueType()));
6859
6860   unsigned Opcode = 0;
6861   unsigned NumOperands = 0;
6862   switch (Op.getNode()->getOpcode()) {
6863   case ISD::ADD:
6864     // Due to an isel shortcoming, be conservative if this add is likely to be
6865     // selected as part of a load-modify-store instruction. When the root node
6866     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6867     // uses of other nodes in the match, such as the ADD in this case. This
6868     // leads to the ADD being left around and reselected, with the result being
6869     // two adds in the output.  Alas, even if none our users are stores, that
6870     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6871     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6872     // climbing the DAG back to the root, and it doesn't seem to be worth the
6873     // effort.
6874     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6875            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6876       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6877         goto default_case;
6878
6879     if (ConstantSDNode *C =
6880         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6881       // An add of one will be selected as an INC.
6882       if (C->getAPIntValue() == 1) {
6883         Opcode = X86ISD::INC;
6884         NumOperands = 1;
6885         break;
6886       }
6887
6888       // An add of negative one (subtract of one) will be selected as a DEC.
6889       if (C->getAPIntValue().isAllOnesValue()) {
6890         Opcode = X86ISD::DEC;
6891         NumOperands = 1;
6892         break;
6893       }
6894     }
6895
6896     // Otherwise use a regular EFLAGS-setting add.
6897     Opcode = X86ISD::ADD;
6898     NumOperands = 2;
6899     break;
6900   case ISD::AND: {
6901     // If the primary and result isn't used, don't bother using X86ISD::AND,
6902     // because a TEST instruction will be better.
6903     bool NonFlagUse = false;
6904     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6905            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6906       SDNode *User = *UI;
6907       unsigned UOpNo = UI.getOperandNo();
6908       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6909         // Look pass truncate.
6910         UOpNo = User->use_begin().getOperandNo();
6911         User = *User->use_begin();
6912       }
6913
6914       if (User->getOpcode() != ISD::BRCOND &&
6915           User->getOpcode() != ISD::SETCC &&
6916           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6917         NonFlagUse = true;
6918         break;
6919       }
6920     }
6921
6922     if (!NonFlagUse)
6923       break;
6924   }
6925     // FALL THROUGH
6926   case ISD::SUB:
6927   case ISD::OR:
6928   case ISD::XOR:
6929     // Due to the ISEL shortcoming noted above, be conservative if this op is
6930     // likely to be selected as part of a load-modify-store instruction.
6931     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6932            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6933       if (UI->getOpcode() == ISD::STORE)
6934         goto default_case;
6935
6936     // Otherwise use a regular EFLAGS-setting instruction.
6937     switch (Op.getNode()->getOpcode()) {
6938     default: llvm_unreachable("unexpected operator!");
6939     case ISD::SUB: Opcode = X86ISD::SUB; break;
6940     case ISD::OR:  Opcode = X86ISD::OR;  break;
6941     case ISD::XOR: Opcode = X86ISD::XOR; break;
6942     case ISD::AND: Opcode = X86ISD::AND; break;
6943     }
6944
6945     NumOperands = 2;
6946     break;
6947   case X86ISD::ADD:
6948   case X86ISD::SUB:
6949   case X86ISD::INC:
6950   case X86ISD::DEC:
6951   case X86ISD::OR:
6952   case X86ISD::XOR:
6953   case X86ISD::AND:
6954     return SDValue(Op.getNode(), 1);
6955   default:
6956   default_case:
6957     break;
6958   }
6959
6960   if (Opcode == 0)
6961     // Emit a CMP with 0, which is the TEST pattern.
6962     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6963                        DAG.getConstant(0, Op.getValueType()));
6964
6965   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6966   SmallVector<SDValue, 4> Ops;
6967   for (unsigned i = 0; i != NumOperands; ++i)
6968     Ops.push_back(Op.getOperand(i));
6969
6970   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6971   DAG.ReplaceAllUsesWith(Op, New);
6972   return SDValue(New.getNode(), 1);
6973 }
6974
6975 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6976 /// equivalent.
6977 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6978                                    SelectionDAG &DAG) const {
6979   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6980     if (C->getAPIntValue() == 0)
6981       return EmitTest(Op0, X86CC, DAG);
6982
6983   DebugLoc dl = Op0.getDebugLoc();
6984   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6985 }
6986
6987 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6988 /// if it's possible.
6989 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6990                                      DebugLoc dl, SelectionDAG &DAG) const {
6991   SDValue Op0 = And.getOperand(0);
6992   SDValue Op1 = And.getOperand(1);
6993   if (Op0.getOpcode() == ISD::TRUNCATE)
6994     Op0 = Op0.getOperand(0);
6995   if (Op1.getOpcode() == ISD::TRUNCATE)
6996     Op1 = Op1.getOperand(0);
6997
6998   SDValue LHS, RHS;
6999   if (Op1.getOpcode() == ISD::SHL)
7000     std::swap(Op0, Op1);
7001   if (Op0.getOpcode() == ISD::SHL) {
7002     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7003       if (And00C->getZExtValue() == 1) {
7004         // If we looked past a truncate, check that it's only truncating away
7005         // known zeros.
7006         unsigned BitWidth = Op0.getValueSizeInBits();
7007         unsigned AndBitWidth = And.getValueSizeInBits();
7008         if (BitWidth > AndBitWidth) {
7009           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7010           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7011           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7012             return SDValue();
7013         }
7014         LHS = Op1;
7015         RHS = Op0.getOperand(1);
7016       }
7017   } else if (Op1.getOpcode() == ISD::Constant) {
7018     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7019     SDValue AndLHS = Op0;
7020     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7021       LHS = AndLHS.getOperand(0);
7022       RHS = AndLHS.getOperand(1);
7023     }
7024   }
7025
7026   if (LHS.getNode()) {
7027     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7028     // instruction.  Since the shift amount is in-range-or-undefined, we know
7029     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7030     // the encoding for the i16 version is larger than the i32 version.
7031     // Also promote i16 to i32 for performance / code size reason.
7032     if (LHS.getValueType() == MVT::i8 ||
7033         LHS.getValueType() == MVT::i16)
7034       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7035
7036     // If the operand types disagree, extend the shift amount to match.  Since
7037     // BT ignores high bits (like shifts) we can use anyextend.
7038     if (LHS.getValueType() != RHS.getValueType())
7039       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7040
7041     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7042     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7043     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7044                        DAG.getConstant(Cond, MVT::i8), BT);
7045   }
7046
7047   return SDValue();
7048 }
7049
7050 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7051   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7052   SDValue Op0 = Op.getOperand(0);
7053   SDValue Op1 = Op.getOperand(1);
7054   DebugLoc dl = Op.getDebugLoc();
7055   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7056
7057   // Optimize to BT if possible.
7058   // Lower (X & (1 << N)) == 0 to BT(X, N).
7059   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7060   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7061   if (Op0.getOpcode() == ISD::AND &&
7062       Op0.hasOneUse() &&
7063       Op1.getOpcode() == ISD::Constant &&
7064       cast<ConstantSDNode>(Op1)->isNullValue() &&
7065       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7066     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7067     if (NewSetCC.getNode())
7068       return NewSetCC;
7069   }
7070
7071   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7072   if (Op0.getOpcode() == X86ISD::SETCC &&
7073       Op1.getOpcode() == ISD::Constant &&
7074       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7075        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7076       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7077     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7078     bool Invert = (CC == ISD::SETNE) ^
7079       cast<ConstantSDNode>(Op1)->isNullValue();
7080     if (Invert)
7081       CCode = X86::GetOppositeBranchCondition(CCode);
7082     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7083                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7084   }
7085
7086   bool isFP = Op1.getValueType().isFloatingPoint();
7087   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7088   if (X86CC == X86::COND_INVALID)
7089     return SDValue();
7090
7091   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7092
7093   // Use sbb x, x to materialize carry bit into a GPR.
7094   if (X86CC == X86::COND_B)
7095     return DAG.getNode(ISD::AND, dl, MVT::i8,
7096                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7097                                    DAG.getConstant(X86CC, MVT::i8), Cond),
7098                        DAG.getConstant(1, MVT::i8));
7099
7100   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7101                      DAG.getConstant(X86CC, MVT::i8), Cond);
7102 }
7103
7104 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7105   SDValue Cond;
7106   SDValue Op0 = Op.getOperand(0);
7107   SDValue Op1 = Op.getOperand(1);
7108   SDValue CC = Op.getOperand(2);
7109   EVT VT = Op.getValueType();
7110   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7111   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7112   DebugLoc dl = Op.getDebugLoc();
7113
7114   if (isFP) {
7115     unsigned SSECC = 8;
7116     EVT VT0 = Op0.getValueType();
7117     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7118     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7119     bool Swap = false;
7120
7121     switch (SetCCOpcode) {
7122     default: break;
7123     case ISD::SETOEQ:
7124     case ISD::SETEQ:  SSECC = 0; break;
7125     case ISD::SETOGT:
7126     case ISD::SETGT: Swap = true; // Fallthrough
7127     case ISD::SETLT:
7128     case ISD::SETOLT: SSECC = 1; break;
7129     case ISD::SETOGE:
7130     case ISD::SETGE: Swap = true; // Fallthrough
7131     case ISD::SETLE:
7132     case ISD::SETOLE: SSECC = 2; break;
7133     case ISD::SETUO:  SSECC = 3; break;
7134     case ISD::SETUNE:
7135     case ISD::SETNE:  SSECC = 4; break;
7136     case ISD::SETULE: Swap = true;
7137     case ISD::SETUGE: SSECC = 5; break;
7138     case ISD::SETULT: Swap = true;
7139     case ISD::SETUGT: SSECC = 6; break;
7140     case ISD::SETO:   SSECC = 7; break;
7141     }
7142     if (Swap)
7143       std::swap(Op0, Op1);
7144
7145     // In the two special cases we can't handle, emit two comparisons.
7146     if (SSECC == 8) {
7147       if (SetCCOpcode == ISD::SETUEQ) {
7148         SDValue UNORD, EQ;
7149         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7150         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7151         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7152       }
7153       else if (SetCCOpcode == ISD::SETONE) {
7154         SDValue ORD, NEQ;
7155         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7156         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7157         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7158       }
7159       llvm_unreachable("Illegal FP comparison");
7160     }
7161     // Handle all other FP comparisons here.
7162     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7163   }
7164
7165   // We are handling one of the integer comparisons here.  Since SSE only has
7166   // GT and EQ comparisons for integer, swapping operands and multiple
7167   // operations may be required for some comparisons.
7168   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7169   bool Swap = false, Invert = false, FlipSigns = false;
7170
7171   switch (VT.getSimpleVT().SimpleTy) {
7172   default: break;
7173   case MVT::v8i8:
7174   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7175   case MVT::v4i16:
7176   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7177   case MVT::v2i32:
7178   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7179   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7180   }
7181
7182   switch (SetCCOpcode) {
7183   default: break;
7184   case ISD::SETNE:  Invert = true;
7185   case ISD::SETEQ:  Opc = EQOpc; break;
7186   case ISD::SETLT:  Swap = true;
7187   case ISD::SETGT:  Opc = GTOpc; break;
7188   case ISD::SETGE:  Swap = true;
7189   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7190   case ISD::SETULT: Swap = true;
7191   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7192   case ISD::SETUGE: Swap = true;
7193   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7194   }
7195   if (Swap)
7196     std::swap(Op0, Op1);
7197
7198   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7199   // bits of the inputs before performing those operations.
7200   if (FlipSigns) {
7201     EVT EltVT = VT.getVectorElementType();
7202     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7203                                       EltVT);
7204     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7205     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7206                                     SignBits.size());
7207     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7208     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7209   }
7210
7211   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7212
7213   // If the logical-not of the result is required, perform that now.
7214   if (Invert)
7215     Result = DAG.getNOT(dl, Result, VT);
7216
7217   return Result;
7218 }
7219
7220 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7221 static bool isX86LogicalCmp(SDValue Op) {
7222   unsigned Opc = Op.getNode()->getOpcode();
7223   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7224     return true;
7225   if (Op.getResNo() == 1 &&
7226       (Opc == X86ISD::ADD ||
7227        Opc == X86ISD::SUB ||
7228        Opc == X86ISD::SMUL ||
7229        Opc == X86ISD::UMUL ||
7230        Opc == X86ISD::INC ||
7231        Opc == X86ISD::DEC ||
7232        Opc == X86ISD::OR ||
7233        Opc == X86ISD::XOR ||
7234        Opc == X86ISD::AND))
7235     return true;
7236
7237   return false;
7238 }
7239
7240 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7241   bool addTest = true;
7242   SDValue Cond  = Op.getOperand(0);
7243   DebugLoc dl = Op.getDebugLoc();
7244   SDValue CC;
7245
7246   if (Cond.getOpcode() == ISD::SETCC) {
7247     SDValue NewCond = LowerSETCC(Cond, DAG);
7248     if (NewCond.getNode())
7249       Cond = NewCond;
7250   }
7251
7252   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7253   SDValue Op1 = Op.getOperand(1);
7254   SDValue Op2 = Op.getOperand(2);
7255   if (Cond.getOpcode() == X86ISD::SETCC &&
7256       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7257     SDValue Cmp = Cond.getOperand(1);
7258     if (Cmp.getOpcode() == X86ISD::CMP) {
7259       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7260       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7261       ConstantSDNode *RHSC =
7262         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7263       if (N1C && N1C->isAllOnesValue() &&
7264           N2C && N2C->isNullValue() &&
7265           RHSC && RHSC->isNullValue()) {
7266         SDValue CmpOp0 = Cmp.getOperand(0);
7267         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7268                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7269         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7270                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7271       }
7272     }
7273   }
7274
7275   // Look pass (and (setcc_carry (cmp ...)), 1).
7276   if (Cond.getOpcode() == ISD::AND &&
7277       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7278     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7279     if (C && C->getAPIntValue() == 1) 
7280       Cond = Cond.getOperand(0);
7281   }
7282
7283   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7284   // setting operand in place of the X86ISD::SETCC.
7285   if (Cond.getOpcode() == X86ISD::SETCC ||
7286       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7287     CC = Cond.getOperand(0);
7288
7289     SDValue Cmp = Cond.getOperand(1);
7290     unsigned Opc = Cmp.getOpcode();
7291     EVT VT = Op.getValueType();
7292
7293     bool IllegalFPCMov = false;
7294     if (VT.isFloatingPoint() && !VT.isVector() &&
7295         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7296       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7297
7298     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7299         Opc == X86ISD::BT) { // FIXME
7300       Cond = Cmp;
7301       addTest = false;
7302     }
7303   }
7304
7305   if (addTest) {
7306     // Look pass the truncate.
7307     if (Cond.getOpcode() == ISD::TRUNCATE)
7308       Cond = Cond.getOperand(0);
7309
7310     // We know the result of AND is compared against zero. Try to match
7311     // it to BT.
7312     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7313       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7314       if (NewSetCC.getNode()) {
7315         CC = NewSetCC.getOperand(0);
7316         Cond = NewSetCC.getOperand(1);
7317         addTest = false;
7318       }
7319     }
7320   }
7321
7322   if (addTest) {
7323     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7324     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7325   }
7326
7327   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7328   // condition is true.
7329   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7330   SDValue Ops[] = { Op2, Op1, CC, Cond };
7331   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7332 }
7333
7334 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7335 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7336 // from the AND / OR.
7337 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7338   Opc = Op.getOpcode();
7339   if (Opc != ISD::OR && Opc != ISD::AND)
7340     return false;
7341   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7342           Op.getOperand(0).hasOneUse() &&
7343           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7344           Op.getOperand(1).hasOneUse());
7345 }
7346
7347 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7348 // 1 and that the SETCC node has a single use.
7349 static bool isXor1OfSetCC(SDValue Op) {
7350   if (Op.getOpcode() != ISD::XOR)
7351     return false;
7352   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7353   if (N1C && N1C->getAPIntValue() == 1) {
7354     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7355       Op.getOperand(0).hasOneUse();
7356   }
7357   return false;
7358 }
7359
7360 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7361   bool addTest = true;
7362   SDValue Chain = Op.getOperand(0);
7363   SDValue Cond  = Op.getOperand(1);
7364   SDValue Dest  = Op.getOperand(2);
7365   DebugLoc dl = Op.getDebugLoc();
7366   SDValue CC;
7367
7368   if (Cond.getOpcode() == ISD::SETCC) {
7369     SDValue NewCond = LowerSETCC(Cond, DAG);
7370     if (NewCond.getNode())
7371       Cond = NewCond;
7372   }
7373 #if 0
7374   // FIXME: LowerXALUO doesn't handle these!!
7375   else if (Cond.getOpcode() == X86ISD::ADD  ||
7376            Cond.getOpcode() == X86ISD::SUB  ||
7377            Cond.getOpcode() == X86ISD::SMUL ||
7378            Cond.getOpcode() == X86ISD::UMUL)
7379     Cond = LowerXALUO(Cond, DAG);
7380 #endif
7381
7382   // Look pass (and (setcc_carry (cmp ...)), 1).
7383   if (Cond.getOpcode() == ISD::AND &&
7384       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7385     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7386     if (C && C->getAPIntValue() == 1) 
7387       Cond = Cond.getOperand(0);
7388   }
7389
7390   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7391   // setting operand in place of the X86ISD::SETCC.
7392   if (Cond.getOpcode() == X86ISD::SETCC ||
7393       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7394     CC = Cond.getOperand(0);
7395
7396     SDValue Cmp = Cond.getOperand(1);
7397     unsigned Opc = Cmp.getOpcode();
7398     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7399     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7400       Cond = Cmp;
7401       addTest = false;
7402     } else {
7403       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7404       default: break;
7405       case X86::COND_O:
7406       case X86::COND_B:
7407         // These can only come from an arithmetic instruction with overflow,
7408         // e.g. SADDO, UADDO.
7409         Cond = Cond.getNode()->getOperand(1);
7410         addTest = false;
7411         break;
7412       }
7413     }
7414   } else {
7415     unsigned CondOpc;
7416     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7417       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7418       if (CondOpc == ISD::OR) {
7419         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7420         // two branches instead of an explicit OR instruction with a
7421         // separate test.
7422         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7423             isX86LogicalCmp(Cmp)) {
7424           CC = Cond.getOperand(0).getOperand(0);
7425           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7426                               Chain, Dest, CC, Cmp);
7427           CC = Cond.getOperand(1).getOperand(0);
7428           Cond = Cmp;
7429           addTest = false;
7430         }
7431       } else { // ISD::AND
7432         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7433         // two branches instead of an explicit AND instruction with a
7434         // separate test. However, we only do this if this block doesn't
7435         // have a fall-through edge, because this requires an explicit
7436         // jmp when the condition is false.
7437         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7438             isX86LogicalCmp(Cmp) &&
7439             Op.getNode()->hasOneUse()) {
7440           X86::CondCode CCode =
7441             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7442           CCode = X86::GetOppositeBranchCondition(CCode);
7443           CC = DAG.getConstant(CCode, MVT::i8);
7444           SDNode *User = *Op.getNode()->use_begin();
7445           // Look for an unconditional branch following this conditional branch.
7446           // We need this because we need to reverse the successors in order
7447           // to implement FCMP_OEQ.
7448           if (User->getOpcode() == ISD::BR) {
7449             SDValue FalseBB = User->getOperand(1);
7450             SDNode *NewBR =
7451               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7452             assert(NewBR == User);
7453             (void)NewBR;
7454             Dest = FalseBB;
7455
7456             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7457                                 Chain, Dest, CC, Cmp);
7458             X86::CondCode CCode =
7459               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7460             CCode = X86::GetOppositeBranchCondition(CCode);
7461             CC = DAG.getConstant(CCode, MVT::i8);
7462             Cond = Cmp;
7463             addTest = false;
7464           }
7465         }
7466       }
7467     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7468       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7469       // It should be transformed during dag combiner except when the condition
7470       // is set by a arithmetics with overflow node.
7471       X86::CondCode CCode =
7472         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7473       CCode = X86::GetOppositeBranchCondition(CCode);
7474       CC = DAG.getConstant(CCode, MVT::i8);
7475       Cond = Cond.getOperand(0).getOperand(1);
7476       addTest = false;
7477     }
7478   }
7479
7480   if (addTest) {
7481     // Look pass the truncate.
7482     if (Cond.getOpcode() == ISD::TRUNCATE)
7483       Cond = Cond.getOperand(0);
7484
7485     // We know the result of AND is compared against zero. Try to match
7486     // it to BT.
7487     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7488       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7489       if (NewSetCC.getNode()) {
7490         CC = NewSetCC.getOperand(0);
7491         Cond = NewSetCC.getOperand(1);
7492         addTest = false;
7493       }
7494     }
7495   }
7496
7497   if (addTest) {
7498     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7499     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7500   }
7501   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7502                      Chain, Dest, CC, Cond);
7503 }
7504
7505
7506 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7507 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7508 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7509 // that the guard pages used by the OS virtual memory manager are allocated in
7510 // correct sequence.
7511 SDValue
7512 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7513                                            SelectionDAG &DAG) const {
7514   assert(Subtarget->isTargetCygMing() &&
7515          "This should be used only on Cygwin/Mingw targets");
7516   DebugLoc dl = Op.getDebugLoc();
7517
7518   // Get the inputs.
7519   SDValue Chain = Op.getOperand(0);
7520   SDValue Size  = Op.getOperand(1);
7521   // FIXME: Ensure alignment here
7522
7523   SDValue Flag;
7524
7525   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7526
7527   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7528   Flag = Chain.getValue(1);
7529
7530   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7531
7532   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7533   Flag = Chain.getValue(1);
7534
7535   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7536
7537   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7538   return DAG.getMergeValues(Ops1, 2, dl);
7539 }
7540
7541 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7542   MachineFunction &MF = DAG.getMachineFunction();
7543   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7544
7545   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7546   DebugLoc DL = Op.getDebugLoc();
7547
7548   if (!Subtarget->is64Bit()) {
7549     // vastart just stores the address of the VarArgsFrameIndex slot into the
7550     // memory location argument.
7551     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7552                                    getPointerTy());
7553     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7554                         MachinePointerInfo(SV), false, false, 0);
7555   }
7556
7557   // __va_list_tag:
7558   //   gp_offset         (0 - 6 * 8)
7559   //   fp_offset         (48 - 48 + 8 * 16)
7560   //   overflow_arg_area (point to parameters coming in memory).
7561   //   reg_save_area
7562   SmallVector<SDValue, 8> MemOps;
7563   SDValue FIN = Op.getOperand(1);
7564   // Store gp_offset
7565   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7566                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7567                                                MVT::i32),
7568                                FIN, MachinePointerInfo(SV), false, false, 0);
7569   MemOps.push_back(Store);
7570
7571   // Store fp_offset
7572   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7573                     FIN, DAG.getIntPtrConstant(4));
7574   Store = DAG.getStore(Op.getOperand(0), DL,
7575                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7576                                        MVT::i32),
7577                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7578   MemOps.push_back(Store);
7579
7580   // Store ptr to overflow_arg_area
7581   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7582                     FIN, DAG.getIntPtrConstant(4));
7583   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7584                                     getPointerTy());
7585   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7586                        MachinePointerInfo(SV, 8),
7587                        false, false, 0);
7588   MemOps.push_back(Store);
7589
7590   // Store ptr to reg_save_area.
7591   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7592                     FIN, DAG.getIntPtrConstant(8));
7593   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7594                                     getPointerTy());
7595   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7596                        MachinePointerInfo(SV, 16), false, false, 0);
7597   MemOps.push_back(Store);
7598   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7599                      &MemOps[0], MemOps.size());
7600 }
7601
7602 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7603   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7604   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7605
7606   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7607   return SDValue();
7608 }
7609
7610 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7611   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7612   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7613   SDValue Chain = Op.getOperand(0);
7614   SDValue DstPtr = Op.getOperand(1);
7615   SDValue SrcPtr = Op.getOperand(2);
7616   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7617   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7618   DebugLoc DL = Op.getDebugLoc();
7619
7620   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7621                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7622                        false, 
7623                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7624 }
7625
7626 SDValue
7627 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7628   DebugLoc dl = Op.getDebugLoc();
7629   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7630   switch (IntNo) {
7631   default: return SDValue();    // Don't custom lower most intrinsics.
7632   // Comparison intrinsics.
7633   case Intrinsic::x86_sse_comieq_ss:
7634   case Intrinsic::x86_sse_comilt_ss:
7635   case Intrinsic::x86_sse_comile_ss:
7636   case Intrinsic::x86_sse_comigt_ss:
7637   case Intrinsic::x86_sse_comige_ss:
7638   case Intrinsic::x86_sse_comineq_ss:
7639   case Intrinsic::x86_sse_ucomieq_ss:
7640   case Intrinsic::x86_sse_ucomilt_ss:
7641   case Intrinsic::x86_sse_ucomile_ss:
7642   case Intrinsic::x86_sse_ucomigt_ss:
7643   case Intrinsic::x86_sse_ucomige_ss:
7644   case Intrinsic::x86_sse_ucomineq_ss:
7645   case Intrinsic::x86_sse2_comieq_sd:
7646   case Intrinsic::x86_sse2_comilt_sd:
7647   case Intrinsic::x86_sse2_comile_sd:
7648   case Intrinsic::x86_sse2_comigt_sd:
7649   case Intrinsic::x86_sse2_comige_sd:
7650   case Intrinsic::x86_sse2_comineq_sd:
7651   case Intrinsic::x86_sse2_ucomieq_sd:
7652   case Intrinsic::x86_sse2_ucomilt_sd:
7653   case Intrinsic::x86_sse2_ucomile_sd:
7654   case Intrinsic::x86_sse2_ucomigt_sd:
7655   case Intrinsic::x86_sse2_ucomige_sd:
7656   case Intrinsic::x86_sse2_ucomineq_sd: {
7657     unsigned Opc = 0;
7658     ISD::CondCode CC = ISD::SETCC_INVALID;
7659     switch (IntNo) {
7660     default: break;
7661     case Intrinsic::x86_sse_comieq_ss:
7662     case Intrinsic::x86_sse2_comieq_sd:
7663       Opc = X86ISD::COMI;
7664       CC = ISD::SETEQ;
7665       break;
7666     case Intrinsic::x86_sse_comilt_ss:
7667     case Intrinsic::x86_sse2_comilt_sd:
7668       Opc = X86ISD::COMI;
7669       CC = ISD::SETLT;
7670       break;
7671     case Intrinsic::x86_sse_comile_ss:
7672     case Intrinsic::x86_sse2_comile_sd:
7673       Opc = X86ISD::COMI;
7674       CC = ISD::SETLE;
7675       break;
7676     case Intrinsic::x86_sse_comigt_ss:
7677     case Intrinsic::x86_sse2_comigt_sd:
7678       Opc = X86ISD::COMI;
7679       CC = ISD::SETGT;
7680       break;
7681     case Intrinsic::x86_sse_comige_ss:
7682     case Intrinsic::x86_sse2_comige_sd:
7683       Opc = X86ISD::COMI;
7684       CC = ISD::SETGE;
7685       break;
7686     case Intrinsic::x86_sse_comineq_ss:
7687     case Intrinsic::x86_sse2_comineq_sd:
7688       Opc = X86ISD::COMI;
7689       CC = ISD::SETNE;
7690       break;
7691     case Intrinsic::x86_sse_ucomieq_ss:
7692     case Intrinsic::x86_sse2_ucomieq_sd:
7693       Opc = X86ISD::UCOMI;
7694       CC = ISD::SETEQ;
7695       break;
7696     case Intrinsic::x86_sse_ucomilt_ss:
7697     case Intrinsic::x86_sse2_ucomilt_sd:
7698       Opc = X86ISD::UCOMI;
7699       CC = ISD::SETLT;
7700       break;
7701     case Intrinsic::x86_sse_ucomile_ss:
7702     case Intrinsic::x86_sse2_ucomile_sd:
7703       Opc = X86ISD::UCOMI;
7704       CC = ISD::SETLE;
7705       break;
7706     case Intrinsic::x86_sse_ucomigt_ss:
7707     case Intrinsic::x86_sse2_ucomigt_sd:
7708       Opc = X86ISD::UCOMI;
7709       CC = ISD::SETGT;
7710       break;
7711     case Intrinsic::x86_sse_ucomige_ss:
7712     case Intrinsic::x86_sse2_ucomige_sd:
7713       Opc = X86ISD::UCOMI;
7714       CC = ISD::SETGE;
7715       break;
7716     case Intrinsic::x86_sse_ucomineq_ss:
7717     case Intrinsic::x86_sse2_ucomineq_sd:
7718       Opc = X86ISD::UCOMI;
7719       CC = ISD::SETNE;
7720       break;
7721     }
7722
7723     SDValue LHS = Op.getOperand(1);
7724     SDValue RHS = Op.getOperand(2);
7725     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7726     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7727     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7728     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7729                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7730     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7731   }
7732   // ptest and testp intrinsics. The intrinsic these come from are designed to
7733   // return an integer value, not just an instruction so lower it to the ptest
7734   // or testp pattern and a setcc for the result.
7735   case Intrinsic::x86_sse41_ptestz:
7736   case Intrinsic::x86_sse41_ptestc:
7737   case Intrinsic::x86_sse41_ptestnzc:
7738   case Intrinsic::x86_avx_ptestz_256:
7739   case Intrinsic::x86_avx_ptestc_256:
7740   case Intrinsic::x86_avx_ptestnzc_256:
7741   case Intrinsic::x86_avx_vtestz_ps:
7742   case Intrinsic::x86_avx_vtestc_ps:
7743   case Intrinsic::x86_avx_vtestnzc_ps:
7744   case Intrinsic::x86_avx_vtestz_pd:
7745   case Intrinsic::x86_avx_vtestc_pd:
7746   case Intrinsic::x86_avx_vtestnzc_pd:
7747   case Intrinsic::x86_avx_vtestz_ps_256:
7748   case Intrinsic::x86_avx_vtestc_ps_256:
7749   case Intrinsic::x86_avx_vtestnzc_ps_256:
7750   case Intrinsic::x86_avx_vtestz_pd_256:
7751   case Intrinsic::x86_avx_vtestc_pd_256:
7752   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7753     bool IsTestPacked = false;
7754     unsigned X86CC = 0;
7755     switch (IntNo) {
7756     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7757     case Intrinsic::x86_avx_vtestz_ps:
7758     case Intrinsic::x86_avx_vtestz_pd:
7759     case Intrinsic::x86_avx_vtestz_ps_256:
7760     case Intrinsic::x86_avx_vtestz_pd_256:
7761       IsTestPacked = true; // Fallthrough
7762     case Intrinsic::x86_sse41_ptestz:
7763     case Intrinsic::x86_avx_ptestz_256:
7764       // ZF = 1
7765       X86CC = X86::COND_E;
7766       break;
7767     case Intrinsic::x86_avx_vtestc_ps:
7768     case Intrinsic::x86_avx_vtestc_pd:
7769     case Intrinsic::x86_avx_vtestc_ps_256:
7770     case Intrinsic::x86_avx_vtestc_pd_256:
7771       IsTestPacked = true; // Fallthrough
7772     case Intrinsic::x86_sse41_ptestc:
7773     case Intrinsic::x86_avx_ptestc_256:
7774       // CF = 1
7775       X86CC = X86::COND_B;
7776       break;
7777     case Intrinsic::x86_avx_vtestnzc_ps:
7778     case Intrinsic::x86_avx_vtestnzc_pd:
7779     case Intrinsic::x86_avx_vtestnzc_ps_256:
7780     case Intrinsic::x86_avx_vtestnzc_pd_256:
7781       IsTestPacked = true; // Fallthrough
7782     case Intrinsic::x86_sse41_ptestnzc:
7783     case Intrinsic::x86_avx_ptestnzc_256:
7784       // ZF and CF = 0
7785       X86CC = X86::COND_A;
7786       break;
7787     }
7788
7789     SDValue LHS = Op.getOperand(1);
7790     SDValue RHS = Op.getOperand(2);
7791     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7792     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7793     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7794     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7795     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7796   }
7797
7798   // Fix vector shift instructions where the last operand is a non-immediate
7799   // i32 value.
7800   case Intrinsic::x86_sse2_pslli_w:
7801   case Intrinsic::x86_sse2_pslli_d:
7802   case Intrinsic::x86_sse2_pslli_q:
7803   case Intrinsic::x86_sse2_psrli_w:
7804   case Intrinsic::x86_sse2_psrli_d:
7805   case Intrinsic::x86_sse2_psrli_q:
7806   case Intrinsic::x86_sse2_psrai_w:
7807   case Intrinsic::x86_sse2_psrai_d:
7808   case Intrinsic::x86_mmx_pslli_w:
7809   case Intrinsic::x86_mmx_pslli_d:
7810   case Intrinsic::x86_mmx_pslli_q:
7811   case Intrinsic::x86_mmx_psrli_w:
7812   case Intrinsic::x86_mmx_psrli_d:
7813   case Intrinsic::x86_mmx_psrli_q:
7814   case Intrinsic::x86_mmx_psrai_w:
7815   case Intrinsic::x86_mmx_psrai_d: {
7816     SDValue ShAmt = Op.getOperand(2);
7817     if (isa<ConstantSDNode>(ShAmt))
7818       return SDValue();
7819
7820     unsigned NewIntNo = 0;
7821     EVT ShAmtVT = MVT::v4i32;
7822     switch (IntNo) {
7823     case Intrinsic::x86_sse2_pslli_w:
7824       NewIntNo = Intrinsic::x86_sse2_psll_w;
7825       break;
7826     case Intrinsic::x86_sse2_pslli_d:
7827       NewIntNo = Intrinsic::x86_sse2_psll_d;
7828       break;
7829     case Intrinsic::x86_sse2_pslli_q:
7830       NewIntNo = Intrinsic::x86_sse2_psll_q;
7831       break;
7832     case Intrinsic::x86_sse2_psrli_w:
7833       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7834       break;
7835     case Intrinsic::x86_sse2_psrli_d:
7836       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7837       break;
7838     case Intrinsic::x86_sse2_psrli_q:
7839       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7840       break;
7841     case Intrinsic::x86_sse2_psrai_w:
7842       NewIntNo = Intrinsic::x86_sse2_psra_w;
7843       break;
7844     case Intrinsic::x86_sse2_psrai_d:
7845       NewIntNo = Intrinsic::x86_sse2_psra_d;
7846       break;
7847     default: {
7848       ShAmtVT = MVT::v2i32;
7849       switch (IntNo) {
7850       case Intrinsic::x86_mmx_pslli_w:
7851         NewIntNo = Intrinsic::x86_mmx_psll_w;
7852         break;
7853       case Intrinsic::x86_mmx_pslli_d:
7854         NewIntNo = Intrinsic::x86_mmx_psll_d;
7855         break;
7856       case Intrinsic::x86_mmx_pslli_q:
7857         NewIntNo = Intrinsic::x86_mmx_psll_q;
7858         break;
7859       case Intrinsic::x86_mmx_psrli_w:
7860         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7861         break;
7862       case Intrinsic::x86_mmx_psrli_d:
7863         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7864         break;
7865       case Intrinsic::x86_mmx_psrli_q:
7866         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7867         break;
7868       case Intrinsic::x86_mmx_psrai_w:
7869         NewIntNo = Intrinsic::x86_mmx_psra_w;
7870         break;
7871       case Intrinsic::x86_mmx_psrai_d:
7872         NewIntNo = Intrinsic::x86_mmx_psra_d;
7873         break;
7874       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7875       }
7876       break;
7877     }
7878     }
7879
7880     // The vector shift intrinsics with scalars uses 32b shift amounts but
7881     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7882     // to be zero.
7883     SDValue ShOps[4];
7884     ShOps[0] = ShAmt;
7885     ShOps[1] = DAG.getConstant(0, MVT::i32);
7886     if (ShAmtVT == MVT::v4i32) {
7887       ShOps[2] = DAG.getUNDEF(MVT::i32);
7888       ShOps[3] = DAG.getUNDEF(MVT::i32);
7889       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7890     } else {
7891       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7892     }
7893
7894     EVT VT = Op.getValueType();
7895     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7896     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7897                        DAG.getConstant(NewIntNo, MVT::i32),
7898                        Op.getOperand(1), ShAmt);
7899   }
7900   }
7901 }
7902
7903 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7904                                            SelectionDAG &DAG) const {
7905   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7906   MFI->setReturnAddressIsTaken(true);
7907
7908   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7909   DebugLoc dl = Op.getDebugLoc();
7910
7911   if (Depth > 0) {
7912     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7913     SDValue Offset =
7914       DAG.getConstant(TD->getPointerSize(),
7915                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7916     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7917                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7918                                    FrameAddr, Offset),
7919                        MachinePointerInfo(), false, false, 0);
7920   }
7921
7922   // Just load the return address.
7923   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7924   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7925                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7926 }
7927
7928 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7929   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7930   MFI->setFrameAddressIsTaken(true);
7931
7932   EVT VT = Op.getValueType();
7933   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7934   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7935   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7936   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7937   while (Depth--)
7938     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7939                             MachinePointerInfo(),
7940                             false, false, 0);
7941   return FrameAddr;
7942 }
7943
7944 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7945                                                      SelectionDAG &DAG) const {
7946   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7947 }
7948
7949 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7950   MachineFunction &MF = DAG.getMachineFunction();
7951   SDValue Chain     = Op.getOperand(0);
7952   SDValue Offset    = Op.getOperand(1);
7953   SDValue Handler   = Op.getOperand(2);
7954   DebugLoc dl       = Op.getDebugLoc();
7955
7956   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7957                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7958                                      getPointerTy());
7959   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7960
7961   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7962                                   DAG.getIntPtrConstant(TD->getPointerSize()));
7963   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7964   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
7965                        false, false, 0);
7966   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7967   MF.getRegInfo().addLiveOut(StoreAddrReg);
7968
7969   return DAG.getNode(X86ISD::EH_RETURN, dl,
7970                      MVT::Other,
7971                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7972 }
7973
7974 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7975                                              SelectionDAG &DAG) const {
7976   SDValue Root = Op.getOperand(0);
7977   SDValue Trmp = Op.getOperand(1); // trampoline
7978   SDValue FPtr = Op.getOperand(2); // nested function
7979   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7980   DebugLoc dl  = Op.getDebugLoc();
7981
7982   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7983
7984   if (Subtarget->is64Bit()) {
7985     SDValue OutChains[6];
7986
7987     // Large code-model.
7988     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7989     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7990
7991     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7992     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7993
7994     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7995
7996     // Load the pointer to the nested function into R11.
7997     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7998     SDValue Addr = Trmp;
7999     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8000                                 Addr, MachinePointerInfo(TrmpAddr),
8001                                 false, false, 0);
8002
8003     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8004                        DAG.getConstant(2, MVT::i64));
8005     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8006                                 MachinePointerInfo(TrmpAddr, 2),
8007                                 false, false, 2);
8008
8009     // Load the 'nest' parameter value into R10.
8010     // R10 is specified in X86CallingConv.td
8011     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8012     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8013                        DAG.getConstant(10, MVT::i64));
8014     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8015                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8016                                 false, false, 0);
8017
8018     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8019                        DAG.getConstant(12, MVT::i64));
8020     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8021                                 MachinePointerInfo(TrmpAddr, 12),
8022                                 false, false, 2);
8023
8024     // Jump to the nested function.
8025     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8026     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8027                        DAG.getConstant(20, MVT::i64));
8028     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8029                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8030                                 false, false, 0);
8031
8032     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8033     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8034                        DAG.getConstant(22, MVT::i64));
8035     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8036                                 MachinePointerInfo(TrmpAddr, 22),
8037                                 false, false, 0);
8038
8039     SDValue Ops[] =
8040       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8041     return DAG.getMergeValues(Ops, 2, dl);
8042   } else {
8043     const Function *Func =
8044       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8045     CallingConv::ID CC = Func->getCallingConv();
8046     unsigned NestReg;
8047
8048     switch (CC) {
8049     default:
8050       llvm_unreachable("Unsupported calling convention");
8051     case CallingConv::C:
8052     case CallingConv::X86_StdCall: {
8053       // Pass 'nest' parameter in ECX.
8054       // Must be kept in sync with X86CallingConv.td
8055       NestReg = X86::ECX;
8056
8057       // Check that ECX wasn't needed by an 'inreg' parameter.
8058       const FunctionType *FTy = Func->getFunctionType();
8059       const AttrListPtr &Attrs = Func->getAttributes();
8060
8061       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8062         unsigned InRegCount = 0;
8063         unsigned Idx = 1;
8064
8065         for (FunctionType::param_iterator I = FTy->param_begin(),
8066              E = FTy->param_end(); I != E; ++I, ++Idx)
8067           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8068             // FIXME: should only count parameters that are lowered to integers.
8069             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8070
8071         if (InRegCount > 2) {
8072           report_fatal_error("Nest register in use - reduce number of inreg"
8073                              " parameters!");
8074         }
8075       }
8076       break;
8077     }
8078     case CallingConv::X86_FastCall:
8079     case CallingConv::X86_ThisCall:
8080     case CallingConv::Fast:
8081       // Pass 'nest' parameter in EAX.
8082       // Must be kept in sync with X86CallingConv.td
8083       NestReg = X86::EAX;
8084       break;
8085     }
8086
8087     SDValue OutChains[4];
8088     SDValue Addr, Disp;
8089
8090     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8091                        DAG.getConstant(10, MVT::i32));
8092     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8093
8094     // This is storing the opcode for MOV32ri.
8095     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8096     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8097     OutChains[0] = DAG.getStore(Root, dl,
8098                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8099                                 Trmp, MachinePointerInfo(TrmpAddr),
8100                                 false, false, 0);
8101
8102     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8103                        DAG.getConstant(1, MVT::i32));
8104     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8105                                 MachinePointerInfo(TrmpAddr, 1),
8106                                 false, false, 1);
8107
8108     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8109     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8110                        DAG.getConstant(5, MVT::i32));
8111     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8112                                 MachinePointerInfo(TrmpAddr, 5),
8113                                 false, false, 1);
8114
8115     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8116                        DAG.getConstant(6, MVT::i32));
8117     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8118                                 MachinePointerInfo(TrmpAddr, 6),
8119                                 false, false, 1);
8120
8121     SDValue Ops[] =
8122       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8123     return DAG.getMergeValues(Ops, 2, dl);
8124   }
8125 }
8126
8127 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8128                                             SelectionDAG &DAG) const {
8129   /*
8130    The rounding mode is in bits 11:10 of FPSR, and has the following
8131    settings:
8132      00 Round to nearest
8133      01 Round to -inf
8134      10 Round to +inf
8135      11 Round to 0
8136
8137   FLT_ROUNDS, on the other hand, expects the following:
8138     -1 Undefined
8139      0 Round to 0
8140      1 Round to nearest
8141      2 Round to +inf
8142      3 Round to -inf
8143
8144   To perform the conversion, we do:
8145     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8146   */
8147
8148   MachineFunction &MF = DAG.getMachineFunction();
8149   const TargetMachine &TM = MF.getTarget();
8150   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8151   unsigned StackAlignment = TFI.getStackAlignment();
8152   EVT VT = Op.getValueType();
8153   DebugLoc dl = Op.getDebugLoc();
8154
8155   // Save FP Control Word to stack slot
8156   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8157   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8158
8159   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
8160                               DAG.getEntryNode(), StackSlot);
8161
8162   // Load FP Control Word from stack slot
8163   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot,
8164                             MachinePointerInfo(), false, false, 0);
8165
8166   // Transform as necessary
8167   SDValue CWD1 =
8168     DAG.getNode(ISD::SRL, dl, MVT::i16,
8169                 DAG.getNode(ISD::AND, dl, MVT::i16,
8170                             CWD, DAG.getConstant(0x800, MVT::i16)),
8171                 DAG.getConstant(11, MVT::i8));
8172   SDValue CWD2 =
8173     DAG.getNode(ISD::SRL, dl, MVT::i16,
8174                 DAG.getNode(ISD::AND, dl, MVT::i16,
8175                             CWD, DAG.getConstant(0x400, MVT::i16)),
8176                 DAG.getConstant(9, MVT::i8));
8177
8178   SDValue RetVal =
8179     DAG.getNode(ISD::AND, dl, MVT::i16,
8180                 DAG.getNode(ISD::ADD, dl, MVT::i16,
8181                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
8182                             DAG.getConstant(1, MVT::i16)),
8183                 DAG.getConstant(3, MVT::i16));
8184
8185
8186   return DAG.getNode((VT.getSizeInBits() < 16 ?
8187                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8188 }
8189
8190 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8191   EVT VT = Op.getValueType();
8192   EVT OpVT = VT;
8193   unsigned NumBits = VT.getSizeInBits();
8194   DebugLoc dl = Op.getDebugLoc();
8195
8196   Op = Op.getOperand(0);
8197   if (VT == MVT::i8) {
8198     // Zero extend to i32 since there is not an i8 bsr.
8199     OpVT = MVT::i32;
8200     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8201   }
8202
8203   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8204   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8205   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8206
8207   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8208   SDValue Ops[] = {
8209     Op,
8210     DAG.getConstant(NumBits+NumBits-1, OpVT),
8211     DAG.getConstant(X86::COND_E, MVT::i8),
8212     Op.getValue(1)
8213   };
8214   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8215
8216   // Finally xor with NumBits-1.
8217   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8218
8219   if (VT == MVT::i8)
8220     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8221   return Op;
8222 }
8223
8224 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8225   EVT VT = Op.getValueType();
8226   EVT OpVT = VT;
8227   unsigned NumBits = VT.getSizeInBits();
8228   DebugLoc dl = Op.getDebugLoc();
8229
8230   Op = Op.getOperand(0);
8231   if (VT == MVT::i8) {
8232     OpVT = MVT::i32;
8233     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8234   }
8235
8236   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8237   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8238   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8239
8240   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8241   SDValue Ops[] = {
8242     Op,
8243     DAG.getConstant(NumBits, OpVT),
8244     DAG.getConstant(X86::COND_E, MVT::i8),
8245     Op.getValue(1)
8246   };
8247   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8248
8249   if (VT == MVT::i8)
8250     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8251   return Op;
8252 }
8253
8254 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8255   EVT VT = Op.getValueType();
8256   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8257   DebugLoc dl = Op.getDebugLoc();
8258
8259   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8260   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8261   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8262   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8263   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8264   //
8265   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8266   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8267   //  return AloBlo + AloBhi + AhiBlo;
8268
8269   SDValue A = Op.getOperand(0);
8270   SDValue B = Op.getOperand(1);
8271
8272   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8273                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8274                        A, DAG.getConstant(32, MVT::i32));
8275   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8276                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8277                        B, DAG.getConstant(32, MVT::i32));
8278   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8279                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8280                        A, B);
8281   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8282                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8283                        A, Bhi);
8284   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8285                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8286                        Ahi, B);
8287   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8288                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8289                        AloBhi, DAG.getConstant(32, MVT::i32));
8290   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8291                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8292                        AhiBlo, DAG.getConstant(32, MVT::i32));
8293   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8294   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8295   return Res;
8296 }
8297
8298 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8299   EVT VT = Op.getValueType();
8300   DebugLoc dl = Op.getDebugLoc();
8301   SDValue R = Op.getOperand(0);
8302
8303   LLVMContext *Context = DAG.getContext();
8304
8305   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8306
8307   if (VT == MVT::v4i32) {
8308     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8309                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8310                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8311
8312     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8313     
8314     std::vector<Constant*> CV(4, CI);
8315     Constant *C = ConstantVector::get(CV);
8316     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8317     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8318                                  MachinePointerInfo::getConstantPool(),
8319                                  false, false, 16);
8320
8321     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8322     Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8323     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8324     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8325   }
8326   if (VT == MVT::v16i8) {
8327     // a = a << 5;
8328     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8329                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8330                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8331
8332     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8333     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8334
8335     std::vector<Constant*> CVM1(16, CM1);
8336     std::vector<Constant*> CVM2(16, CM2);
8337     Constant *C = ConstantVector::get(CVM1);
8338     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8339     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8340                             MachinePointerInfo::getConstantPool(),
8341                             false, false, 16);
8342
8343     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8344     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8345     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8346                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8347                     DAG.getConstant(4, MVT::i32));
8348     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8349                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8350                     R, M, Op);
8351     // a += a
8352     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8353     
8354     C = ConstantVector::get(CVM2);
8355     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8356     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8357                     MachinePointerInfo::getConstantPool(),
8358                     false, false, 16);
8359     
8360     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8361     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8362     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8363                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8364                     DAG.getConstant(2, MVT::i32));
8365     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8366                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8367                     R, M, Op);
8368     // a += a
8369     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8370     
8371     // return pblendv(r, r+r, a);
8372     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8373                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8374                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8375     return R;
8376   }
8377   return SDValue();
8378 }
8379
8380 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8381   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8382   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8383   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8384   // has only one use.
8385   SDNode *N = Op.getNode();
8386   SDValue LHS = N->getOperand(0);
8387   SDValue RHS = N->getOperand(1);
8388   unsigned BaseOp = 0;
8389   unsigned Cond = 0;
8390   DebugLoc dl = Op.getDebugLoc();
8391
8392   switch (Op.getOpcode()) {
8393   default: llvm_unreachable("Unknown ovf instruction!");
8394   case ISD::SADDO:
8395     // A subtract of one will be selected as a INC. Note that INC doesn't
8396     // set CF, so we can't do this for UADDO.
8397     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8398       if (C->getAPIntValue() == 1) {
8399         BaseOp = X86ISD::INC;
8400         Cond = X86::COND_O;
8401         break;
8402       }
8403     BaseOp = X86ISD::ADD;
8404     Cond = X86::COND_O;
8405     break;
8406   case ISD::UADDO:
8407     BaseOp = X86ISD::ADD;
8408     Cond = X86::COND_B;
8409     break;
8410   case ISD::SSUBO:
8411     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8412     // set CF, so we can't do this for USUBO.
8413     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8414       if (C->getAPIntValue() == 1) {
8415         BaseOp = X86ISD::DEC;
8416         Cond = X86::COND_O;
8417         break;
8418       }
8419     BaseOp = X86ISD::SUB;
8420     Cond = X86::COND_O;
8421     break;
8422   case ISD::USUBO:
8423     BaseOp = X86ISD::SUB;
8424     Cond = X86::COND_B;
8425     break;
8426   case ISD::SMULO:
8427     BaseOp = X86ISD::SMUL;
8428     Cond = X86::COND_O;
8429     break;
8430   case ISD::UMULO:
8431     BaseOp = X86ISD::UMUL;
8432     Cond = X86::COND_B;
8433     break;
8434   }
8435
8436   // Also sets EFLAGS.
8437   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8438   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8439
8440   SDValue SetCC =
8441     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8442                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8443
8444   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8445   return Sum;
8446 }
8447
8448 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8449   DebugLoc dl = Op.getDebugLoc();
8450   
8451   if (!Subtarget->hasSSE2()) {
8452     SDValue Chain = Op.getOperand(0);
8453     SDValue Zero = DAG.getConstant(0, 
8454                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8455     SDValue Ops[] = {
8456       DAG.getRegister(X86::ESP, MVT::i32), // Base
8457       DAG.getTargetConstant(1, MVT::i8),   // Scale
8458       DAG.getRegister(0, MVT::i32),        // Index
8459       DAG.getTargetConstant(0, MVT::i32),  // Disp
8460       DAG.getRegister(0, MVT::i32),        // Segment.
8461       Zero,
8462       Chain
8463     };
8464     SDNode *Res = 
8465       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8466                           array_lengthof(Ops));
8467     return SDValue(Res, 0);
8468   }
8469   
8470   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8471   if (!isDev)
8472     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8473   
8474   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8475   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8476   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8477   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8478   
8479   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8480   if (!Op1 && !Op2 && !Op3 && Op4)
8481     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8482   
8483   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8484   if (Op1 && !Op2 && !Op3 && !Op4)
8485     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8486   
8487   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 
8488   //           (MFENCE)>;
8489   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8490 }
8491
8492 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8493   EVT T = Op.getValueType();
8494   DebugLoc dl = Op.getDebugLoc();
8495   unsigned Reg = 0;
8496   unsigned size = 0;
8497   switch(T.getSimpleVT().SimpleTy) {
8498   default:
8499     assert(false && "Invalid value type!");
8500   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8501   case MVT::i16: Reg = X86::AX;  size = 2; break;
8502   case MVT::i32: Reg = X86::EAX; size = 4; break;
8503   case MVT::i64:
8504     assert(Subtarget->is64Bit() && "Node not type legal!");
8505     Reg = X86::RAX; size = 8;
8506     break;
8507   }
8508   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
8509                                     Op.getOperand(2), SDValue());
8510   SDValue Ops[] = { cpIn.getValue(0),
8511                     Op.getOperand(1),
8512                     Op.getOperand(3),
8513                     DAG.getTargetConstant(size, MVT::i8),
8514                     cpIn.getValue(1) };
8515   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8516   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
8517   SDValue cpOut =
8518     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
8519   return cpOut;
8520 }
8521
8522 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8523                                                  SelectionDAG &DAG) const {
8524   assert(Subtarget->is64Bit() && "Result not type legalized?");
8525   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8526   SDValue TheChain = Op.getOperand(0);
8527   DebugLoc dl = Op.getDebugLoc();
8528   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8529   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8530   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8531                                    rax.getValue(2));
8532   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8533                             DAG.getConstant(32, MVT::i8));
8534   SDValue Ops[] = {
8535     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8536     rdx.getValue(1)
8537   };
8538   return DAG.getMergeValues(Ops, 2, dl);
8539 }
8540
8541 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8542                                             SelectionDAG &DAG) const {
8543   EVT SrcVT = Op.getOperand(0).getValueType();
8544   EVT DstVT = Op.getValueType();
8545   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
8546           Subtarget->hasMMX() && !DisableMMX) &&
8547          "Unexpected custom BIT_CONVERT");
8548   assert((DstVT == MVT::i64 || 
8549           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8550          "Unexpected custom BIT_CONVERT");
8551   // i64 <=> MMX conversions are Legal.
8552   if (SrcVT==MVT::i64 && DstVT.isVector())
8553     return Op;
8554   if (DstVT==MVT::i64 && SrcVT.isVector())
8555     return Op;
8556   // MMX <=> MMX conversions are Legal.
8557   if (SrcVT.isVector() && DstVT.isVector())
8558     return Op;
8559   // All other conversions need to be expanded.
8560   return SDValue();
8561 }
8562 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8563   SDNode *Node = Op.getNode();
8564   DebugLoc dl = Node->getDebugLoc();
8565   EVT T = Node->getValueType(0);
8566   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8567                               DAG.getConstant(0, T), Node->getOperand(2));
8568   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8569                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8570                        Node->getOperand(0),
8571                        Node->getOperand(1), negOp,
8572                        cast<AtomicSDNode>(Node)->getSrcValue(),
8573                        cast<AtomicSDNode>(Node)->getAlignment());
8574 }
8575
8576 /// LowerOperation - Provide custom lowering hooks for some operations.
8577 ///
8578 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8579   switch (Op.getOpcode()) {
8580   default: llvm_unreachable("Should not custom lower this!");
8581   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8582   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8583   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8584   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8585   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8586   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8587   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8588   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8589   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8590   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8591   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8592   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8593   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8594   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8595   case ISD::SHL_PARTS:
8596   case ISD::SRA_PARTS:
8597   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8598   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8599   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8600   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8601   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8602   case ISD::FABS:               return LowerFABS(Op, DAG);
8603   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8604   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8605   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8606   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8607   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8608   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8609   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8610   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8611   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8612   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8613   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8614   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8615   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8616   case ISD::FRAME_TO_ARGS_OFFSET:
8617                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8618   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8619   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8620   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8621   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8622   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8623   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8624   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8625   case ISD::SHL:                return LowerSHL(Op, DAG);
8626   case ISD::SADDO:
8627   case ISD::UADDO:
8628   case ISD::SSUBO:
8629   case ISD::USUBO:
8630   case ISD::SMULO:
8631   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8632   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8633   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
8634   }
8635 }
8636
8637 void X86TargetLowering::
8638 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8639                         SelectionDAG &DAG, unsigned NewOp) const {
8640   EVT T = Node->getValueType(0);
8641   DebugLoc dl = Node->getDebugLoc();
8642   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8643
8644   SDValue Chain = Node->getOperand(0);
8645   SDValue In1 = Node->getOperand(1);
8646   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8647                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8648   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8649                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8650   SDValue Ops[] = { Chain, In1, In2L, In2H };
8651   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8652   SDValue Result =
8653     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8654                             cast<MemSDNode>(Node)->getMemOperand());
8655   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8656   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8657   Results.push_back(Result.getValue(2));
8658 }
8659
8660 /// ReplaceNodeResults - Replace a node with an illegal result type
8661 /// with a new node built out of custom code.
8662 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8663                                            SmallVectorImpl<SDValue>&Results,
8664                                            SelectionDAG &DAG) const {
8665   DebugLoc dl = N->getDebugLoc();
8666   switch (N->getOpcode()) {
8667   default:
8668     assert(false && "Do not know how to custom type legalize this operation!");
8669     return;
8670   case ISD::FP_TO_SINT: {
8671     std::pair<SDValue,SDValue> Vals =
8672         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8673     SDValue FIST = Vals.first, StackSlot = Vals.second;
8674     if (FIST.getNode() != 0) {
8675       EVT VT = N->getValueType(0);
8676       // Return a load from the stack slot.
8677       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8678                                     MachinePointerInfo(), false, false, 0));
8679     }
8680     return;
8681   }
8682   case ISD::READCYCLECOUNTER: {
8683     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8684     SDValue TheChain = N->getOperand(0);
8685     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8686     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8687                                      rd.getValue(1));
8688     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8689                                      eax.getValue(2));
8690     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8691     SDValue Ops[] = { eax, edx };
8692     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8693     Results.push_back(edx.getValue(1));
8694     return;
8695   }
8696   case ISD::ATOMIC_CMP_SWAP: {
8697     EVT T = N->getValueType(0);
8698     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8699     SDValue cpInL, cpInH;
8700     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8701                         DAG.getConstant(0, MVT::i32));
8702     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8703                         DAG.getConstant(1, MVT::i32));
8704     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8705     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8706                              cpInL.getValue(1));
8707     SDValue swapInL, swapInH;
8708     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8709                           DAG.getConstant(0, MVT::i32));
8710     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8711                           DAG.getConstant(1, MVT::i32));
8712     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8713                                cpInH.getValue(1));
8714     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8715                                swapInL.getValue(1));
8716     SDValue Ops[] = { swapInH.getValue(0),
8717                       N->getOperand(1),
8718                       swapInH.getValue(1) };
8719     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8720     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8721     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8722                                         MVT::i32, Result.getValue(1));
8723     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8724                                         MVT::i32, cpOutL.getValue(2));
8725     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8726     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8727     Results.push_back(cpOutH.getValue(1));
8728     return;
8729   }
8730   case ISD::ATOMIC_LOAD_ADD:
8731     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8732     return;
8733   case ISD::ATOMIC_LOAD_AND:
8734     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8735     return;
8736   case ISD::ATOMIC_LOAD_NAND:
8737     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8738     return;
8739   case ISD::ATOMIC_LOAD_OR:
8740     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8741     return;
8742   case ISD::ATOMIC_LOAD_SUB:
8743     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8744     return;
8745   case ISD::ATOMIC_LOAD_XOR:
8746     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8747     return;
8748   case ISD::ATOMIC_SWAP:
8749     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8750     return;
8751   }
8752 }
8753
8754 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8755   switch (Opcode) {
8756   default: return NULL;
8757   case X86ISD::BSF:                return "X86ISD::BSF";
8758   case X86ISD::BSR:                return "X86ISD::BSR";
8759   case X86ISD::SHLD:               return "X86ISD::SHLD";
8760   case X86ISD::SHRD:               return "X86ISD::SHRD";
8761   case X86ISD::FAND:               return "X86ISD::FAND";
8762   case X86ISD::FOR:                return "X86ISD::FOR";
8763   case X86ISD::FXOR:               return "X86ISD::FXOR";
8764   case X86ISD::FSRL:               return "X86ISD::FSRL";
8765   case X86ISD::FILD:               return "X86ISD::FILD";
8766   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8767   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8768   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8769   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8770   case X86ISD::FLD:                return "X86ISD::FLD";
8771   case X86ISD::FST:                return "X86ISD::FST";
8772   case X86ISD::CALL:               return "X86ISD::CALL";
8773   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8774   case X86ISD::BT:                 return "X86ISD::BT";
8775   case X86ISD::CMP:                return "X86ISD::CMP";
8776   case X86ISD::COMI:               return "X86ISD::COMI";
8777   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8778   case X86ISD::SETCC:              return "X86ISD::SETCC";
8779   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8780   case X86ISD::CMOV:               return "X86ISD::CMOV";
8781   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8782   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8783   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8784   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8785   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8786   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8787   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8788   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8789   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8790   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8791   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8792   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8793   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
8794   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8795   case X86ISD::FMAX:               return "X86ISD::FMAX";
8796   case X86ISD::FMIN:               return "X86ISD::FMIN";
8797   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8798   case X86ISD::FRCP:               return "X86ISD::FRCP";
8799   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8800   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8801   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
8802   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8803   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8804   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8805   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8806   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8807   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8808   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8809   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8810   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8811   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8812   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8813   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8814   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8815   case X86ISD::VSHL:               return "X86ISD::VSHL";
8816   case X86ISD::VSRL:               return "X86ISD::VSRL";
8817   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8818   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8819   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8820   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8821   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8822   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8823   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8824   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8825   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8826   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8827   case X86ISD::ADD:                return "X86ISD::ADD";
8828   case X86ISD::SUB:                return "X86ISD::SUB";
8829   case X86ISD::SMUL:               return "X86ISD::SMUL";
8830   case X86ISD::UMUL:               return "X86ISD::UMUL";
8831   case X86ISD::INC:                return "X86ISD::INC";
8832   case X86ISD::DEC:                return "X86ISD::DEC";
8833   case X86ISD::OR:                 return "X86ISD::OR";
8834   case X86ISD::XOR:                return "X86ISD::XOR";
8835   case X86ISD::AND:                return "X86ISD::AND";
8836   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8837   case X86ISD::PTEST:              return "X86ISD::PTEST";
8838   case X86ISD::TESTP:              return "X86ISD::TESTP";
8839   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8840   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8841   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8842   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8843   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8844   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8845   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8846   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8847   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8848   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8849   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8850   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8851   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8852   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8853   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8854   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8855   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8856   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8857   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8858   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8859   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8860   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8861   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8862   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8863   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8864   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8865   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8866   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8867   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8868   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8869   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8870   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8871   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8872   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8873   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
8874   }
8875 }
8876
8877 // isLegalAddressingMode - Return true if the addressing mode represented
8878 // by AM is legal for this target, for a load/store of the specified type.
8879 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8880                                               const Type *Ty) const {
8881   // X86 supports extremely general addressing modes.
8882   CodeModel::Model M = getTargetMachine().getCodeModel();
8883   Reloc::Model R = getTargetMachine().getRelocationModel();
8884
8885   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8886   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8887     return false;
8888
8889   if (AM.BaseGV) {
8890     unsigned GVFlags =
8891       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8892
8893     // If a reference to this global requires an extra load, we can't fold it.
8894     if (isGlobalStubReference(GVFlags))
8895       return false;
8896
8897     // If BaseGV requires a register for the PIC base, we cannot also have a
8898     // BaseReg specified.
8899     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8900       return false;
8901
8902     // If lower 4G is not available, then we must use rip-relative addressing.
8903     if ((M != CodeModel::Small || R != Reloc::Static) &&
8904         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8905       return false;
8906   }
8907
8908   switch (AM.Scale) {
8909   case 0:
8910   case 1:
8911   case 2:
8912   case 4:
8913   case 8:
8914     // These scales always work.
8915     break;
8916   case 3:
8917   case 5:
8918   case 9:
8919     // These scales are formed with basereg+scalereg.  Only accept if there is
8920     // no basereg yet.
8921     if (AM.HasBaseReg)
8922       return false;
8923     break;
8924   default:  // Other stuff never works.
8925     return false;
8926   }
8927
8928   return true;
8929 }
8930
8931
8932 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8933   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8934     return false;
8935   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8936   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8937   if (NumBits1 <= NumBits2)
8938     return false;
8939   return true;
8940 }
8941
8942 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8943   if (!VT1.isInteger() || !VT2.isInteger())
8944     return false;
8945   unsigned NumBits1 = VT1.getSizeInBits();
8946   unsigned NumBits2 = VT2.getSizeInBits();
8947   if (NumBits1 <= NumBits2)
8948     return false;
8949   return true;
8950 }
8951
8952 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8953   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8954   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8955 }
8956
8957 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8958   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8959   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8960 }
8961
8962 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8963   // i16 instructions are longer (0x66 prefix) and potentially slower.
8964   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8965 }
8966
8967 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8968 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8969 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8970 /// are assumed to be legal.
8971 bool
8972 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8973                                       EVT VT) const {
8974   // Very little shuffling can be done for 64-bit vectors right now.
8975   if (VT.getSizeInBits() == 64)
8976     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8977
8978   // FIXME: pshufb, blends, shifts.
8979   return (VT.getVectorNumElements() == 2 ||
8980           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8981           isMOVLMask(M, VT) ||
8982           isSHUFPMask(M, VT) ||
8983           isPSHUFDMask(M, VT) ||
8984           isPSHUFHWMask(M, VT) ||
8985           isPSHUFLWMask(M, VT) ||
8986           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8987           isUNPCKLMask(M, VT) ||
8988           isUNPCKHMask(M, VT) ||
8989           isUNPCKL_v_undef_Mask(M, VT) ||
8990           isUNPCKH_v_undef_Mask(M, VT));
8991 }
8992
8993 bool
8994 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8995                                           EVT VT) const {
8996   unsigned NumElts = VT.getVectorNumElements();
8997   // FIXME: This collection of masks seems suspect.
8998   if (NumElts == 2)
8999     return true;
9000   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9001     return (isMOVLMask(Mask, VT)  ||
9002             isCommutedMOVLMask(Mask, VT, true) ||
9003             isSHUFPMask(Mask, VT) ||
9004             isCommutedSHUFPMask(Mask, VT));
9005   }
9006   return false;
9007 }
9008
9009 //===----------------------------------------------------------------------===//
9010 //                           X86 Scheduler Hooks
9011 //===----------------------------------------------------------------------===//
9012
9013 // private utility function
9014 MachineBasicBlock *
9015 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9016                                                        MachineBasicBlock *MBB,
9017                                                        unsigned regOpc,
9018                                                        unsigned immOpc,
9019                                                        unsigned LoadOpc,
9020                                                        unsigned CXchgOpc,
9021                                                        unsigned notOpc,
9022                                                        unsigned EAXreg,
9023                                                        TargetRegisterClass *RC,
9024                                                        bool invSrc) const {
9025   // For the atomic bitwise operator, we generate
9026   //   thisMBB:
9027   //   newMBB:
9028   //     ld  t1 = [bitinstr.addr]
9029   //     op  t2 = t1, [bitinstr.val]
9030   //     mov EAX = t1
9031   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9032   //     bz  newMBB
9033   //     fallthrough -->nextMBB
9034   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9035   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9036   MachineFunction::iterator MBBIter = MBB;
9037   ++MBBIter;
9038
9039   /// First build the CFG
9040   MachineFunction *F = MBB->getParent();
9041   MachineBasicBlock *thisMBB = MBB;
9042   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9043   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9044   F->insert(MBBIter, newMBB);
9045   F->insert(MBBIter, nextMBB);
9046
9047   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9048   nextMBB->splice(nextMBB->begin(), thisMBB,
9049                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9050                   thisMBB->end());
9051   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9052
9053   // Update thisMBB to fall through to newMBB
9054   thisMBB->addSuccessor(newMBB);
9055
9056   // newMBB jumps to itself and fall through to nextMBB
9057   newMBB->addSuccessor(nextMBB);
9058   newMBB->addSuccessor(newMBB);
9059
9060   // Insert instructions into newMBB based on incoming instruction
9061   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9062          "unexpected number of operands");
9063   DebugLoc dl = bInstr->getDebugLoc();
9064   MachineOperand& destOper = bInstr->getOperand(0);
9065   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9066   int numArgs = bInstr->getNumOperands() - 1;
9067   for (int i=0; i < numArgs; ++i)
9068     argOpers[i] = &bInstr->getOperand(i+1);
9069
9070   // x86 address has 4 operands: base, index, scale, and displacement
9071   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9072   int valArgIndx = lastAddrIndx + 1;
9073
9074   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9075   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9076   for (int i=0; i <= lastAddrIndx; ++i)
9077     (*MIB).addOperand(*argOpers[i]);
9078
9079   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9080   if (invSrc) {
9081     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9082   }
9083   else
9084     tt = t1;
9085
9086   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9087   assert((argOpers[valArgIndx]->isReg() ||
9088           argOpers[valArgIndx]->isImm()) &&
9089          "invalid operand");
9090   if (argOpers[valArgIndx]->isReg())
9091     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9092   else
9093     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9094   MIB.addReg(tt);
9095   (*MIB).addOperand(*argOpers[valArgIndx]);
9096
9097   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9098   MIB.addReg(t1);
9099
9100   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9101   for (int i=0; i <= lastAddrIndx; ++i)
9102     (*MIB).addOperand(*argOpers[i]);
9103   MIB.addReg(t2);
9104   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9105   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9106                     bInstr->memoperands_end());
9107
9108   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9109   MIB.addReg(EAXreg);
9110
9111   // insert branch
9112   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9113
9114   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9115   return nextMBB;
9116 }
9117
9118 // private utility function:  64 bit atomics on 32 bit host.
9119 MachineBasicBlock *
9120 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9121                                                        MachineBasicBlock *MBB,
9122                                                        unsigned regOpcL,
9123                                                        unsigned regOpcH,
9124                                                        unsigned immOpcL,
9125                                                        unsigned immOpcH,
9126                                                        bool invSrc) const {
9127   // For the atomic bitwise operator, we generate
9128   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9129   //     ld t1,t2 = [bitinstr.addr]
9130   //   newMBB:
9131   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9132   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9133   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9134   //     mov ECX, EBX <- t5, t6
9135   //     mov EAX, EDX <- t1, t2
9136   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9137   //     mov t3, t4 <- EAX, EDX
9138   //     bz  newMBB
9139   //     result in out1, out2
9140   //     fallthrough -->nextMBB
9141
9142   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9143   const unsigned LoadOpc = X86::MOV32rm;
9144   const unsigned NotOpc = X86::NOT32r;
9145   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9146   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9147   MachineFunction::iterator MBBIter = MBB;
9148   ++MBBIter;
9149
9150   /// First build the CFG
9151   MachineFunction *F = MBB->getParent();
9152   MachineBasicBlock *thisMBB = MBB;
9153   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9154   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9155   F->insert(MBBIter, newMBB);
9156   F->insert(MBBIter, nextMBB);
9157
9158   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9159   nextMBB->splice(nextMBB->begin(), thisMBB,
9160                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9161                   thisMBB->end());
9162   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9163
9164   // Update thisMBB to fall through to newMBB
9165   thisMBB->addSuccessor(newMBB);
9166
9167   // newMBB jumps to itself and fall through to nextMBB
9168   newMBB->addSuccessor(nextMBB);
9169   newMBB->addSuccessor(newMBB);
9170
9171   DebugLoc dl = bInstr->getDebugLoc();
9172   // Insert instructions into newMBB based on incoming instruction
9173   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9174   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9175          "unexpected number of operands");
9176   MachineOperand& dest1Oper = bInstr->getOperand(0);
9177   MachineOperand& dest2Oper = bInstr->getOperand(1);
9178   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9179   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9180     argOpers[i] = &bInstr->getOperand(i+2);
9181
9182     // We use some of the operands multiple times, so conservatively just
9183     // clear any kill flags that might be present.
9184     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9185       argOpers[i]->setIsKill(false);
9186   }
9187
9188   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9189   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9190
9191   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9192   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9193   for (int i=0; i <= lastAddrIndx; ++i)
9194     (*MIB).addOperand(*argOpers[i]);
9195   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9196   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9197   // add 4 to displacement.
9198   for (int i=0; i <= lastAddrIndx-2; ++i)
9199     (*MIB).addOperand(*argOpers[i]);
9200   MachineOperand newOp3 = *(argOpers[3]);
9201   if (newOp3.isImm())
9202     newOp3.setImm(newOp3.getImm()+4);
9203   else
9204     newOp3.setOffset(newOp3.getOffset()+4);
9205   (*MIB).addOperand(newOp3);
9206   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9207
9208   // t3/4 are defined later, at the bottom of the loop
9209   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9210   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9211   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9212     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9213   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9214     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9215
9216   // The subsequent operations should be using the destination registers of
9217   //the PHI instructions.
9218   if (invSrc) {
9219     t1 = F->getRegInfo().createVirtualRegister(RC);
9220     t2 = F->getRegInfo().createVirtualRegister(RC);
9221     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9222     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9223   } else {
9224     t1 = dest1Oper.getReg();
9225     t2 = dest2Oper.getReg();
9226   }
9227
9228   int valArgIndx = lastAddrIndx + 1;
9229   assert((argOpers[valArgIndx]->isReg() ||
9230           argOpers[valArgIndx]->isImm()) &&
9231          "invalid operand");
9232   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9233   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9234   if (argOpers[valArgIndx]->isReg())
9235     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9236   else
9237     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9238   if (regOpcL != X86::MOV32rr)
9239     MIB.addReg(t1);
9240   (*MIB).addOperand(*argOpers[valArgIndx]);
9241   assert(argOpers[valArgIndx + 1]->isReg() ==
9242          argOpers[valArgIndx]->isReg());
9243   assert(argOpers[valArgIndx + 1]->isImm() ==
9244          argOpers[valArgIndx]->isImm());
9245   if (argOpers[valArgIndx + 1]->isReg())
9246     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9247   else
9248     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9249   if (regOpcH != X86::MOV32rr)
9250     MIB.addReg(t2);
9251   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9252
9253   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9254   MIB.addReg(t1);
9255   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9256   MIB.addReg(t2);
9257
9258   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9259   MIB.addReg(t5);
9260   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9261   MIB.addReg(t6);
9262
9263   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9264   for (int i=0; i <= lastAddrIndx; ++i)
9265     (*MIB).addOperand(*argOpers[i]);
9266
9267   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9268   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9269                     bInstr->memoperands_end());
9270
9271   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9272   MIB.addReg(X86::EAX);
9273   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9274   MIB.addReg(X86::EDX);
9275
9276   // insert branch
9277   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9278
9279   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9280   return nextMBB;
9281 }
9282
9283 // private utility function
9284 MachineBasicBlock *
9285 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9286                                                       MachineBasicBlock *MBB,
9287                                                       unsigned cmovOpc) const {
9288   // For the atomic min/max operator, we generate
9289   //   thisMBB:
9290   //   newMBB:
9291   //     ld t1 = [min/max.addr]
9292   //     mov t2 = [min/max.val]
9293   //     cmp  t1, t2
9294   //     cmov[cond] t2 = t1
9295   //     mov EAX = t1
9296   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9297   //     bz   newMBB
9298   //     fallthrough -->nextMBB
9299   //
9300   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9301   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9302   MachineFunction::iterator MBBIter = MBB;
9303   ++MBBIter;
9304
9305   /// First build the CFG
9306   MachineFunction *F = MBB->getParent();
9307   MachineBasicBlock *thisMBB = MBB;
9308   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9309   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9310   F->insert(MBBIter, newMBB);
9311   F->insert(MBBIter, nextMBB);
9312
9313   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9314   nextMBB->splice(nextMBB->begin(), thisMBB,
9315                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9316                   thisMBB->end());
9317   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9318
9319   // Update thisMBB to fall through to newMBB
9320   thisMBB->addSuccessor(newMBB);
9321
9322   // newMBB jumps to newMBB and fall through to nextMBB
9323   newMBB->addSuccessor(nextMBB);
9324   newMBB->addSuccessor(newMBB);
9325
9326   DebugLoc dl = mInstr->getDebugLoc();
9327   // Insert instructions into newMBB based on incoming instruction
9328   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9329          "unexpected number of operands");
9330   MachineOperand& destOper = mInstr->getOperand(0);
9331   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9332   int numArgs = mInstr->getNumOperands() - 1;
9333   for (int i=0; i < numArgs; ++i)
9334     argOpers[i] = &mInstr->getOperand(i+1);
9335
9336   // x86 address has 4 operands: base, index, scale, and displacement
9337   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9338   int valArgIndx = lastAddrIndx + 1;
9339
9340   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9341   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9342   for (int i=0; i <= lastAddrIndx; ++i)
9343     (*MIB).addOperand(*argOpers[i]);
9344
9345   // We only support register and immediate values
9346   assert((argOpers[valArgIndx]->isReg() ||
9347           argOpers[valArgIndx]->isImm()) &&
9348          "invalid operand");
9349
9350   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9351   if (argOpers[valArgIndx]->isReg())
9352     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9353   else
9354     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9355   (*MIB).addOperand(*argOpers[valArgIndx]);
9356
9357   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9358   MIB.addReg(t1);
9359
9360   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9361   MIB.addReg(t1);
9362   MIB.addReg(t2);
9363
9364   // Generate movc
9365   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9366   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9367   MIB.addReg(t2);
9368   MIB.addReg(t1);
9369
9370   // Cmp and exchange if none has modified the memory location
9371   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9372   for (int i=0; i <= lastAddrIndx; ++i)
9373     (*MIB).addOperand(*argOpers[i]);
9374   MIB.addReg(t3);
9375   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9376   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9377                     mInstr->memoperands_end());
9378
9379   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9380   MIB.addReg(X86::EAX);
9381
9382   // insert branch
9383   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9384
9385   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9386   return nextMBB;
9387 }
9388
9389 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9390 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9391 // in the .td file.
9392 MachineBasicBlock *
9393 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9394                             unsigned numArgs, bool memArg) const {
9395
9396   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9397          "Target must have SSE4.2 or AVX features enabled");
9398
9399   DebugLoc dl = MI->getDebugLoc();
9400   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9401
9402   unsigned Opc;
9403
9404   if (!Subtarget->hasAVX()) {
9405     if (memArg)
9406       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9407     else
9408       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9409   } else {
9410     if (memArg)
9411       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9412     else
9413       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9414   }
9415
9416   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9417
9418   for (unsigned i = 0; i < numArgs; ++i) {
9419     MachineOperand &Op = MI->getOperand(i+1);
9420
9421     if (!(Op.isReg() && Op.isImplicit()))
9422       MIB.addOperand(Op);
9423   }
9424
9425   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9426     .addReg(X86::XMM0);
9427
9428   MI->eraseFromParent();
9429
9430   return BB;
9431 }
9432
9433 MachineBasicBlock *
9434 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9435                                                  MachineInstr *MI,
9436                                                  MachineBasicBlock *MBB) const {
9437   // Emit code to save XMM registers to the stack. The ABI says that the
9438   // number of registers to save is given in %al, so it's theoretically
9439   // possible to do an indirect jump trick to avoid saving all of them,
9440   // however this code takes a simpler approach and just executes all
9441   // of the stores if %al is non-zero. It's less code, and it's probably
9442   // easier on the hardware branch predictor, and stores aren't all that
9443   // expensive anyway.
9444
9445   // Create the new basic blocks. One block contains all the XMM stores,
9446   // and one block is the final destination regardless of whether any
9447   // stores were performed.
9448   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9449   MachineFunction *F = MBB->getParent();
9450   MachineFunction::iterator MBBIter = MBB;
9451   ++MBBIter;
9452   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9453   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9454   F->insert(MBBIter, XMMSaveMBB);
9455   F->insert(MBBIter, EndMBB);
9456
9457   // Transfer the remainder of MBB and its successor edges to EndMBB.
9458   EndMBB->splice(EndMBB->begin(), MBB,
9459                  llvm::next(MachineBasicBlock::iterator(MI)),
9460                  MBB->end());
9461   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9462
9463   // The original block will now fall through to the XMM save block.
9464   MBB->addSuccessor(XMMSaveMBB);
9465   // The XMMSaveMBB will fall through to the end block.
9466   XMMSaveMBB->addSuccessor(EndMBB);
9467
9468   // Now add the instructions.
9469   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9470   DebugLoc DL = MI->getDebugLoc();
9471
9472   unsigned CountReg = MI->getOperand(0).getReg();
9473   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9474   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9475
9476   if (!Subtarget->isTargetWin64()) {
9477     // If %al is 0, branch around the XMM save block.
9478     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9479     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9480     MBB->addSuccessor(EndMBB);
9481   }
9482
9483   // In the XMM save block, save all the XMM argument registers.
9484   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9485     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9486     MachineMemOperand *MMO =
9487       F->getMachineMemOperand(
9488           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9489         MachineMemOperand::MOStore,
9490         /*Size=*/16, /*Align=*/16);
9491     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9492       .addFrameIndex(RegSaveFrameIndex)
9493       .addImm(/*Scale=*/1)
9494       .addReg(/*IndexReg=*/0)
9495       .addImm(/*Disp=*/Offset)
9496       .addReg(/*Segment=*/0)
9497       .addReg(MI->getOperand(i).getReg())
9498       .addMemOperand(MMO);
9499   }
9500
9501   MI->eraseFromParent();   // The pseudo instruction is gone now.
9502
9503   return EndMBB;
9504 }
9505
9506 MachineBasicBlock *
9507 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9508                                      MachineBasicBlock *BB) const {
9509   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9510   DebugLoc DL = MI->getDebugLoc();
9511
9512   // To "insert" a SELECT_CC instruction, we actually have to insert the
9513   // diamond control-flow pattern.  The incoming instruction knows the
9514   // destination vreg to set, the condition code register to branch on, the
9515   // true/false values to select between, and a branch opcode to use.
9516   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9517   MachineFunction::iterator It = BB;
9518   ++It;
9519
9520   //  thisMBB:
9521   //  ...
9522   //   TrueVal = ...
9523   //   cmpTY ccX, r1, r2
9524   //   bCC copy1MBB
9525   //   fallthrough --> copy0MBB
9526   MachineBasicBlock *thisMBB = BB;
9527   MachineFunction *F = BB->getParent();
9528   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9529   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9530   F->insert(It, copy0MBB);
9531   F->insert(It, sinkMBB);
9532
9533   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9534   // live into the sink and copy blocks.
9535   const MachineFunction *MF = BB->getParent();
9536   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9537   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9538
9539   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9540     const MachineOperand &MO = MI->getOperand(I);
9541     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9542     unsigned Reg = MO.getReg();
9543     if (Reg != X86::EFLAGS) continue;
9544     copy0MBB->addLiveIn(Reg);
9545     sinkMBB->addLiveIn(Reg);
9546   }
9547
9548   // Transfer the remainder of BB and its successor edges to sinkMBB.
9549   sinkMBB->splice(sinkMBB->begin(), BB,
9550                   llvm::next(MachineBasicBlock::iterator(MI)),
9551                   BB->end());
9552   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9553
9554   // Add the true and fallthrough blocks as its successors.
9555   BB->addSuccessor(copy0MBB);
9556   BB->addSuccessor(sinkMBB);
9557
9558   // Create the conditional branch instruction.
9559   unsigned Opc =
9560     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9561   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9562
9563   //  copy0MBB:
9564   //   %FalseValue = ...
9565   //   # fallthrough to sinkMBB
9566   copy0MBB->addSuccessor(sinkMBB);
9567
9568   //  sinkMBB:
9569   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9570   //  ...
9571   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9572           TII->get(X86::PHI), MI->getOperand(0).getReg())
9573     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9574     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9575
9576   MI->eraseFromParent();   // The pseudo instruction is gone now.
9577   return sinkMBB;
9578 }
9579
9580 MachineBasicBlock *
9581 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9582                                           MachineBasicBlock *BB) const {
9583   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9584   DebugLoc DL = MI->getDebugLoc();
9585
9586   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9587   // non-trivial part is impdef of ESP.
9588   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9589   // mingw-w64.
9590
9591   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9592     .addExternalSymbol("_alloca")
9593     .addReg(X86::EAX, RegState::Implicit)
9594     .addReg(X86::ESP, RegState::Implicit)
9595     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9596     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9597     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9598
9599   MI->eraseFromParent();   // The pseudo instruction is gone now.
9600   return BB;
9601 }
9602
9603 MachineBasicBlock *
9604 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9605                                       MachineBasicBlock *BB) const {
9606   // This is pretty easy.  We're taking the value that we received from
9607   // our load from the relocation, sticking it in either RDI (x86-64)
9608   // or EAX and doing an indirect call.  The return value will then
9609   // be in the normal return register.
9610   const X86InstrInfo *TII 
9611     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9612   DebugLoc DL = MI->getDebugLoc();
9613   MachineFunction *F = BB->getParent();
9614   bool IsWin64 = Subtarget->isTargetWin64();
9615   
9616   assert(MI->getOperand(3).isGlobal() && "This should be a global");
9617   
9618   if (Subtarget->is64Bit()) {
9619     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9620                                       TII->get(X86::MOV64rm), X86::RDI)
9621     .addReg(X86::RIP)
9622     .addImm(0).addReg(0)
9623     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9624                       MI->getOperand(3).getTargetFlags())
9625     .addReg(0);
9626     MIB = BuildMI(*BB, MI, DL, TII->get(IsWin64 ? X86::WINCALL64m : X86::CALL64m));
9627     addDirectMem(MIB, X86::RDI);
9628   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9629     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9630                                       TII->get(X86::MOV32rm), X86::EAX)
9631     .addReg(0)
9632     .addImm(0).addReg(0)
9633     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9634                       MI->getOperand(3).getTargetFlags())
9635     .addReg(0);
9636     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9637     addDirectMem(MIB, X86::EAX);
9638   } else {
9639     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9640                                       TII->get(X86::MOV32rm), X86::EAX)
9641     .addReg(TII->getGlobalBaseReg(F))
9642     .addImm(0).addReg(0)
9643     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9644                       MI->getOperand(3).getTargetFlags())
9645     .addReg(0);
9646     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9647     addDirectMem(MIB, X86::EAX);
9648   }
9649   
9650   MI->eraseFromParent(); // The pseudo instruction is gone now.
9651   return BB;
9652 }
9653
9654 MachineBasicBlock *
9655 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9656                                                MachineBasicBlock *BB) const {
9657   switch (MI->getOpcode()) {
9658   default: assert(false && "Unexpected instr type to insert");
9659   case X86::MINGW_ALLOCA:
9660     return EmitLoweredMingwAlloca(MI, BB);
9661   case X86::TLSCall_32:
9662   case X86::TLSCall_64:
9663     return EmitLoweredTLSCall(MI, BB);
9664   case X86::CMOV_GR8:
9665   case X86::CMOV_V1I64:
9666   case X86::CMOV_FR32:
9667   case X86::CMOV_FR64:
9668   case X86::CMOV_V4F32:
9669   case X86::CMOV_V2F64:
9670   case X86::CMOV_V2I64:
9671   case X86::CMOV_GR16:
9672   case X86::CMOV_GR32:
9673   case X86::CMOV_RFP32:
9674   case X86::CMOV_RFP64:
9675   case X86::CMOV_RFP80:
9676     return EmitLoweredSelect(MI, BB);
9677
9678   case X86::FP32_TO_INT16_IN_MEM:
9679   case X86::FP32_TO_INT32_IN_MEM:
9680   case X86::FP32_TO_INT64_IN_MEM:
9681   case X86::FP64_TO_INT16_IN_MEM:
9682   case X86::FP64_TO_INT32_IN_MEM:
9683   case X86::FP64_TO_INT64_IN_MEM:
9684   case X86::FP80_TO_INT16_IN_MEM:
9685   case X86::FP80_TO_INT32_IN_MEM:
9686   case X86::FP80_TO_INT64_IN_MEM: {
9687     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9688     DebugLoc DL = MI->getDebugLoc();
9689
9690     // Change the floating point control register to use "round towards zero"
9691     // mode when truncating to an integer value.
9692     MachineFunction *F = BB->getParent();
9693     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9694     addFrameReference(BuildMI(*BB, MI, DL,
9695                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
9696
9697     // Load the old value of the high byte of the control word...
9698     unsigned OldCW =
9699       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9700     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9701                       CWFrameIdx);
9702
9703     // Set the high part to be round to zero...
9704     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9705       .addImm(0xC7F);
9706
9707     // Reload the modified control word now...
9708     addFrameReference(BuildMI(*BB, MI, DL,
9709                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9710
9711     // Restore the memory image of control word to original value
9712     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9713       .addReg(OldCW);
9714
9715     // Get the X86 opcode to use.
9716     unsigned Opc;
9717     switch (MI->getOpcode()) {
9718     default: llvm_unreachable("illegal opcode!");
9719     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9720     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9721     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9722     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9723     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9724     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9725     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9726     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9727     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9728     }
9729
9730     X86AddressMode AM;
9731     MachineOperand &Op = MI->getOperand(0);
9732     if (Op.isReg()) {
9733       AM.BaseType = X86AddressMode::RegBase;
9734       AM.Base.Reg = Op.getReg();
9735     } else {
9736       AM.BaseType = X86AddressMode::FrameIndexBase;
9737       AM.Base.FrameIndex = Op.getIndex();
9738     }
9739     Op = MI->getOperand(1);
9740     if (Op.isImm())
9741       AM.Scale = Op.getImm();
9742     Op = MI->getOperand(2);
9743     if (Op.isImm())
9744       AM.IndexReg = Op.getImm();
9745     Op = MI->getOperand(3);
9746     if (Op.isGlobal()) {
9747       AM.GV = Op.getGlobal();
9748     } else {
9749       AM.Disp = Op.getImm();
9750     }
9751     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9752                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9753
9754     // Reload the original control word now.
9755     addFrameReference(BuildMI(*BB, MI, DL,
9756                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9757
9758     MI->eraseFromParent();   // The pseudo instruction is gone now.
9759     return BB;
9760   }
9761     // String/text processing lowering.
9762   case X86::PCMPISTRM128REG:
9763   case X86::VPCMPISTRM128REG:
9764     return EmitPCMP(MI, BB, 3, false /* in-mem */);
9765   case X86::PCMPISTRM128MEM:
9766   case X86::VPCMPISTRM128MEM:
9767     return EmitPCMP(MI, BB, 3, true /* in-mem */);
9768   case X86::PCMPESTRM128REG:
9769   case X86::VPCMPESTRM128REG:
9770     return EmitPCMP(MI, BB, 5, false /* in mem */);
9771   case X86::PCMPESTRM128MEM:
9772   case X86::VPCMPESTRM128MEM:
9773     return EmitPCMP(MI, BB, 5, true /* in mem */);
9774
9775     // Atomic Lowering.
9776   case X86::ATOMAND32:
9777     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9778                                                X86::AND32ri, X86::MOV32rm,
9779                                                X86::LCMPXCHG32,
9780                                                X86::NOT32r, X86::EAX,
9781                                                X86::GR32RegisterClass);
9782   case X86::ATOMOR32:
9783     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9784                                                X86::OR32ri, X86::MOV32rm,
9785                                                X86::LCMPXCHG32,
9786                                                X86::NOT32r, X86::EAX,
9787                                                X86::GR32RegisterClass);
9788   case X86::ATOMXOR32:
9789     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9790                                                X86::XOR32ri, X86::MOV32rm,
9791                                                X86::LCMPXCHG32,
9792                                                X86::NOT32r, X86::EAX,
9793                                                X86::GR32RegisterClass);
9794   case X86::ATOMNAND32:
9795     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9796                                                X86::AND32ri, X86::MOV32rm,
9797                                                X86::LCMPXCHG32,
9798                                                X86::NOT32r, X86::EAX,
9799                                                X86::GR32RegisterClass, true);
9800   case X86::ATOMMIN32:
9801     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9802   case X86::ATOMMAX32:
9803     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9804   case X86::ATOMUMIN32:
9805     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9806   case X86::ATOMUMAX32:
9807     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9808
9809   case X86::ATOMAND16:
9810     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9811                                                X86::AND16ri, X86::MOV16rm,
9812                                                X86::LCMPXCHG16,
9813                                                X86::NOT16r, X86::AX,
9814                                                X86::GR16RegisterClass);
9815   case X86::ATOMOR16:
9816     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9817                                                X86::OR16ri, X86::MOV16rm,
9818                                                X86::LCMPXCHG16,
9819                                                X86::NOT16r, X86::AX,
9820                                                X86::GR16RegisterClass);
9821   case X86::ATOMXOR16:
9822     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9823                                                X86::XOR16ri, X86::MOV16rm,
9824                                                X86::LCMPXCHG16,
9825                                                X86::NOT16r, X86::AX,
9826                                                X86::GR16RegisterClass);
9827   case X86::ATOMNAND16:
9828     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9829                                                X86::AND16ri, X86::MOV16rm,
9830                                                X86::LCMPXCHG16,
9831                                                X86::NOT16r, X86::AX,
9832                                                X86::GR16RegisterClass, true);
9833   case X86::ATOMMIN16:
9834     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9835   case X86::ATOMMAX16:
9836     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9837   case X86::ATOMUMIN16:
9838     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9839   case X86::ATOMUMAX16:
9840     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9841
9842   case X86::ATOMAND8:
9843     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9844                                                X86::AND8ri, X86::MOV8rm,
9845                                                X86::LCMPXCHG8,
9846                                                X86::NOT8r, X86::AL,
9847                                                X86::GR8RegisterClass);
9848   case X86::ATOMOR8:
9849     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9850                                                X86::OR8ri, X86::MOV8rm,
9851                                                X86::LCMPXCHG8,
9852                                                X86::NOT8r, X86::AL,
9853                                                X86::GR8RegisterClass);
9854   case X86::ATOMXOR8:
9855     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9856                                                X86::XOR8ri, X86::MOV8rm,
9857                                                X86::LCMPXCHG8,
9858                                                X86::NOT8r, X86::AL,
9859                                                X86::GR8RegisterClass);
9860   case X86::ATOMNAND8:
9861     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9862                                                X86::AND8ri, X86::MOV8rm,
9863                                                X86::LCMPXCHG8,
9864                                                X86::NOT8r, X86::AL,
9865                                                X86::GR8RegisterClass, true);
9866   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9867   // This group is for 64-bit host.
9868   case X86::ATOMAND64:
9869     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9870                                                X86::AND64ri32, X86::MOV64rm,
9871                                                X86::LCMPXCHG64,
9872                                                X86::NOT64r, X86::RAX,
9873                                                X86::GR64RegisterClass);
9874   case X86::ATOMOR64:
9875     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9876                                                X86::OR64ri32, X86::MOV64rm,
9877                                                X86::LCMPXCHG64,
9878                                                X86::NOT64r, X86::RAX,
9879                                                X86::GR64RegisterClass);
9880   case X86::ATOMXOR64:
9881     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9882                                                X86::XOR64ri32, X86::MOV64rm,
9883                                                X86::LCMPXCHG64,
9884                                                X86::NOT64r, X86::RAX,
9885                                                X86::GR64RegisterClass);
9886   case X86::ATOMNAND64:
9887     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9888                                                X86::AND64ri32, X86::MOV64rm,
9889                                                X86::LCMPXCHG64,
9890                                                X86::NOT64r, X86::RAX,
9891                                                X86::GR64RegisterClass, true);
9892   case X86::ATOMMIN64:
9893     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9894   case X86::ATOMMAX64:
9895     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9896   case X86::ATOMUMIN64:
9897     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9898   case X86::ATOMUMAX64:
9899     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9900
9901   // This group does 64-bit operations on a 32-bit host.
9902   case X86::ATOMAND6432:
9903     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9904                                                X86::AND32rr, X86::AND32rr,
9905                                                X86::AND32ri, X86::AND32ri,
9906                                                false);
9907   case X86::ATOMOR6432:
9908     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9909                                                X86::OR32rr, X86::OR32rr,
9910                                                X86::OR32ri, X86::OR32ri,
9911                                                false);
9912   case X86::ATOMXOR6432:
9913     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9914                                                X86::XOR32rr, X86::XOR32rr,
9915                                                X86::XOR32ri, X86::XOR32ri,
9916                                                false);
9917   case X86::ATOMNAND6432:
9918     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9919                                                X86::AND32rr, X86::AND32rr,
9920                                                X86::AND32ri, X86::AND32ri,
9921                                                true);
9922   case X86::ATOMADD6432:
9923     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9924                                                X86::ADD32rr, X86::ADC32rr,
9925                                                X86::ADD32ri, X86::ADC32ri,
9926                                                false);
9927   case X86::ATOMSUB6432:
9928     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9929                                                X86::SUB32rr, X86::SBB32rr,
9930                                                X86::SUB32ri, X86::SBB32ri,
9931                                                false);
9932   case X86::ATOMSWAP6432:
9933     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9934                                                X86::MOV32rr, X86::MOV32rr,
9935                                                X86::MOV32ri, X86::MOV32ri,
9936                                                false);
9937   case X86::VASTART_SAVE_XMM_REGS:
9938     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9939   }
9940 }
9941
9942 //===----------------------------------------------------------------------===//
9943 //                           X86 Optimization Hooks
9944 //===----------------------------------------------------------------------===//
9945
9946 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9947                                                        const APInt &Mask,
9948                                                        APInt &KnownZero,
9949                                                        APInt &KnownOne,
9950                                                        const SelectionDAG &DAG,
9951                                                        unsigned Depth) const {
9952   unsigned Opc = Op.getOpcode();
9953   assert((Opc >= ISD::BUILTIN_OP_END ||
9954           Opc == ISD::INTRINSIC_WO_CHAIN ||
9955           Opc == ISD::INTRINSIC_W_CHAIN ||
9956           Opc == ISD::INTRINSIC_VOID) &&
9957          "Should use MaskedValueIsZero if you don't know whether Op"
9958          " is a target node!");
9959
9960   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
9961   switch (Opc) {
9962   default: break;
9963   case X86ISD::ADD:
9964   case X86ISD::SUB:
9965   case X86ISD::SMUL:
9966   case X86ISD::UMUL:
9967   case X86ISD::INC:
9968   case X86ISD::DEC:
9969   case X86ISD::OR:
9970   case X86ISD::XOR:
9971   case X86ISD::AND:
9972     // These nodes' second result is a boolean.
9973     if (Op.getResNo() == 0)
9974       break;
9975     // Fallthrough
9976   case X86ISD::SETCC:
9977     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9978                                        Mask.getBitWidth() - 1);
9979     break;
9980   }
9981 }
9982
9983 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9984 /// node is a GlobalAddress + offset.
9985 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9986                                        const GlobalValue* &GA,
9987                                        int64_t &Offset) const {
9988   if (N->getOpcode() == X86ISD::Wrapper) {
9989     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9990       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9991       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9992       return true;
9993     }
9994   }
9995   return TargetLowering::isGAPlusOffset(N, GA, Offset);
9996 }
9997
9998 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9999 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10000 /// if the load addresses are consecutive, non-overlapping, and in the right
10001 /// order.
10002 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10003                                      const TargetLowering &TLI) {
10004   DebugLoc dl = N->getDebugLoc();
10005   EVT VT = N->getValueType(0);
10006
10007   if (VT.getSizeInBits() != 128)
10008     return SDValue();
10009
10010   SmallVector<SDValue, 16> Elts;
10011   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10012     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10013
10014   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10015 }
10016
10017 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10018 /// generation and convert it from being a bunch of shuffles and extracts
10019 /// to a simple store and scalar loads to extract the elements.
10020 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10021                                                 const TargetLowering &TLI) {
10022   SDValue InputVector = N->getOperand(0);
10023
10024   // Only operate on vectors of 4 elements, where the alternative shuffling
10025   // gets to be more expensive.
10026   if (InputVector.getValueType() != MVT::v4i32)
10027     return SDValue();
10028
10029   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10030   // single use which is a sign-extend or zero-extend, and all elements are
10031   // used.
10032   SmallVector<SDNode *, 4> Uses;
10033   unsigned ExtractedElements = 0;
10034   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10035        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10036     if (UI.getUse().getResNo() != InputVector.getResNo())
10037       return SDValue();
10038
10039     SDNode *Extract = *UI;
10040     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10041       return SDValue();
10042
10043     if (Extract->getValueType(0) != MVT::i32)
10044       return SDValue();
10045     if (!Extract->hasOneUse())
10046       return SDValue();
10047     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10048         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10049       return SDValue();
10050     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10051       return SDValue();
10052
10053     // Record which element was extracted.
10054     ExtractedElements |=
10055       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10056
10057     Uses.push_back(Extract);
10058   }
10059
10060   // If not all the elements were used, this may not be worthwhile.
10061   if (ExtractedElements != 15)
10062     return SDValue();
10063
10064   // Ok, we've now decided to do the transformation.
10065   DebugLoc dl = InputVector.getDebugLoc();
10066
10067   // Store the value to a temporary stack slot.
10068   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10069   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10070                             MachinePointerInfo(), false, false, 0);
10071
10072   // Replace each use (extract) with a load of the appropriate element.
10073   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10074        UE = Uses.end(); UI != UE; ++UI) {
10075     SDNode *Extract = *UI;
10076
10077     // Compute the element's address.
10078     SDValue Idx = Extract->getOperand(1);
10079     unsigned EltSize =
10080         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10081     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10082     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10083
10084     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10085                                      StackPtr, OffsetVal);
10086
10087     // Load the scalar.
10088     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10089                                      ScalarAddr, MachinePointerInfo(),
10090                                      false, false, 0);
10091
10092     // Replace the exact with the load.
10093     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10094   }
10095
10096   // The replacement was made in place; don't return anything.
10097   return SDValue();
10098 }
10099
10100 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10101 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10102                                     const X86Subtarget *Subtarget) {
10103   DebugLoc DL = N->getDebugLoc();
10104   SDValue Cond = N->getOperand(0);
10105   // Get the LHS/RHS of the select.
10106   SDValue LHS = N->getOperand(1);
10107   SDValue RHS = N->getOperand(2);
10108
10109   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10110   // instructions match the semantics of the common C idiom x<y?x:y but not
10111   // x<=y?x:y, because of how they handle negative zero (which can be
10112   // ignored in unsafe-math mode).
10113   if (Subtarget->hasSSE2() &&
10114       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10115       Cond.getOpcode() == ISD::SETCC) {
10116     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10117
10118     unsigned Opcode = 0;
10119     // Check for x CC y ? x : y.
10120     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10121         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10122       switch (CC) {
10123       default: break;
10124       case ISD::SETULT:
10125         // Converting this to a min would handle NaNs incorrectly, and swapping
10126         // the operands would cause it to handle comparisons between positive
10127         // and negative zero incorrectly.
10128         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10129           if (!UnsafeFPMath &&
10130               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10131             break;
10132           std::swap(LHS, RHS);
10133         }
10134         Opcode = X86ISD::FMIN;
10135         break;
10136       case ISD::SETOLE:
10137         // Converting this to a min would handle comparisons between positive
10138         // and negative zero incorrectly.
10139         if (!UnsafeFPMath &&
10140             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10141           break;
10142         Opcode = X86ISD::FMIN;
10143         break;
10144       case ISD::SETULE:
10145         // Converting this to a min would handle both negative zeros and NaNs
10146         // incorrectly, but we can swap the operands to fix both.
10147         std::swap(LHS, RHS);
10148       case ISD::SETOLT:
10149       case ISD::SETLT:
10150       case ISD::SETLE:
10151         Opcode = X86ISD::FMIN;
10152         break;
10153
10154       case ISD::SETOGE:
10155         // Converting this to a max would handle comparisons between positive
10156         // and negative zero incorrectly.
10157         if (!UnsafeFPMath &&
10158             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10159           break;
10160         Opcode = X86ISD::FMAX;
10161         break;
10162       case ISD::SETUGT:
10163         // Converting this to a max would handle NaNs incorrectly, and swapping
10164         // the operands would cause it to handle comparisons between positive
10165         // and negative zero incorrectly.
10166         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10167           if (!UnsafeFPMath &&
10168               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10169             break;
10170           std::swap(LHS, RHS);
10171         }
10172         Opcode = X86ISD::FMAX;
10173         break;
10174       case ISD::SETUGE:
10175         // Converting this to a max would handle both negative zeros and NaNs
10176         // incorrectly, but we can swap the operands to fix both.
10177         std::swap(LHS, RHS);
10178       case ISD::SETOGT:
10179       case ISD::SETGT:
10180       case ISD::SETGE:
10181         Opcode = X86ISD::FMAX;
10182         break;
10183       }
10184     // Check for x CC y ? y : x -- a min/max with reversed arms.
10185     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10186                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10187       switch (CC) {
10188       default: break;
10189       case ISD::SETOGE:
10190         // Converting this to a min would handle comparisons between positive
10191         // and negative zero incorrectly, and swapping the operands would
10192         // cause it to handle NaNs incorrectly.
10193         if (!UnsafeFPMath &&
10194             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10195           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10196             break;
10197           std::swap(LHS, RHS);
10198         }
10199         Opcode = X86ISD::FMIN;
10200         break;
10201       case ISD::SETUGT:
10202         // Converting this to a min would handle NaNs incorrectly.
10203         if (!UnsafeFPMath &&
10204             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10205           break;
10206         Opcode = X86ISD::FMIN;
10207         break;
10208       case ISD::SETUGE:
10209         // Converting this to a min would handle both negative zeros and NaNs
10210         // incorrectly, but we can swap the operands to fix both.
10211         std::swap(LHS, RHS);
10212       case ISD::SETOGT:
10213       case ISD::SETGT:
10214       case ISD::SETGE:
10215         Opcode = X86ISD::FMIN;
10216         break;
10217
10218       case ISD::SETULT:
10219         // Converting this to a max would handle NaNs incorrectly.
10220         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10221           break;
10222         Opcode = X86ISD::FMAX;
10223         break;
10224       case ISD::SETOLE:
10225         // Converting this to a max would handle comparisons between positive
10226         // and negative zero incorrectly, and swapping the operands would
10227         // cause it to handle NaNs incorrectly.
10228         if (!UnsafeFPMath &&
10229             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10230           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10231             break;
10232           std::swap(LHS, RHS);
10233         }
10234         Opcode = X86ISD::FMAX;
10235         break;
10236       case ISD::SETULE:
10237         // Converting this to a max would handle both negative zeros and NaNs
10238         // incorrectly, but we can swap the operands to fix both.
10239         std::swap(LHS, RHS);
10240       case ISD::SETOLT:
10241       case ISD::SETLT:
10242       case ISD::SETLE:
10243         Opcode = X86ISD::FMAX;
10244         break;
10245       }
10246     }
10247
10248     if (Opcode)
10249       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10250   }
10251
10252   // If this is a select between two integer constants, try to do some
10253   // optimizations.
10254   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10255     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10256       // Don't do this for crazy integer types.
10257       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10258         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10259         // so that TrueC (the true value) is larger than FalseC.
10260         bool NeedsCondInvert = false;
10261
10262         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10263             // Efficiently invertible.
10264             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10265              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10266               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10267           NeedsCondInvert = true;
10268           std::swap(TrueC, FalseC);
10269         }
10270
10271         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10272         if (FalseC->getAPIntValue() == 0 &&
10273             TrueC->getAPIntValue().isPowerOf2()) {
10274           if (NeedsCondInvert) // Invert the condition if needed.
10275             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10276                                DAG.getConstant(1, Cond.getValueType()));
10277
10278           // Zero extend the condition if needed.
10279           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10280
10281           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10282           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10283                              DAG.getConstant(ShAmt, MVT::i8));
10284         }
10285
10286         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10287         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10288           if (NeedsCondInvert) // Invert the condition if needed.
10289             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10290                                DAG.getConstant(1, Cond.getValueType()));
10291
10292           // Zero extend the condition if needed.
10293           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10294                              FalseC->getValueType(0), Cond);
10295           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10296                              SDValue(FalseC, 0));
10297         }
10298
10299         // Optimize cases that will turn into an LEA instruction.  This requires
10300         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10301         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10302           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10303           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10304
10305           bool isFastMultiplier = false;
10306           if (Diff < 10) {
10307             switch ((unsigned char)Diff) {
10308               default: break;
10309               case 1:  // result = add base, cond
10310               case 2:  // result = lea base(    , cond*2)
10311               case 3:  // result = lea base(cond, cond*2)
10312               case 4:  // result = lea base(    , cond*4)
10313               case 5:  // result = lea base(cond, cond*4)
10314               case 8:  // result = lea base(    , cond*8)
10315               case 9:  // result = lea base(cond, cond*8)
10316                 isFastMultiplier = true;
10317                 break;
10318             }
10319           }
10320
10321           if (isFastMultiplier) {
10322             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10323             if (NeedsCondInvert) // Invert the condition if needed.
10324               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10325                                  DAG.getConstant(1, Cond.getValueType()));
10326
10327             // Zero extend the condition if needed.
10328             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10329                                Cond);
10330             // Scale the condition by the difference.
10331             if (Diff != 1)
10332               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10333                                  DAG.getConstant(Diff, Cond.getValueType()));
10334
10335             // Add the base if non-zero.
10336             if (FalseC->getAPIntValue() != 0)
10337               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10338                                  SDValue(FalseC, 0));
10339             return Cond;
10340           }
10341         }
10342       }
10343   }
10344
10345   return SDValue();
10346 }
10347
10348 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10349 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10350                                   TargetLowering::DAGCombinerInfo &DCI) {
10351   DebugLoc DL = N->getDebugLoc();
10352
10353   // If the flag operand isn't dead, don't touch this CMOV.
10354   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10355     return SDValue();
10356
10357   // If this is a select between two integer constants, try to do some
10358   // optimizations.  Note that the operands are ordered the opposite of SELECT
10359   // operands.
10360   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10361     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10362       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10363       // larger than FalseC (the false value).
10364       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10365
10366       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10367         CC = X86::GetOppositeBranchCondition(CC);
10368         std::swap(TrueC, FalseC);
10369       }
10370
10371       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10372       // This is efficient for any integer data type (including i8/i16) and
10373       // shift amount.
10374       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10375         SDValue Cond = N->getOperand(3);
10376         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10377                            DAG.getConstant(CC, MVT::i8), Cond);
10378
10379         // Zero extend the condition if needed.
10380         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10381
10382         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10383         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10384                            DAG.getConstant(ShAmt, MVT::i8));
10385         if (N->getNumValues() == 2)  // Dead flag value?
10386           return DCI.CombineTo(N, Cond, SDValue());
10387         return Cond;
10388       }
10389
10390       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10391       // for any integer data type, including i8/i16.
10392       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10393         SDValue Cond = N->getOperand(3);
10394         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10395                            DAG.getConstant(CC, MVT::i8), Cond);
10396
10397         // Zero extend the condition if needed.
10398         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10399                            FalseC->getValueType(0), Cond);
10400         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10401                            SDValue(FalseC, 0));
10402
10403         if (N->getNumValues() == 2)  // Dead flag value?
10404           return DCI.CombineTo(N, Cond, SDValue());
10405         return Cond;
10406       }
10407
10408       // Optimize cases that will turn into an LEA instruction.  This requires
10409       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10410       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10411         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10412         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10413
10414         bool isFastMultiplier = false;
10415         if (Diff < 10) {
10416           switch ((unsigned char)Diff) {
10417           default: break;
10418           case 1:  // result = add base, cond
10419           case 2:  // result = lea base(    , cond*2)
10420           case 3:  // result = lea base(cond, cond*2)
10421           case 4:  // result = lea base(    , cond*4)
10422           case 5:  // result = lea base(cond, cond*4)
10423           case 8:  // result = lea base(    , cond*8)
10424           case 9:  // result = lea base(cond, cond*8)
10425             isFastMultiplier = true;
10426             break;
10427           }
10428         }
10429
10430         if (isFastMultiplier) {
10431           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10432           SDValue Cond = N->getOperand(3);
10433           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10434                              DAG.getConstant(CC, MVT::i8), Cond);
10435           // Zero extend the condition if needed.
10436           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10437                              Cond);
10438           // Scale the condition by the difference.
10439           if (Diff != 1)
10440             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10441                                DAG.getConstant(Diff, Cond.getValueType()));
10442
10443           // Add the base if non-zero.
10444           if (FalseC->getAPIntValue() != 0)
10445             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10446                                SDValue(FalseC, 0));
10447           if (N->getNumValues() == 2)  // Dead flag value?
10448             return DCI.CombineTo(N, Cond, SDValue());
10449           return Cond;
10450         }
10451       }
10452     }
10453   }
10454   return SDValue();
10455 }
10456
10457 /// PerformAddCombine - Optimize ADD when combined with X86 opcodes.
10458 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
10459                                  TargetLowering::DAGCombinerInfo &DCI) {
10460   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10461     return SDValue();
10462   
10463   EVT VT = N->getValueType(0);
10464   SDValue Op1 = N->getOperand(1);
10465   if (Op1->getOpcode() == ISD::AND) {
10466     SDValue AndOp0 = Op1->getOperand(0);
10467     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 
10468     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
10469     if (AndOp0->getOpcode() == X86ISD::SETCC_CARRY &&
10470         AndOp1 && AndOp1->getZExtValue() == 1) {
10471       DebugLoc DL = N->getDebugLoc();
10472       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
10473     }
10474   }
10475   
10476   return SDValue();
10477 }
10478
10479 /// PerformMulCombine - Optimize a single multiply with constant into two
10480 /// in order to implement it with two cheaper instructions, e.g.
10481 /// LEA + SHL, LEA + LEA.
10482 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10483                                  TargetLowering::DAGCombinerInfo &DCI) {
10484   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10485     return SDValue();
10486
10487   EVT VT = N->getValueType(0);
10488   if (VT != MVT::i64)
10489     return SDValue();
10490
10491   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10492   if (!C)
10493     return SDValue();
10494   uint64_t MulAmt = C->getZExtValue();
10495   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10496     return SDValue();
10497
10498   uint64_t MulAmt1 = 0;
10499   uint64_t MulAmt2 = 0;
10500   if ((MulAmt % 9) == 0) {
10501     MulAmt1 = 9;
10502     MulAmt2 = MulAmt / 9;
10503   } else if ((MulAmt % 5) == 0) {
10504     MulAmt1 = 5;
10505     MulAmt2 = MulAmt / 5;
10506   } else if ((MulAmt % 3) == 0) {
10507     MulAmt1 = 3;
10508     MulAmt2 = MulAmt / 3;
10509   }
10510   if (MulAmt2 &&
10511       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10512     DebugLoc DL = N->getDebugLoc();
10513
10514     if (isPowerOf2_64(MulAmt2) &&
10515         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10516       // If second multiplifer is pow2, issue it first. We want the multiply by
10517       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10518       // is an add.
10519       std::swap(MulAmt1, MulAmt2);
10520
10521     SDValue NewMul;
10522     if (isPowerOf2_64(MulAmt1))
10523       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10524                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10525     else
10526       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10527                            DAG.getConstant(MulAmt1, VT));
10528
10529     if (isPowerOf2_64(MulAmt2))
10530       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10531                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10532     else
10533       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10534                            DAG.getConstant(MulAmt2, VT));
10535
10536     // Do not add new nodes to DAG combiner worklist.
10537     DCI.CombineTo(N, NewMul, false);
10538   }
10539   return SDValue();
10540 }
10541
10542 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10543   SDValue N0 = N->getOperand(0);
10544   SDValue N1 = N->getOperand(1);
10545   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10546   EVT VT = N0.getValueType();
10547
10548   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10549   // since the result of setcc_c is all zero's or all ones.
10550   if (N1C && N0.getOpcode() == ISD::AND &&
10551       N0.getOperand(1).getOpcode() == ISD::Constant) {
10552     SDValue N00 = N0.getOperand(0);
10553     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10554         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10555           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10556          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10557       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10558       APInt ShAmt = N1C->getAPIntValue();
10559       Mask = Mask.shl(ShAmt);
10560       if (Mask != 0)
10561         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10562                            N00, DAG.getConstant(Mask, VT));
10563     }
10564   }
10565
10566   return SDValue();
10567 }
10568
10569 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10570 ///                       when possible.
10571 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10572                                    const X86Subtarget *Subtarget) {
10573   EVT VT = N->getValueType(0);
10574   if (!VT.isVector() && VT.isInteger() &&
10575       N->getOpcode() == ISD::SHL)
10576     return PerformSHLCombine(N, DAG);
10577
10578   // On X86 with SSE2 support, we can transform this to a vector shift if
10579   // all elements are shifted by the same amount.  We can't do this in legalize
10580   // because the a constant vector is typically transformed to a constant pool
10581   // so we have no knowledge of the shift amount.
10582   if (!Subtarget->hasSSE2())
10583     return SDValue();
10584
10585   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10586     return SDValue();
10587
10588   SDValue ShAmtOp = N->getOperand(1);
10589   EVT EltVT = VT.getVectorElementType();
10590   DebugLoc DL = N->getDebugLoc();
10591   SDValue BaseShAmt = SDValue();
10592   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10593     unsigned NumElts = VT.getVectorNumElements();
10594     unsigned i = 0;
10595     for (; i != NumElts; ++i) {
10596       SDValue Arg = ShAmtOp.getOperand(i);
10597       if (Arg.getOpcode() == ISD::UNDEF) continue;
10598       BaseShAmt = Arg;
10599       break;
10600     }
10601     for (; i != NumElts; ++i) {
10602       SDValue Arg = ShAmtOp.getOperand(i);
10603       if (Arg.getOpcode() == ISD::UNDEF) continue;
10604       if (Arg != BaseShAmt) {
10605         return SDValue();
10606       }
10607     }
10608   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10609              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10610     SDValue InVec = ShAmtOp.getOperand(0);
10611     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10612       unsigned NumElts = InVec.getValueType().getVectorNumElements();
10613       unsigned i = 0;
10614       for (; i != NumElts; ++i) {
10615         SDValue Arg = InVec.getOperand(i);
10616         if (Arg.getOpcode() == ISD::UNDEF) continue;
10617         BaseShAmt = Arg;
10618         break;
10619       }
10620     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10621        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10622          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10623          if (C->getZExtValue() == SplatIdx)
10624            BaseShAmt = InVec.getOperand(1);
10625        }
10626     }
10627     if (BaseShAmt.getNode() == 0)
10628       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10629                               DAG.getIntPtrConstant(0));
10630   } else
10631     return SDValue();
10632
10633   // The shift amount is an i32.
10634   if (EltVT.bitsGT(MVT::i32))
10635     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10636   else if (EltVT.bitsLT(MVT::i32))
10637     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10638
10639   // The shift amount is identical so we can do a vector shift.
10640   SDValue  ValOp = N->getOperand(0);
10641   switch (N->getOpcode()) {
10642   default:
10643     llvm_unreachable("Unknown shift opcode!");
10644     break;
10645   case ISD::SHL:
10646     if (VT == MVT::v2i64)
10647       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10648                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10649                          ValOp, BaseShAmt);
10650     if (VT == MVT::v4i32)
10651       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10652                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10653                          ValOp, BaseShAmt);
10654     if (VT == MVT::v8i16)
10655       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10656                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10657                          ValOp, BaseShAmt);
10658     break;
10659   case ISD::SRA:
10660     if (VT == MVT::v4i32)
10661       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10662                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10663                          ValOp, BaseShAmt);
10664     if (VT == MVT::v8i16)
10665       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10666                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10667                          ValOp, BaseShAmt);
10668     break;
10669   case ISD::SRL:
10670     if (VT == MVT::v2i64)
10671       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10672                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10673                          ValOp, BaseShAmt);
10674     if (VT == MVT::v4i32)
10675       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10676                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10677                          ValOp, BaseShAmt);
10678     if (VT ==  MVT::v8i16)
10679       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10680                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10681                          ValOp, BaseShAmt);
10682     break;
10683   }
10684   return SDValue();
10685 }
10686
10687 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10688                                 TargetLowering::DAGCombinerInfo &DCI,
10689                                 const X86Subtarget *Subtarget) {
10690   if (DCI.isBeforeLegalizeOps())
10691     return SDValue();
10692
10693   EVT VT = N->getValueType(0);
10694   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10695     return SDValue();
10696
10697   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10698   SDValue N0 = N->getOperand(0);
10699   SDValue N1 = N->getOperand(1);
10700   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10701     std::swap(N0, N1);
10702   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10703     return SDValue();
10704   if (!N0.hasOneUse() || !N1.hasOneUse())
10705     return SDValue();
10706
10707   SDValue ShAmt0 = N0.getOperand(1);
10708   if (ShAmt0.getValueType() != MVT::i8)
10709     return SDValue();
10710   SDValue ShAmt1 = N1.getOperand(1);
10711   if (ShAmt1.getValueType() != MVT::i8)
10712     return SDValue();
10713   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10714     ShAmt0 = ShAmt0.getOperand(0);
10715   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10716     ShAmt1 = ShAmt1.getOperand(0);
10717
10718   DebugLoc DL = N->getDebugLoc();
10719   unsigned Opc = X86ISD::SHLD;
10720   SDValue Op0 = N0.getOperand(0);
10721   SDValue Op1 = N1.getOperand(0);
10722   if (ShAmt0.getOpcode() == ISD::SUB) {
10723     Opc = X86ISD::SHRD;
10724     std::swap(Op0, Op1);
10725     std::swap(ShAmt0, ShAmt1);
10726   }
10727
10728   unsigned Bits = VT.getSizeInBits();
10729   if (ShAmt1.getOpcode() == ISD::SUB) {
10730     SDValue Sum = ShAmt1.getOperand(0);
10731     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10732       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10733       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10734         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10735       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10736         return DAG.getNode(Opc, DL, VT,
10737                            Op0, Op1,
10738                            DAG.getNode(ISD::TRUNCATE, DL,
10739                                        MVT::i8, ShAmt0));
10740     }
10741   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10742     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10743     if (ShAmt0C &&
10744         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10745       return DAG.getNode(Opc, DL, VT,
10746                          N0.getOperand(0), N1.getOperand(0),
10747                          DAG.getNode(ISD::TRUNCATE, DL,
10748                                        MVT::i8, ShAmt0));
10749   }
10750
10751   return SDValue();
10752 }
10753
10754 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10755 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10756                                    const X86Subtarget *Subtarget) {
10757   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
10758   // the FP state in cases where an emms may be missing.
10759   // A preferable solution to the general problem is to figure out the right
10760   // places to insert EMMS.  This qualifies as a quick hack.
10761
10762   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10763   StoreSDNode *St = cast<StoreSDNode>(N);
10764   EVT VT = St->getValue().getValueType();
10765   if (VT.getSizeInBits() != 64)
10766     return SDValue();
10767
10768   const Function *F = DAG.getMachineFunction().getFunction();
10769   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10770   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10771     && Subtarget->hasSSE2();
10772   if ((VT.isVector() ||
10773        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10774       isa<LoadSDNode>(St->getValue()) &&
10775       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10776       St->getChain().hasOneUse() && !St->isVolatile()) {
10777     SDNode* LdVal = St->getValue().getNode();
10778     LoadSDNode *Ld = 0;
10779     int TokenFactorIndex = -1;
10780     SmallVector<SDValue, 8> Ops;
10781     SDNode* ChainVal = St->getChain().getNode();
10782     // Must be a store of a load.  We currently handle two cases:  the load
10783     // is a direct child, and it's under an intervening TokenFactor.  It is
10784     // possible to dig deeper under nested TokenFactors.
10785     if (ChainVal == LdVal)
10786       Ld = cast<LoadSDNode>(St->getChain());
10787     else if (St->getValue().hasOneUse() &&
10788              ChainVal->getOpcode() == ISD::TokenFactor) {
10789       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10790         if (ChainVal->getOperand(i).getNode() == LdVal) {
10791           TokenFactorIndex = i;
10792           Ld = cast<LoadSDNode>(St->getValue());
10793         } else
10794           Ops.push_back(ChainVal->getOperand(i));
10795       }
10796     }
10797
10798     if (!Ld || !ISD::isNormalLoad(Ld))
10799       return SDValue();
10800
10801     // If this is not the MMX case, i.e. we are just turning i64 load/store
10802     // into f64 load/store, avoid the transformation if there are multiple
10803     // uses of the loaded value.
10804     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10805       return SDValue();
10806
10807     DebugLoc LdDL = Ld->getDebugLoc();
10808     DebugLoc StDL = N->getDebugLoc();
10809     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10810     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10811     // pair instead.
10812     if (Subtarget->is64Bit() || F64IsLegal) {
10813       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10814       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
10815                                   Ld->getPointerInfo(), Ld->isVolatile(),
10816                                   Ld->isNonTemporal(), Ld->getAlignment());
10817       SDValue NewChain = NewLd.getValue(1);
10818       if (TokenFactorIndex != -1) {
10819         Ops.push_back(NewChain);
10820         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10821                                Ops.size());
10822       }
10823       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10824                           St->getPointerInfo(),
10825                           St->isVolatile(), St->isNonTemporal(),
10826                           St->getAlignment());
10827     }
10828
10829     // Otherwise, lower to two pairs of 32-bit loads / stores.
10830     SDValue LoAddr = Ld->getBasePtr();
10831     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10832                                  DAG.getConstant(4, MVT::i32));
10833
10834     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10835                                Ld->getPointerInfo(),
10836                                Ld->isVolatile(), Ld->isNonTemporal(),
10837                                Ld->getAlignment());
10838     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10839                                Ld->getPointerInfo().getWithOffset(4),
10840                                Ld->isVolatile(), Ld->isNonTemporal(),
10841                                MinAlign(Ld->getAlignment(), 4));
10842
10843     SDValue NewChain = LoLd.getValue(1);
10844     if (TokenFactorIndex != -1) {
10845       Ops.push_back(LoLd);
10846       Ops.push_back(HiLd);
10847       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10848                              Ops.size());
10849     }
10850
10851     LoAddr = St->getBasePtr();
10852     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10853                          DAG.getConstant(4, MVT::i32));
10854
10855     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10856                                 St->getPointerInfo(),
10857                                 St->isVolatile(), St->isNonTemporal(),
10858                                 St->getAlignment());
10859     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10860                                 St->getPointerInfo().getWithOffset(4),
10861                                 St->isVolatile(),
10862                                 St->isNonTemporal(),
10863                                 MinAlign(St->getAlignment(), 4));
10864     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10865   }
10866   return SDValue();
10867 }
10868
10869 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10870 /// X86ISD::FXOR nodes.
10871 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10872   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10873   // F[X]OR(0.0, x) -> x
10874   // F[X]OR(x, 0.0) -> x
10875   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10876     if (C->getValueAPF().isPosZero())
10877       return N->getOperand(1);
10878   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10879     if (C->getValueAPF().isPosZero())
10880       return N->getOperand(0);
10881   return SDValue();
10882 }
10883
10884 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10885 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10886   // FAND(0.0, x) -> 0.0
10887   // FAND(x, 0.0) -> 0.0
10888   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10889     if (C->getValueAPF().isPosZero())
10890       return N->getOperand(0);
10891   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10892     if (C->getValueAPF().isPosZero())
10893       return N->getOperand(1);
10894   return SDValue();
10895 }
10896
10897 static SDValue PerformBTCombine(SDNode *N,
10898                                 SelectionDAG &DAG,
10899                                 TargetLowering::DAGCombinerInfo &DCI) {
10900   // BT ignores high bits in the bit index operand.
10901   SDValue Op1 = N->getOperand(1);
10902   if (Op1.hasOneUse()) {
10903     unsigned BitWidth = Op1.getValueSizeInBits();
10904     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10905     APInt KnownZero, KnownOne;
10906     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10907                                           !DCI.isBeforeLegalizeOps());
10908     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10909     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10910         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10911       DCI.CommitTargetLoweringOpt(TLO);
10912   }
10913   return SDValue();
10914 }
10915
10916 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10917   SDValue Op = N->getOperand(0);
10918   if (Op.getOpcode() == ISD::BIT_CONVERT)
10919     Op = Op.getOperand(0);
10920   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10921   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10922       VT.getVectorElementType().getSizeInBits() ==
10923       OpVT.getVectorElementType().getSizeInBits()) {
10924     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10925   }
10926   return SDValue();
10927 }
10928
10929 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10930   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
10931   //           (and (i32 x86isd::setcc_carry), 1)
10932   // This eliminates the zext. This transformation is necessary because
10933   // ISD::SETCC is always legalized to i8.
10934   DebugLoc dl = N->getDebugLoc();
10935   SDValue N0 = N->getOperand(0);
10936   EVT VT = N->getValueType(0);
10937   if (N0.getOpcode() == ISD::AND &&
10938       N0.hasOneUse() &&
10939       N0.getOperand(0).hasOneUse()) {
10940     SDValue N00 = N0.getOperand(0);
10941     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10942       return SDValue();
10943     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10944     if (!C || C->getZExtValue() != 1)
10945       return SDValue();
10946     return DAG.getNode(ISD::AND, dl, VT,
10947                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10948                                    N00.getOperand(0), N00.getOperand(1)),
10949                        DAG.getConstant(1, VT));
10950   }
10951
10952   return SDValue();
10953 }
10954
10955 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10956                                              DAGCombinerInfo &DCI) const {
10957   SelectionDAG &DAG = DCI.DAG;
10958   switch (N->getOpcode()) {
10959   default: break;
10960   case ISD::EXTRACT_VECTOR_ELT:
10961                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10962   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
10963   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
10964   case ISD::ADD:            return PerformAddCombine(N, DAG, DCI);
10965   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
10966   case ISD::SHL:
10967   case ISD::SRA:
10968   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
10969   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
10970   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
10971   case X86ISD::FXOR:
10972   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
10973   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
10974   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
10975   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
10976   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
10977   case X86ISD::SHUFPS:      // Handle all target specific shuffles
10978   case X86ISD::SHUFPD:
10979   case X86ISD::PALIGN:
10980   case X86ISD::PUNPCKHBW:
10981   case X86ISD::PUNPCKHWD:
10982   case X86ISD::PUNPCKHDQ:
10983   case X86ISD::PUNPCKHQDQ:
10984   case X86ISD::UNPCKHPS:
10985   case X86ISD::UNPCKHPD:
10986   case X86ISD::PUNPCKLBW:
10987   case X86ISD::PUNPCKLWD:
10988   case X86ISD::PUNPCKLDQ:
10989   case X86ISD::PUNPCKLQDQ:
10990   case X86ISD::UNPCKLPS:
10991   case X86ISD::UNPCKLPD:
10992   case X86ISD::MOVHLPS:
10993   case X86ISD::MOVLHPS:
10994   case X86ISD::PSHUFD:
10995   case X86ISD::PSHUFHW:
10996   case X86ISD::PSHUFLW:
10997   case X86ISD::MOVSS:
10998   case X86ISD::MOVSD:
10999   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11000   }
11001
11002   return SDValue();
11003 }
11004
11005 /// isTypeDesirableForOp - Return true if the target has native support for
11006 /// the specified value type and it is 'desirable' to use the type for the
11007 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11008 /// instruction encodings are longer and some i16 instructions are slow.
11009 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11010   if (!isTypeLegal(VT))
11011     return false;
11012   if (VT != MVT::i16)
11013     return true;
11014
11015   switch (Opc) {
11016   default:
11017     return true;
11018   case ISD::LOAD:
11019   case ISD::SIGN_EXTEND:
11020   case ISD::ZERO_EXTEND:
11021   case ISD::ANY_EXTEND:
11022   case ISD::SHL:
11023   case ISD::SRL:
11024   case ISD::SUB:
11025   case ISD::ADD:
11026   case ISD::MUL:
11027   case ISD::AND:
11028   case ISD::OR:
11029   case ISD::XOR:
11030     return false;
11031   }
11032 }
11033
11034 /// IsDesirableToPromoteOp - This method query the target whether it is
11035 /// beneficial for dag combiner to promote the specified node. If true, it
11036 /// should return the desired promotion type by reference.
11037 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11038   EVT VT = Op.getValueType();
11039   if (VT != MVT::i16)
11040     return false;
11041
11042   bool Promote = false;
11043   bool Commute = false;
11044   switch (Op.getOpcode()) {
11045   default: break;
11046   case ISD::LOAD: {
11047     LoadSDNode *LD = cast<LoadSDNode>(Op);
11048     // If the non-extending load has a single use and it's not live out, then it
11049     // might be folded.
11050     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11051                                                      Op.hasOneUse()*/) {
11052       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11053              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11054         // The only case where we'd want to promote LOAD (rather then it being
11055         // promoted as an operand is when it's only use is liveout.
11056         if (UI->getOpcode() != ISD::CopyToReg)
11057           return false;
11058       }
11059     }
11060     Promote = true;
11061     break;
11062   }
11063   case ISD::SIGN_EXTEND:
11064   case ISD::ZERO_EXTEND:
11065   case ISD::ANY_EXTEND:
11066     Promote = true;
11067     break;
11068   case ISD::SHL:
11069   case ISD::SRL: {
11070     SDValue N0 = Op.getOperand(0);
11071     // Look out for (store (shl (load), x)).
11072     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11073       return false;
11074     Promote = true;
11075     break;
11076   }
11077   case ISD::ADD:
11078   case ISD::MUL:
11079   case ISD::AND:
11080   case ISD::OR:
11081   case ISD::XOR:
11082     Commute = true;
11083     // fallthrough
11084   case ISD::SUB: {
11085     SDValue N0 = Op.getOperand(0);
11086     SDValue N1 = Op.getOperand(1);
11087     if (!Commute && MayFoldLoad(N1))
11088       return false;
11089     // Avoid disabling potential load folding opportunities.
11090     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11091       return false;
11092     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11093       return false;
11094     Promote = true;
11095   }
11096   }
11097
11098   PVT = MVT::i32;
11099   return Promote;
11100 }
11101
11102 //===----------------------------------------------------------------------===//
11103 //                           X86 Inline Assembly Support
11104 //===----------------------------------------------------------------------===//
11105
11106 static bool LowerToBSwap(CallInst *CI) {
11107   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11108   // we will turn this bswap into something that will be lowered to logical ops
11109   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11110   // so don't worry about this.
11111
11112   // Verify this is a simple bswap.
11113   if (CI->getNumArgOperands() != 1 ||
11114       CI->getType() != CI->getArgOperand(0)->getType() ||
11115       !CI->getType()->isIntegerTy())
11116     return false;
11117
11118   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11119   if (!Ty || Ty->getBitWidth() % 16 != 0)
11120     return false;
11121
11122   // Okay, we can do this xform, do so now.
11123   const Type *Tys[] = { Ty };
11124   Module *M = CI->getParent()->getParent()->getParent();
11125   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11126
11127   Value *Op = CI->getArgOperand(0);
11128   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11129
11130   CI->replaceAllUsesWith(Op);
11131   CI->eraseFromParent();
11132   return true;
11133 }
11134
11135 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11136   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11137   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11138
11139   std::string AsmStr = IA->getAsmString();
11140
11141   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11142   SmallVector<StringRef, 4> AsmPieces;
11143   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
11144
11145   switch (AsmPieces.size()) {
11146   default: return false;
11147   case 1:
11148     AsmStr = AsmPieces[0];
11149     AsmPieces.clear();
11150     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11151
11152     // bswap $0
11153     if (AsmPieces.size() == 2 &&
11154         (AsmPieces[0] == "bswap" ||
11155          AsmPieces[0] == "bswapq" ||
11156          AsmPieces[0] == "bswapl") &&
11157         (AsmPieces[1] == "$0" ||
11158          AsmPieces[1] == "${0:q}")) {
11159       // No need to check constraints, nothing other than the equivalent of
11160       // "=r,0" would be valid here.
11161       return LowerToBSwap(CI);
11162     }
11163     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11164     if (CI->getType()->isIntegerTy(16) &&
11165         AsmPieces.size() == 3 &&
11166         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11167         AsmPieces[1] == "$$8," &&
11168         AsmPieces[2] == "${0:w}" &&
11169         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11170       AsmPieces.clear();
11171       const std::string &Constraints = IA->getConstraintString();
11172       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11173       std::sort(AsmPieces.begin(), AsmPieces.end());
11174       if (AsmPieces.size() == 4 &&
11175           AsmPieces[0] == "~{cc}" &&
11176           AsmPieces[1] == "~{dirflag}" &&
11177           AsmPieces[2] == "~{flags}" &&
11178           AsmPieces[3] == "~{fpsr}") {
11179         return LowerToBSwap(CI);
11180       }
11181     }
11182     break;
11183   case 3:
11184     if (CI->getType()->isIntegerTy(64) &&
11185         Constraints.size() >= 2 &&
11186         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11187         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11188       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11189       SmallVector<StringRef, 4> Words;
11190       SplitString(AsmPieces[0], Words, " \t");
11191       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11192         Words.clear();
11193         SplitString(AsmPieces[1], Words, " \t");
11194         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11195           Words.clear();
11196           SplitString(AsmPieces[2], Words, " \t,");
11197           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11198               Words[2] == "%edx") {
11199             return LowerToBSwap(CI);
11200           }
11201         }
11202       }
11203     }
11204     break;
11205   }
11206   return false;
11207 }
11208
11209
11210
11211 /// getConstraintType - Given a constraint letter, return the type of
11212 /// constraint it is for this target.
11213 X86TargetLowering::ConstraintType
11214 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11215   if (Constraint.size() == 1) {
11216     switch (Constraint[0]) {
11217     case 'A':
11218       return C_Register;
11219     case 'f':
11220     case 'r':
11221     case 'R':
11222     case 'l':
11223     case 'q':
11224     case 'Q':
11225     case 'x':
11226     case 'y':
11227     case 'Y':
11228       return C_RegisterClass;
11229     case 'e':
11230     case 'Z':
11231       return C_Other;
11232     default:
11233       break;
11234     }
11235   }
11236   return TargetLowering::getConstraintType(Constraint);
11237 }
11238
11239 /// Examine constraint type and operand type and determine a weight value,
11240 /// where: -1 = invalid match, and 0 = so-so match to 3 = good match.
11241 /// This object must already have been set up with the operand type
11242 /// and the current alternative constraint selected.
11243 int X86TargetLowering::getSingleConstraintMatchWeight(
11244     AsmOperandInfo &info, const char *constraint) const {
11245   int weight = -1;
11246   Value *CallOperandVal = info.CallOperandVal;
11247     // If we don't have a value, we can't do a match,
11248     // but allow it at the lowest weight.
11249   if (CallOperandVal == NULL)
11250     return 0;
11251   // Look at the constraint type.
11252   switch (*constraint) {
11253   default:
11254     return TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11255     break;
11256   case 'I':
11257     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11258       if (C->getZExtValue() <= 31)
11259         weight = 3;
11260     }
11261     break;
11262   // etc.
11263   }
11264   return weight;
11265 }
11266
11267 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11268 /// with another that has more specific requirements based on the type of the
11269 /// corresponding operand.
11270 const char *X86TargetLowering::
11271 LowerXConstraint(EVT ConstraintVT) const {
11272   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11273   // 'f' like normal targets.
11274   if (ConstraintVT.isFloatingPoint()) {
11275     if (Subtarget->hasSSE2())
11276       return "Y";
11277     if (Subtarget->hasSSE1())
11278       return "x";
11279   }
11280
11281   return TargetLowering::LowerXConstraint(ConstraintVT);
11282 }
11283
11284 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11285 /// vector.  If it is invalid, don't add anything to Ops.
11286 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11287                                                      char Constraint,
11288                                                      std::vector<SDValue>&Ops,
11289                                                      SelectionDAG &DAG) const {
11290   SDValue Result(0, 0);
11291
11292   switch (Constraint) {
11293   default: break;
11294   case 'I':
11295     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11296       if (C->getZExtValue() <= 31) {
11297         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11298         break;
11299       }
11300     }
11301     return;
11302   case 'J':
11303     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11304       if (C->getZExtValue() <= 63) {
11305         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11306         break;
11307       }
11308     }
11309     return;
11310   case 'K':
11311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11312       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11313         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11314         break;
11315       }
11316     }
11317     return;
11318   case 'N':
11319     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11320       if (C->getZExtValue() <= 255) {
11321         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11322         break;
11323       }
11324     }
11325     return;
11326   case 'e': {
11327     // 32-bit signed value
11328     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11329       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11330                                            C->getSExtValue())) {
11331         // Widen to 64 bits here to get it sign extended.
11332         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11333         break;
11334       }
11335     // FIXME gcc accepts some relocatable values here too, but only in certain
11336     // memory models; it's complicated.
11337     }
11338     return;
11339   }
11340   case 'Z': {
11341     // 32-bit unsigned value
11342     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11343       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11344                                            C->getZExtValue())) {
11345         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11346         break;
11347       }
11348     }
11349     // FIXME gcc accepts some relocatable values here too, but only in certain
11350     // memory models; it's complicated.
11351     return;
11352   }
11353   case 'i': {
11354     // Literal immediates are always ok.
11355     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11356       // Widen to 64 bits here to get it sign extended.
11357       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11358       break;
11359     }
11360
11361     // In any sort of PIC mode addresses need to be computed at runtime by
11362     // adding in a register or some sort of table lookup.  These can't
11363     // be used as immediates.
11364     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11365       return;
11366
11367     // If we are in non-pic codegen mode, we allow the address of a global (with
11368     // an optional displacement) to be used with 'i'.
11369     GlobalAddressSDNode *GA = 0;
11370     int64_t Offset = 0;
11371
11372     // Match either (GA), (GA+C), (GA+C1+C2), etc.
11373     while (1) {
11374       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11375         Offset += GA->getOffset();
11376         break;
11377       } else if (Op.getOpcode() == ISD::ADD) {
11378         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11379           Offset += C->getZExtValue();
11380           Op = Op.getOperand(0);
11381           continue;
11382         }
11383       } else if (Op.getOpcode() == ISD::SUB) {
11384         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11385           Offset += -C->getZExtValue();
11386           Op = Op.getOperand(0);
11387           continue;
11388         }
11389       }
11390
11391       // Otherwise, this isn't something we can handle, reject it.
11392       return;
11393     }
11394
11395     const GlobalValue *GV = GA->getGlobal();
11396     // If we require an extra load to get this address, as in PIC mode, we
11397     // can't accept it.
11398     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11399                                                         getTargetMachine())))
11400       return;
11401
11402     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11403                                         GA->getValueType(0), Offset);
11404     break;
11405   }
11406   }
11407
11408   if (Result.getNode()) {
11409     Ops.push_back(Result);
11410     return;
11411   }
11412   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11413 }
11414
11415 std::vector<unsigned> X86TargetLowering::
11416 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11417                                   EVT VT) const {
11418   if (Constraint.size() == 1) {
11419     // FIXME: not handling fp-stack yet!
11420     switch (Constraint[0]) {      // GCC X86 Constraint Letters
11421     default: break;  // Unknown constraint letter
11422     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11423       if (Subtarget->is64Bit()) {
11424         if (VT == MVT::i32)
11425           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11426                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11427                                        X86::R10D,X86::R11D,X86::R12D,
11428                                        X86::R13D,X86::R14D,X86::R15D,
11429                                        X86::EBP, X86::ESP, 0);
11430         else if (VT == MVT::i16)
11431           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
11432                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
11433                                        X86::R10W,X86::R11W,X86::R12W,
11434                                        X86::R13W,X86::R14W,X86::R15W,
11435                                        X86::BP,  X86::SP, 0);
11436         else if (VT == MVT::i8)
11437           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
11438                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11439                                        X86::R10B,X86::R11B,X86::R12B,
11440                                        X86::R13B,X86::R14B,X86::R15B,
11441                                        X86::BPL, X86::SPL, 0);
11442
11443         else if (VT == MVT::i64)
11444           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11445                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
11446                                        X86::R10, X86::R11, X86::R12,
11447                                        X86::R13, X86::R14, X86::R15,
11448                                        X86::RBP, X86::RSP, 0);
11449
11450         break;
11451       }
11452       // 32-bit fallthrough
11453     case 'Q':   // Q_REGS
11454       if (VT == MVT::i32)
11455         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11456       else if (VT == MVT::i16)
11457         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11458       else if (VT == MVT::i8)
11459         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11460       else if (VT == MVT::i64)
11461         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11462       break;
11463     }
11464   }
11465
11466   return std::vector<unsigned>();
11467 }
11468
11469 std::pair<unsigned, const TargetRegisterClass*>
11470 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11471                                                 EVT VT) const {
11472   // First, see if this is a constraint that directly corresponds to an LLVM
11473   // register class.
11474   if (Constraint.size() == 1) {
11475     // GCC Constraint Letters
11476     switch (Constraint[0]) {
11477     default: break;
11478     case 'r':   // GENERAL_REGS
11479     case 'l':   // INDEX_REGS
11480       if (VT == MVT::i8)
11481         return std::make_pair(0U, X86::GR8RegisterClass);
11482       if (VT == MVT::i16)
11483         return std::make_pair(0U, X86::GR16RegisterClass);
11484       if (VT == MVT::i32 || !Subtarget->is64Bit())
11485         return std::make_pair(0U, X86::GR32RegisterClass);
11486       return std::make_pair(0U, X86::GR64RegisterClass);
11487     case 'R':   // LEGACY_REGS
11488       if (VT == MVT::i8)
11489         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11490       if (VT == MVT::i16)
11491         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11492       if (VT == MVT::i32 || !Subtarget->is64Bit())
11493         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11494       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11495     case 'f':  // FP Stack registers.
11496       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11497       // value to the correct fpstack register class.
11498       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11499         return std::make_pair(0U, X86::RFP32RegisterClass);
11500       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11501         return std::make_pair(0U, X86::RFP64RegisterClass);
11502       return std::make_pair(0U, X86::RFP80RegisterClass);
11503     case 'y':   // MMX_REGS if MMX allowed.
11504       if (!Subtarget->hasMMX()) break;
11505       return std::make_pair(0U, X86::VR64RegisterClass);
11506     case 'Y':   // SSE_REGS if SSE2 allowed
11507       if (!Subtarget->hasSSE2()) break;
11508       // FALL THROUGH.
11509     case 'x':   // SSE_REGS if SSE1 allowed
11510       if (!Subtarget->hasSSE1()) break;
11511
11512       switch (VT.getSimpleVT().SimpleTy) {
11513       default: break;
11514       // Scalar SSE types.
11515       case MVT::f32:
11516       case MVT::i32:
11517         return std::make_pair(0U, X86::FR32RegisterClass);
11518       case MVT::f64:
11519       case MVT::i64:
11520         return std::make_pair(0U, X86::FR64RegisterClass);
11521       // Vector types.
11522       case MVT::v16i8:
11523       case MVT::v8i16:
11524       case MVT::v4i32:
11525       case MVT::v2i64:
11526       case MVT::v4f32:
11527       case MVT::v2f64:
11528         return std::make_pair(0U, X86::VR128RegisterClass);
11529       }
11530       break;
11531     }
11532   }
11533
11534   // Use the default implementation in TargetLowering to convert the register
11535   // constraint into a member of a register class.
11536   std::pair<unsigned, const TargetRegisterClass*> Res;
11537   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11538
11539   // Not found as a standard register?
11540   if (Res.second == 0) {
11541     // Map st(0) -> st(7) -> ST0
11542     if (Constraint.size() == 7 && Constraint[0] == '{' &&
11543         tolower(Constraint[1]) == 's' &&
11544         tolower(Constraint[2]) == 't' &&
11545         Constraint[3] == '(' &&
11546         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11547         Constraint[5] == ')' &&
11548         Constraint[6] == '}') {
11549
11550       Res.first = X86::ST0+Constraint[4]-'0';
11551       Res.second = X86::RFP80RegisterClass;
11552       return Res;
11553     }
11554
11555     // GCC allows "st(0)" to be called just plain "st".
11556     if (StringRef("{st}").equals_lower(Constraint)) {
11557       Res.first = X86::ST0;
11558       Res.second = X86::RFP80RegisterClass;
11559       return Res;
11560     }
11561
11562     // flags -> EFLAGS
11563     if (StringRef("{flags}").equals_lower(Constraint)) {
11564       Res.first = X86::EFLAGS;
11565       Res.second = X86::CCRRegisterClass;
11566       return Res;
11567     }
11568
11569     // 'A' means EAX + EDX.
11570     if (Constraint == "A") {
11571       Res.first = X86::EAX;
11572       Res.second = X86::GR32_ADRegisterClass;
11573       return Res;
11574     }
11575     return Res;
11576   }
11577
11578   // Otherwise, check to see if this is a register class of the wrong value
11579   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11580   // turn into {ax},{dx}.
11581   if (Res.second->hasType(VT))
11582     return Res;   // Correct type already, nothing to do.
11583
11584   // All of the single-register GCC register classes map their values onto
11585   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
11586   // really want an 8-bit or 32-bit register, map to the appropriate register
11587   // class and return the appropriate register.
11588   if (Res.second == X86::GR16RegisterClass) {
11589     if (VT == MVT::i8) {
11590       unsigned DestReg = 0;
11591       switch (Res.first) {
11592       default: break;
11593       case X86::AX: DestReg = X86::AL; break;
11594       case X86::DX: DestReg = X86::DL; break;
11595       case X86::CX: DestReg = X86::CL; break;
11596       case X86::BX: DestReg = X86::BL; break;
11597       }
11598       if (DestReg) {
11599         Res.first = DestReg;
11600         Res.second = X86::GR8RegisterClass;
11601       }
11602     } else if (VT == MVT::i32) {
11603       unsigned DestReg = 0;
11604       switch (Res.first) {
11605       default: break;
11606       case X86::AX: DestReg = X86::EAX; break;
11607       case X86::DX: DestReg = X86::EDX; break;
11608       case X86::CX: DestReg = X86::ECX; break;
11609       case X86::BX: DestReg = X86::EBX; break;
11610       case X86::SI: DestReg = X86::ESI; break;
11611       case X86::DI: DestReg = X86::EDI; break;
11612       case X86::BP: DestReg = X86::EBP; break;
11613       case X86::SP: DestReg = X86::ESP; break;
11614       }
11615       if (DestReg) {
11616         Res.first = DestReg;
11617         Res.second = X86::GR32RegisterClass;
11618       }
11619     } else if (VT == MVT::i64) {
11620       unsigned DestReg = 0;
11621       switch (Res.first) {
11622       default: break;
11623       case X86::AX: DestReg = X86::RAX; break;
11624       case X86::DX: DestReg = X86::RDX; break;
11625       case X86::CX: DestReg = X86::RCX; break;
11626       case X86::BX: DestReg = X86::RBX; break;
11627       case X86::SI: DestReg = X86::RSI; break;
11628       case X86::DI: DestReg = X86::RDI; break;
11629       case X86::BP: DestReg = X86::RBP; break;
11630       case X86::SP: DestReg = X86::RSP; break;
11631       }
11632       if (DestReg) {
11633         Res.first = DestReg;
11634         Res.second = X86::GR64RegisterClass;
11635       }
11636     }
11637   } else if (Res.second == X86::FR32RegisterClass ||
11638              Res.second == X86::FR64RegisterClass ||
11639              Res.second == X86::VR128RegisterClass) {
11640     // Handle references to XMM physical registers that got mapped into the
11641     // wrong class.  This can happen with constraints like {xmm0} where the
11642     // target independent register mapper will just pick the first match it can
11643     // find, ignoring the required type.
11644     if (VT == MVT::f32)
11645       Res.second = X86::FR32RegisterClass;
11646     else if (VT == MVT::f64)
11647       Res.second = X86::FR64RegisterClass;
11648     else if (X86::VR128RegisterClass->hasType(VT))
11649       Res.second = X86::VR128RegisterClass;
11650   }
11651
11652   return Res;
11653 }