71de5cf1d95497d004e87aa93121e428ce12611b
[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   if (Subtarget->is64Bit())
1025     setTargetDAGCombine(ISD::MUL);
1026
1027   computeRegisterProperties();
1028
1029   // FIXME: These should be based on subtarget info. Plus, the values should
1030   // be smaller when we are in optimizing for size mode.
1031   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1032   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1033   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1034   setPrefLoopAlignment(16);
1035   benefitFromCodePlacementOpt = true;
1036 }
1037
1038
1039 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1040   return MVT::i8;
1041 }
1042
1043
1044 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1045 /// the desired ByVal argument alignment.
1046 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1047   if (MaxAlign == 16)
1048     return;
1049   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1050     if (VTy->getBitWidth() == 128)
1051       MaxAlign = 16;
1052   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1053     unsigned EltAlign = 0;
1054     getMaxByValAlign(ATy->getElementType(), EltAlign);
1055     if (EltAlign > MaxAlign)
1056       MaxAlign = EltAlign;
1057   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1058     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1059       unsigned EltAlign = 0;
1060       getMaxByValAlign(STy->getElementType(i), EltAlign);
1061       if (EltAlign > MaxAlign)
1062         MaxAlign = EltAlign;
1063       if (MaxAlign == 16)
1064         break;
1065     }
1066   }
1067   return;
1068 }
1069
1070 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1071 /// function arguments in the caller parameter area. For X86, aggregates
1072 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1073 /// are at 4-byte boundaries.
1074 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1075   if (Subtarget->is64Bit()) {
1076     // Max of 8 and alignment of type.
1077     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1078     if (TyAlign > 8)
1079       return TyAlign;
1080     return 8;
1081   }
1082
1083   unsigned Align = 4;
1084   if (Subtarget->hasSSE1())
1085     getMaxByValAlign(Ty, Align);
1086   return Align;
1087 }
1088
1089 /// getOptimalMemOpType - Returns the target specific optimal type for load
1090 /// and store operations as a result of memset, memcpy, and memmove
1091 /// lowering. If DstAlign is zero that means it's safe to destination
1092 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1093 /// means there isn't a need to check it against alignment requirement,
1094 /// probably because the source does not need to be loaded. If
1095 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1096 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1097 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1098 /// constant so it does not need to be loaded.
1099 /// It returns EVT::Other if the type should be determined using generic
1100 /// target-independent logic.
1101 EVT
1102 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1103                                        unsigned DstAlign, unsigned SrcAlign,
1104                                        bool NonScalarIntSafe,
1105                                        bool MemcpyStrSrc,
1106                                        MachineFunction &MF) const {
1107   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1108   // linux.  This is because the stack realignment code can't handle certain
1109   // cases like PR2962.  This should be removed when PR2962 is fixed.
1110   const Function *F = MF.getFunction();
1111   if (NonScalarIntSafe &&
1112       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1113     if (Size >= 16 &&
1114         (Subtarget->isUnalignedMemAccessFast() ||
1115          ((DstAlign == 0 || DstAlign >= 16) &&
1116           (SrcAlign == 0 || SrcAlign >= 16))) &&
1117         Subtarget->getStackAlignment() >= 16) {
1118       if (Subtarget->hasSSE2())
1119         return MVT::v4i32;
1120       if (Subtarget->hasSSE1())
1121         return MVT::v4f32;
1122     } else if (!MemcpyStrSrc && Size >= 8 &&
1123                !Subtarget->is64Bit() &&
1124                Subtarget->getStackAlignment() >= 8 &&
1125                Subtarget->hasSSE2()) {
1126       // Do not use f64 to lower memcpy if source is string constant. It's
1127       // better to use i32 to avoid the loads.
1128       return MVT::f64;
1129     }
1130   }
1131   if (Subtarget->is64Bit() && Size >= 8)
1132     return MVT::i64;
1133   return MVT::i32;
1134 }
1135
1136 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1137 /// current function.  The returned value is a member of the
1138 /// MachineJumpTableInfo::JTEntryKind enum.
1139 unsigned X86TargetLowering::getJumpTableEncoding() const {
1140   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1141   // symbol.
1142   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1143       Subtarget->isPICStyleGOT())
1144     return MachineJumpTableInfo::EK_Custom32;
1145   
1146   // Otherwise, use the normal jump table encoding heuristics.
1147   return TargetLowering::getJumpTableEncoding();
1148 }
1149
1150 /// getPICBaseSymbol - Return the X86-32 PIC base.
1151 MCSymbol *
1152 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1153                                     MCContext &Ctx) const {
1154   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1155   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1156                                Twine(MF->getFunctionNumber())+"$pb");
1157 }
1158
1159
1160 const MCExpr *
1161 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1162                                              const MachineBasicBlock *MBB,
1163                                              unsigned uid,MCContext &Ctx) const{
1164   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1165          Subtarget->isPICStyleGOT());
1166   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1167   // entries.
1168   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1169                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1170 }
1171
1172 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1173 /// jumptable.
1174 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1175                                                     SelectionDAG &DAG) const {
1176   if (!Subtarget->is64Bit())
1177     // This doesn't have DebugLoc associated with it, but is not really the
1178     // same as a Register.
1179     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1180   return Table;
1181 }
1182
1183 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1184 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1185 /// MCExpr.
1186 const MCExpr *X86TargetLowering::
1187 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1188                              MCContext &Ctx) const {
1189   // X86-64 uses RIP relative addressing based on the jump table label.
1190   if (Subtarget->isPICStyleRIPRel())
1191     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1192
1193   // Otherwise, the reference is relative to the PIC base.
1194   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1195 }
1196
1197 /// getFunctionAlignment - Return the Log2 alignment of this function.
1198 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1199   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1200 }
1201
1202 std::pair<const TargetRegisterClass*, uint8_t>
1203 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1204   const TargetRegisterClass *RRC = 0;
1205   uint8_t Cost = 1;
1206   switch (VT.getSimpleVT().SimpleTy) {
1207   default:
1208     return TargetLowering::findRepresentativeClass(VT);
1209   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1210     RRC = (Subtarget->is64Bit()
1211            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1212     break;
1213   case MVT::v8i8: case MVT::v4i16:
1214   case MVT::v2i32: case MVT::v1i64: 
1215     RRC = X86::VR64RegisterClass;
1216     break;
1217   case MVT::f32: case MVT::f64:
1218   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1219   case MVT::v4f32: case MVT::v2f64:
1220   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1221   case MVT::v4f64:
1222     RRC = X86::VR128RegisterClass;
1223     break;
1224   }
1225   return std::make_pair(RRC, Cost);
1226 }
1227
1228 unsigned
1229 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1230                                        MachineFunction &MF) const {
1231   unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1232   switch (RC->getID()) {
1233   default:
1234     return 0;
1235   case X86::GR32RegClassID:
1236     return 4 - FPDiff;
1237   case X86::GR64RegClassID:
1238     return 8 - FPDiff;
1239   case X86::VR128RegClassID:
1240     return Subtarget->is64Bit() ? 10 : 4;
1241   case X86::VR64RegClassID:
1242     return 4;
1243   }
1244 }
1245
1246 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1247                                                unsigned &Offset) const {
1248   if (!Subtarget->isTargetLinux())
1249     return false;
1250
1251   if (Subtarget->is64Bit()) {
1252     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1253     Offset = 0x28;
1254     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1255       AddressSpace = 256;
1256     else
1257       AddressSpace = 257;
1258   } else {
1259     // %gs:0x14 on i386
1260     Offset = 0x14;
1261     AddressSpace = 256;
1262   }
1263   return true;
1264 }
1265
1266
1267 //===----------------------------------------------------------------------===//
1268 //               Return Value Calling Convention Implementation
1269 //===----------------------------------------------------------------------===//
1270
1271 #include "X86GenCallingConv.inc"
1272
1273 bool 
1274 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1275                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1276                         LLVMContext &Context) const {
1277   SmallVector<CCValAssign, 16> RVLocs;
1278   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1279                  RVLocs, Context);
1280   return CCInfo.CheckReturn(Outs, RetCC_X86);
1281 }
1282
1283 SDValue
1284 X86TargetLowering::LowerReturn(SDValue Chain,
1285                                CallingConv::ID CallConv, bool isVarArg,
1286                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1287                                const SmallVectorImpl<SDValue> &OutVals,
1288                                DebugLoc dl, SelectionDAG &DAG) const {
1289   MachineFunction &MF = DAG.getMachineFunction();
1290   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1291
1292   SmallVector<CCValAssign, 16> RVLocs;
1293   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1294                  RVLocs, *DAG.getContext());
1295   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1296
1297   // Add the regs to the liveout set for the function.
1298   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1299   for (unsigned i = 0; i != RVLocs.size(); ++i)
1300     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1301       MRI.addLiveOut(RVLocs[i].getLocReg());
1302
1303   SDValue Flag;
1304
1305   SmallVector<SDValue, 6> RetOps;
1306   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1307   // Operand #1 = Bytes To Pop
1308   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1309                    MVT::i16));
1310
1311   // Copy the result values into the output registers.
1312   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1313     CCValAssign &VA = RVLocs[i];
1314     assert(VA.isRegLoc() && "Can only return in registers!");
1315     SDValue ValToCopy = OutVals[i];
1316     EVT ValVT = ValToCopy.getValueType();
1317
1318     // If this is x86-64, and we disabled SSE, we can't return FP values
1319     if ((ValVT == MVT::f32 || ValVT == MVT::f64) &&
1320         (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1321       report_fatal_error("SSE register return with SSE disabled");
1322     }
1323     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1324     // llvm-gcc has never done it right and no one has noticed, so this
1325     // should be OK for now.
1326     if (ValVT == MVT::f64 &&
1327         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1328       report_fatal_error("SSE2 register return with SSE2 disabled");
1329
1330     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1331     // the RET instruction and handled by the FP Stackifier.
1332     if (VA.getLocReg() == X86::ST0 ||
1333         VA.getLocReg() == X86::ST1) {
1334       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1335       // change the value to the FP stack register class.
1336       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1337         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1338       RetOps.push_back(ValToCopy);
1339       // Don't emit a copytoreg.
1340       continue;
1341     }
1342
1343     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1344     // which is returned in RAX / RDX.
1345     if (Subtarget->is64Bit()) {
1346       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1347         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1348         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1349           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1350                                   ValToCopy);
1351           
1352           // If we don't have SSE2 available, convert to v4f32 so the generated
1353           // register is legal.
1354           if (!Subtarget->hasSSE2())
1355             ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32,ValToCopy);
1356         }
1357       }
1358     }
1359     
1360     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1361     Flag = Chain.getValue(1);
1362   }
1363
1364   // The x86-64 ABI for returning structs by value requires that we copy
1365   // the sret argument into %rax for the return. We saved the argument into
1366   // a virtual register in the entry block, so now we copy the value out
1367   // and into %rax.
1368   if (Subtarget->is64Bit() &&
1369       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1370     MachineFunction &MF = DAG.getMachineFunction();
1371     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1372     unsigned Reg = FuncInfo->getSRetReturnReg();
1373     assert(Reg && 
1374            "SRetReturnReg should have been set in LowerFormalArguments().");
1375     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1376
1377     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1378     Flag = Chain.getValue(1);
1379
1380     // RAX now acts like a return value.
1381     MRI.addLiveOut(X86::RAX);
1382   }
1383
1384   RetOps[0] = Chain;  // Update chain.
1385
1386   // Add the flag if we have it.
1387   if (Flag.getNode())
1388     RetOps.push_back(Flag);
1389
1390   return DAG.getNode(X86ISD::RET_FLAG, dl,
1391                      MVT::Other, &RetOps[0], RetOps.size());
1392 }
1393
1394 /// LowerCallResult - Lower the result values of a call into the
1395 /// appropriate copies out of appropriate physical registers.
1396 ///
1397 SDValue
1398 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1399                                    CallingConv::ID CallConv, bool isVarArg,
1400                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1401                                    DebugLoc dl, SelectionDAG &DAG,
1402                                    SmallVectorImpl<SDValue> &InVals) const {
1403
1404   // Assign locations to each value returned by this call.
1405   SmallVector<CCValAssign, 16> RVLocs;
1406   bool Is64Bit = Subtarget->is64Bit();
1407   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1408                  RVLocs, *DAG.getContext());
1409   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1410
1411   // Copy all of the result registers out of their specified physreg.
1412   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1413     CCValAssign &VA = RVLocs[i];
1414     EVT CopyVT = VA.getValVT();
1415
1416     // If this is x86-64, and we disabled SSE, we can't return FP values
1417     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1418         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1419       report_fatal_error("SSE register return with SSE disabled");
1420     }
1421
1422     SDValue Val;
1423
1424     // If this is a call to a function that returns an fp value on the floating
1425     // point stack, we must guarantee the the value is popped from the stack, so
1426     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1427     // if the return value is not used. We use the FpGET_ST0 instructions
1428     // instead.
1429     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1430       // If we prefer to use the value in xmm registers, copy it out as f80 and
1431       // use a truncate to move it from fp stack reg to xmm reg.
1432       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1433       bool isST0 = VA.getLocReg() == X86::ST0;
1434       unsigned Opc = 0;
1435       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1436       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1437       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1438       SDValue Ops[] = { Chain, InFlag };
1439       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1440                                          Ops, 2), 1);
1441       Val = Chain.getValue(0);
1442
1443       // Round the f80 to the right size, which also moves it to the appropriate
1444       // xmm register.
1445       if (CopyVT != VA.getValVT())
1446         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1447                           // This truncation won't change the value.
1448                           DAG.getIntPtrConstant(1));
1449     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1450       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1451       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1452         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1453                                    MVT::v2i64, InFlag).getValue(1);
1454         Val = Chain.getValue(0);
1455         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1456                           Val, DAG.getConstant(0, MVT::i64));
1457       } else {
1458         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1459                                    MVT::i64, InFlag).getValue(1);
1460         Val = Chain.getValue(0);
1461       }
1462       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1463     } else {
1464       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1465                                  CopyVT, InFlag).getValue(1);
1466       Val = Chain.getValue(0);
1467     }
1468     InFlag = Chain.getValue(2);
1469     InVals.push_back(Val);
1470   }
1471
1472   return Chain;
1473 }
1474
1475
1476 //===----------------------------------------------------------------------===//
1477 //                C & StdCall & Fast Calling Convention implementation
1478 //===----------------------------------------------------------------------===//
1479 //  StdCall calling convention seems to be standard for many Windows' API
1480 //  routines and around. It differs from C calling convention just a little:
1481 //  callee should clean up the stack, not caller. Symbols should be also
1482 //  decorated in some fancy way :) It doesn't support any vector arguments.
1483 //  For info on fast calling convention see Fast Calling Convention (tail call)
1484 //  implementation LowerX86_32FastCCCallTo.
1485
1486 /// CallIsStructReturn - Determines whether a call uses struct return
1487 /// semantics.
1488 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1489   if (Outs.empty())
1490     return false;
1491
1492   return Outs[0].Flags.isSRet();
1493 }
1494
1495 /// ArgsAreStructReturn - Determines whether a function uses struct
1496 /// return semantics.
1497 static bool
1498 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1499   if (Ins.empty())
1500     return false;
1501
1502   return Ins[0].Flags.isSRet();
1503 }
1504
1505 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1506 /// given CallingConvention value.
1507 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1508   if (Subtarget->is64Bit()) {
1509     if (CC == CallingConv::GHC)
1510       return CC_X86_64_GHC;
1511     else if (Subtarget->isTargetWin64())
1512       return CC_X86_Win64_C;
1513     else
1514       return CC_X86_64_C;
1515   }
1516
1517   if (CC == CallingConv::X86_FastCall)
1518     return CC_X86_32_FastCall;
1519   else if (CC == CallingConv::X86_ThisCall)
1520     return CC_X86_32_ThisCall;
1521   else if (CC == CallingConv::Fast)
1522     return CC_X86_32_FastCC;
1523   else if (CC == CallingConv::GHC)
1524     return CC_X86_32_GHC;
1525   else
1526     return CC_X86_32_C;
1527 }
1528
1529 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1530 /// by "Src" to address "Dst" with size and alignment information specified by
1531 /// the specific parameter attribute. The copy will be passed as a byval
1532 /// function parameter.
1533 static SDValue
1534 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1535                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1536                           DebugLoc dl) {
1537   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1538   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1539                        /*isVolatile*/false, /*AlwaysInline=*/true,
1540                        NULL, 0, NULL, 0);
1541 }
1542
1543 /// IsTailCallConvention - Return true if the calling convention is one that
1544 /// supports tail call optimization.
1545 static bool IsTailCallConvention(CallingConv::ID CC) {
1546   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1547 }
1548
1549 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1550 /// a tailcall target by changing its ABI.
1551 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1552   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1553 }
1554
1555 SDValue
1556 X86TargetLowering::LowerMemArgument(SDValue Chain,
1557                                     CallingConv::ID CallConv,
1558                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1559                                     DebugLoc dl, SelectionDAG &DAG,
1560                                     const CCValAssign &VA,
1561                                     MachineFrameInfo *MFI,
1562                                     unsigned i) const {
1563   // Create the nodes corresponding to a load from this parameter slot.
1564   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1565   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1566   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1567   EVT ValVT;
1568
1569   // If value is passed by pointer we have address passed instead of the value
1570   // itself.
1571   if (VA.getLocInfo() == CCValAssign::Indirect)
1572     ValVT = VA.getLocVT();
1573   else
1574     ValVT = VA.getValVT();
1575
1576   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1577   // changed with more analysis.
1578   // In case of tail call optimization mark all arguments mutable. Since they
1579   // could be overwritten by lowering of arguments in case of a tail call.
1580   if (Flags.isByVal()) {
1581     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1582                                     VA.getLocMemOffset(), isImmutable);
1583     return DAG.getFrameIndex(FI, getPointerTy());
1584   } else {
1585     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1586                                     VA.getLocMemOffset(), isImmutable);
1587     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1588     return DAG.getLoad(ValVT, dl, Chain, FIN,
1589                        PseudoSourceValue::getFixedStack(FI), 0,
1590                        false, false, 0);
1591   }
1592 }
1593
1594 SDValue
1595 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1596                                         CallingConv::ID CallConv,
1597                                         bool isVarArg,
1598                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1599                                         DebugLoc dl,
1600                                         SelectionDAG &DAG,
1601                                         SmallVectorImpl<SDValue> &InVals)
1602                                           const {
1603   MachineFunction &MF = DAG.getMachineFunction();
1604   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1605
1606   const Function* Fn = MF.getFunction();
1607   if (Fn->hasExternalLinkage() &&
1608       Subtarget->isTargetCygMing() &&
1609       Fn->getName() == "main")
1610     FuncInfo->setForceFramePointer(true);
1611
1612   MachineFrameInfo *MFI = MF.getFrameInfo();
1613   bool Is64Bit = Subtarget->is64Bit();
1614   bool IsWin64 = Subtarget->isTargetWin64();
1615
1616   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1617          "Var args not supported with calling convention fastcc or ghc");
1618
1619   // Assign locations to all of the incoming arguments.
1620   SmallVector<CCValAssign, 16> ArgLocs;
1621   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1622                  ArgLocs, *DAG.getContext());
1623   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1624
1625   unsigned LastVal = ~0U;
1626   SDValue ArgValue;
1627   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1628     CCValAssign &VA = ArgLocs[i];
1629     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1630     // places.
1631     assert(VA.getValNo() != LastVal &&
1632            "Don't support value assigned to multiple locs yet");
1633     LastVal = VA.getValNo();
1634
1635     if (VA.isRegLoc()) {
1636       EVT RegVT = VA.getLocVT();
1637       TargetRegisterClass *RC = NULL;
1638       if (RegVT == MVT::i32)
1639         RC = X86::GR32RegisterClass;
1640       else if (Is64Bit && RegVT == MVT::i64)
1641         RC = X86::GR64RegisterClass;
1642       else if (RegVT == MVT::f32)
1643         RC = X86::FR32RegisterClass;
1644       else if (RegVT == MVT::f64)
1645         RC = X86::FR64RegisterClass;
1646       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1647         RC = X86::VR256RegisterClass;
1648       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1649         RC = X86::VR128RegisterClass;
1650       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1651         RC = X86::VR64RegisterClass;
1652       else
1653         llvm_unreachable("Unknown argument type!");
1654
1655       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1656       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1657
1658       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1659       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1660       // right size.
1661       if (VA.getLocInfo() == CCValAssign::SExt)
1662         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1663                                DAG.getValueType(VA.getValVT()));
1664       else if (VA.getLocInfo() == CCValAssign::ZExt)
1665         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1666                                DAG.getValueType(VA.getValVT()));
1667       else if (VA.getLocInfo() == CCValAssign::BCvt)
1668         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1669
1670       if (VA.isExtInLoc()) {
1671         // Handle MMX values passed in XMM regs.
1672         if (RegVT.isVector()) {
1673           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1674                                  ArgValue, DAG.getConstant(0, MVT::i64));
1675           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1676         } else
1677           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1678       }
1679     } else {
1680       assert(VA.isMemLoc());
1681       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1682     }
1683
1684     // If value is passed via pointer - do a load.
1685     if (VA.getLocInfo() == CCValAssign::Indirect)
1686       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1687                              false, false, 0);
1688
1689     InVals.push_back(ArgValue);
1690   }
1691
1692   // The x86-64 ABI for returning structs by value requires that we copy
1693   // the sret argument into %rax for the return. Save the argument into
1694   // a virtual register so that we can access it from the return points.
1695   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1696     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1697     unsigned Reg = FuncInfo->getSRetReturnReg();
1698     if (!Reg) {
1699       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1700       FuncInfo->setSRetReturnReg(Reg);
1701     }
1702     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1703     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1704   }
1705
1706   unsigned StackSize = CCInfo.getNextStackOffset();
1707   // Align stack specially for tail calls.
1708   if (FuncIsMadeTailCallSafe(CallConv))
1709     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1710
1711   // If the function takes variable number of arguments, make a frame index for
1712   // the start of the first vararg value... for expansion of llvm.va_start.
1713   if (isVarArg) {
1714     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1715                     CallConv != CallingConv::X86_ThisCall)) {
1716       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1717     }
1718     if (Is64Bit) {
1719       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1720
1721       // FIXME: We should really autogenerate these arrays
1722       static const unsigned GPR64ArgRegsWin64[] = {
1723         X86::RCX, X86::RDX, X86::R8,  X86::R9
1724       };
1725       static const unsigned XMMArgRegsWin64[] = {
1726         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1727       };
1728       static const unsigned GPR64ArgRegs64Bit[] = {
1729         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1730       };
1731       static const unsigned XMMArgRegs64Bit[] = {
1732         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1733         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1734       };
1735       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1736
1737       if (IsWin64) {
1738         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1739         GPR64ArgRegs = GPR64ArgRegsWin64;
1740         XMMArgRegs = XMMArgRegsWin64;
1741       } else {
1742         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1743         GPR64ArgRegs = GPR64ArgRegs64Bit;
1744         XMMArgRegs = XMMArgRegs64Bit;
1745       }
1746       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1747                                                        TotalNumIntRegs);
1748       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1749                                                        TotalNumXMMRegs);
1750
1751       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1752       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1753              "SSE register cannot be used when SSE is disabled!");
1754       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1755              "SSE register cannot be used when SSE is disabled!");
1756       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1757         // Kernel mode asks for SSE to be disabled, so don't push them
1758         // on the stack.
1759         TotalNumXMMRegs = 0;
1760
1761       // For X86-64, if there are vararg parameters that are passed via
1762       // registers, then we must store them to their spots on the stack so they
1763       // may be loaded by deferencing the result of va_next.
1764       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1765       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1766       FuncInfo->setRegSaveFrameIndex(
1767         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1768                                false));
1769
1770       // Store the integer parameter registers.
1771       SmallVector<SDValue, 8> MemOps;
1772       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1773                                         getPointerTy());
1774       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1775       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1776         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1777                                   DAG.getIntPtrConstant(Offset));
1778         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1779                                      X86::GR64RegisterClass);
1780         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1781         SDValue Store =
1782           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1783                        PseudoSourceValue::getFixedStack(
1784                          FuncInfo->getRegSaveFrameIndex()),
1785                        Offset, false, false, 0);
1786         MemOps.push_back(Store);
1787         Offset += 8;
1788       }
1789
1790       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1791         // Now store the XMM (fp + vector) parameter registers.
1792         SmallVector<SDValue, 11> SaveXMMOps;
1793         SaveXMMOps.push_back(Chain);
1794
1795         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1796         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1797         SaveXMMOps.push_back(ALVal);
1798
1799         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1800                                FuncInfo->getRegSaveFrameIndex()));
1801         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1802                                FuncInfo->getVarArgsFPOffset()));
1803
1804         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1805           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1806                                        X86::VR128RegisterClass);
1807           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1808           SaveXMMOps.push_back(Val);
1809         }
1810         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1811                                      MVT::Other,
1812                                      &SaveXMMOps[0], SaveXMMOps.size()));
1813       }
1814
1815       if (!MemOps.empty())
1816         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1817                             &MemOps[0], MemOps.size());
1818     }
1819   }
1820
1821   // Some CCs need callee pop.
1822   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1823     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1824   } else {
1825     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1826     // If this is an sret function, the return should pop the hidden pointer.
1827     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1828       FuncInfo->setBytesToPopOnReturn(4);
1829   }
1830
1831   if (!Is64Bit) {
1832     // RegSaveFrameIndex is X86-64 only.
1833     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1834     if (CallConv == CallingConv::X86_FastCall ||
1835         CallConv == CallingConv::X86_ThisCall)
1836       // fastcc functions can't have varargs.
1837       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1838   }
1839
1840   return Chain;
1841 }
1842
1843 SDValue
1844 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1845                                     SDValue StackPtr, SDValue Arg,
1846                                     DebugLoc dl, SelectionDAG &DAG,
1847                                     const CCValAssign &VA,
1848                                     ISD::ArgFlagsTy Flags) const {
1849   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1850   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1851   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1852   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1853   if (Flags.isByVal()) {
1854     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1855   }
1856   return DAG.getStore(Chain, dl, Arg, PtrOff,
1857                       PseudoSourceValue::getStack(), LocMemOffset,
1858                       false, false, 0);
1859 }
1860
1861 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1862 /// optimization is performed and it is required.
1863 SDValue
1864 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1865                                            SDValue &OutRetAddr, SDValue Chain,
1866                                            bool IsTailCall, bool Is64Bit,
1867                                            int FPDiff, DebugLoc dl) const {
1868   // Adjust the Return address stack slot.
1869   EVT VT = getPointerTy();
1870   OutRetAddr = getReturnAddressFrameIndex(DAG);
1871
1872   // Load the "old" Return address.
1873   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1874   return SDValue(OutRetAddr.getNode(), 1);
1875 }
1876
1877 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1878 /// optimization is performed and it is required (FPDiff!=0).
1879 static SDValue
1880 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1881                          SDValue Chain, SDValue RetAddrFrIdx,
1882                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1883   // Store the return address to the appropriate stack slot.
1884   if (!FPDiff) return Chain;
1885   // Calculate the new stack slot for the return address.
1886   int SlotSize = Is64Bit ? 8 : 4;
1887   int NewReturnAddrFI =
1888     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1889   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1890   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1891   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1892                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1893                        false, false, 0);
1894   return Chain;
1895 }
1896
1897 SDValue
1898 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1899                              CallingConv::ID CallConv, bool isVarArg,
1900                              bool &isTailCall,
1901                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                              const SmallVectorImpl<SDValue> &OutVals,
1903                              const SmallVectorImpl<ISD::InputArg> &Ins,
1904                              DebugLoc dl, SelectionDAG &DAG,
1905                              SmallVectorImpl<SDValue> &InVals) const {
1906   MachineFunction &MF = DAG.getMachineFunction();
1907   bool Is64Bit        = Subtarget->is64Bit();
1908   bool IsStructRet    = CallIsStructReturn(Outs);
1909   bool IsSibcall      = false;
1910
1911   if (isTailCall) {
1912     // Check if it's really possible to do a tail call.
1913     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1914                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1915                                                    Outs, OutVals, Ins, DAG);
1916
1917     // Sibcalls are automatically detected tailcalls which do not require
1918     // ABI changes.
1919     if (!GuaranteedTailCallOpt && isTailCall)
1920       IsSibcall = true;
1921
1922     if (isTailCall)
1923       ++NumTailCalls;
1924   }
1925
1926   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1927          "Var args not supported with calling convention fastcc or ghc");
1928
1929   // Analyze operands of the call, assigning locations to each operand.
1930   SmallVector<CCValAssign, 16> ArgLocs;
1931   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1932                  ArgLocs, *DAG.getContext());
1933   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1934
1935   // Get a count of how many bytes are to be pushed on the stack.
1936   unsigned NumBytes = CCInfo.getNextStackOffset();
1937   if (IsSibcall)
1938     // This is a sibcall. The memory operands are available in caller's
1939     // own caller's stack.
1940     NumBytes = 0;
1941   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1942     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1943
1944   int FPDiff = 0;
1945   if (isTailCall && !IsSibcall) {
1946     // Lower arguments at fp - stackoffset + fpdiff.
1947     unsigned NumBytesCallerPushed =
1948       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1949     FPDiff = NumBytesCallerPushed - NumBytes;
1950
1951     // Set the delta of movement of the returnaddr stackslot.
1952     // But only set if delta is greater than previous delta.
1953     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1954       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1955   }
1956
1957   if (!IsSibcall)
1958     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1959
1960   SDValue RetAddrFrIdx;
1961   // Load return adress for tail calls.
1962   if (isTailCall && FPDiff)
1963     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1964                                     Is64Bit, FPDiff, dl);
1965
1966   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1967   SmallVector<SDValue, 8> MemOpChains;
1968   SDValue StackPtr;
1969
1970   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1971   // of tail call optimization arguments are handle later.
1972   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1973     CCValAssign &VA = ArgLocs[i];
1974     EVT RegVT = VA.getLocVT();
1975     SDValue Arg = OutVals[i];
1976     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1977     bool isByVal = Flags.isByVal();
1978
1979     // Promote the value if needed.
1980     switch (VA.getLocInfo()) {
1981     default: llvm_unreachable("Unknown loc info!");
1982     case CCValAssign::Full: break;
1983     case CCValAssign::SExt:
1984       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1985       break;
1986     case CCValAssign::ZExt:
1987       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1988       break;
1989     case CCValAssign::AExt:
1990       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1991         // Special case: passing MMX values in XMM registers.
1992         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1993         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1994         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1995       } else
1996         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1997       break;
1998     case CCValAssign::BCvt:
1999       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
2000       break;
2001     case CCValAssign::Indirect: {
2002       // Store the argument.
2003       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2004       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2005       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2006                            PseudoSourceValue::getFixedStack(FI), 0,
2007                            false, false, 0);
2008       Arg = SpillSlot;
2009       break;
2010     }
2011     }
2012
2013     if (VA.isRegLoc()) {
2014       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2015       if (isVarArg && Subtarget->isTargetWin64()) {
2016         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2017         // shadow reg if callee is a varargs function.
2018         unsigned ShadowReg = 0;
2019         switch (VA.getLocReg()) {
2020         case X86::XMM0: ShadowReg = X86::RCX; break;
2021         case X86::XMM1: ShadowReg = X86::RDX; break;
2022         case X86::XMM2: ShadowReg = X86::R8; break;
2023         case X86::XMM3: ShadowReg = X86::R9; break;
2024         }
2025         if (ShadowReg)
2026           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2027       }
2028     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2029       assert(VA.isMemLoc());
2030       if (StackPtr.getNode() == 0)
2031         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2032       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2033                                              dl, DAG, VA, Flags));
2034     }
2035   }
2036
2037   if (!MemOpChains.empty())
2038     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2039                         &MemOpChains[0], MemOpChains.size());
2040
2041   // Build a sequence of copy-to-reg nodes chained together with token chain
2042   // and flag operands which copy the outgoing args into registers.
2043   SDValue InFlag;
2044   // Tail call byval lowering might overwrite argument registers so in case of
2045   // tail call optimization the copies to registers are lowered later.
2046   if (!isTailCall)
2047     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2048       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2049                                RegsToPass[i].second, InFlag);
2050       InFlag = Chain.getValue(1);
2051     }
2052
2053   if (Subtarget->isPICStyleGOT()) {
2054     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2055     // GOT pointer.
2056     if (!isTailCall) {
2057       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2058                                DAG.getNode(X86ISD::GlobalBaseReg,
2059                                            DebugLoc(), getPointerTy()),
2060                                InFlag);
2061       InFlag = Chain.getValue(1);
2062     } else {
2063       // If we are tail calling and generating PIC/GOT style code load the
2064       // address of the callee into ECX. The value in ecx is used as target of
2065       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2066       // for tail calls on PIC/GOT architectures. Normally we would just put the
2067       // address of GOT into ebx and then call target@PLT. But for tail calls
2068       // ebx would be restored (since ebx is callee saved) before jumping to the
2069       // target@PLT.
2070
2071       // Note: The actual moving to ECX is done further down.
2072       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2073       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2074           !G->getGlobal()->hasProtectedVisibility())
2075         Callee = LowerGlobalAddress(Callee, DAG);
2076       else if (isa<ExternalSymbolSDNode>(Callee))
2077         Callee = LowerExternalSymbol(Callee, DAG);
2078     }
2079   }
2080
2081   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2082     // From AMD64 ABI document:
2083     // For calls that may call functions that use varargs or stdargs
2084     // (prototype-less calls or calls to functions containing ellipsis (...) in
2085     // the declaration) %al is used as hidden argument to specify the number
2086     // of SSE registers used. The contents of %al do not need to match exactly
2087     // the number of registers, but must be an ubound on the number of SSE
2088     // registers used and is in the range 0 - 8 inclusive.
2089
2090     // Count the number of XMM registers allocated.
2091     static const unsigned XMMArgRegs[] = {
2092       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2093       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2094     };
2095     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2096     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2097            && "SSE registers cannot be used when SSE is disabled");
2098
2099     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2100                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2101     InFlag = Chain.getValue(1);
2102   }
2103
2104
2105   // For tail calls lower the arguments to the 'real' stack slot.
2106   if (isTailCall) {
2107     // Force all the incoming stack arguments to be loaded from the stack
2108     // before any new outgoing arguments are stored to the stack, because the
2109     // outgoing stack slots may alias the incoming argument stack slots, and
2110     // the alias isn't otherwise explicit. This is slightly more conservative
2111     // than necessary, because it means that each store effectively depends
2112     // on every argument instead of just those arguments it would clobber.
2113     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2114
2115     SmallVector<SDValue, 8> MemOpChains2;
2116     SDValue FIN;
2117     int FI = 0;
2118     // Do not flag preceeding copytoreg stuff together with the following stuff.
2119     InFlag = SDValue();
2120     if (GuaranteedTailCallOpt) {
2121       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2122         CCValAssign &VA = ArgLocs[i];
2123         if (VA.isRegLoc())
2124           continue;
2125         assert(VA.isMemLoc());
2126         SDValue Arg = OutVals[i];
2127         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2128         // Create frame index.
2129         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2130         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2131         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2132         FIN = DAG.getFrameIndex(FI, getPointerTy());
2133
2134         if (Flags.isByVal()) {
2135           // Copy relative to framepointer.
2136           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2137           if (StackPtr.getNode() == 0)
2138             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2139                                           getPointerTy());
2140           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2141
2142           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2143                                                            ArgChain,
2144                                                            Flags, DAG, dl));
2145         } else {
2146           // Store relative to framepointer.
2147           MemOpChains2.push_back(
2148             DAG.getStore(ArgChain, dl, Arg, FIN,
2149                          PseudoSourceValue::getFixedStack(FI), 0,
2150                          false, false, 0));
2151         }
2152       }
2153     }
2154
2155     if (!MemOpChains2.empty())
2156       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2157                           &MemOpChains2[0], MemOpChains2.size());
2158
2159     // Copy arguments to their registers.
2160     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2161       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2162                                RegsToPass[i].second, InFlag);
2163       InFlag = Chain.getValue(1);
2164     }
2165     InFlag =SDValue();
2166
2167     // Store the return address to the appropriate stack slot.
2168     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2169                                      FPDiff, dl);
2170   }
2171
2172   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2173     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2174     // In the 64-bit large code model, we have to make all calls
2175     // through a register, since the call instruction's 32-bit
2176     // pc-relative offset may not be large enough to hold the whole
2177     // address.
2178   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2179     // If the callee is a GlobalAddress node (quite common, every direct call
2180     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2181     // it.
2182
2183     // We should use extra load for direct calls to dllimported functions in
2184     // non-JIT mode.
2185     const GlobalValue *GV = G->getGlobal();
2186     if (!GV->hasDLLImportLinkage()) {
2187       unsigned char OpFlags = 0;
2188
2189       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2190       // external symbols most go through the PLT in PIC mode.  If the symbol
2191       // has hidden or protected visibility, or if it is static or local, then
2192       // we don't need to use the PLT - we can directly call it.
2193       if (Subtarget->isTargetELF() &&
2194           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2195           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2196         OpFlags = X86II::MO_PLT;
2197       } else if (Subtarget->isPICStyleStubAny() &&
2198                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2199                Subtarget->getDarwinVers() < 9) {
2200         // PC-relative references to external symbols should go through $stub,
2201         // unless we're building with the leopard linker or later, which
2202         // automatically synthesizes these stubs.
2203         OpFlags = X86II::MO_DARWIN_STUB;
2204       }
2205
2206       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2207                                           G->getOffset(), OpFlags);
2208     }
2209   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2210     unsigned char OpFlags = 0;
2211
2212     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2213     // symbols should go through the PLT.
2214     if (Subtarget->isTargetELF() &&
2215         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2216       OpFlags = X86II::MO_PLT;
2217     } else if (Subtarget->isPICStyleStubAny() &&
2218              Subtarget->getDarwinVers() < 9) {
2219       // PC-relative references to external symbols should go through $stub,
2220       // unless we're building with the leopard linker or later, which
2221       // automatically synthesizes these stubs.
2222       OpFlags = X86II::MO_DARWIN_STUB;
2223     }
2224
2225     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2226                                          OpFlags);
2227   }
2228
2229   // Returns a chain & a flag for retval copy to use.
2230   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2231   SmallVector<SDValue, 8> Ops;
2232
2233   if (!IsSibcall && isTailCall) {
2234     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2235                            DAG.getIntPtrConstant(0, true), InFlag);
2236     InFlag = Chain.getValue(1);
2237   }
2238
2239   Ops.push_back(Chain);
2240   Ops.push_back(Callee);
2241
2242   if (isTailCall)
2243     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2244
2245   // Add argument registers to the end of the list so that they are known live
2246   // into the call.
2247   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2248     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2249                                   RegsToPass[i].second.getValueType()));
2250
2251   // Add an implicit use GOT pointer in EBX.
2252   if (!isTailCall && Subtarget->isPICStyleGOT())
2253     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2254
2255   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2256   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2257     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2258
2259   if (InFlag.getNode())
2260     Ops.push_back(InFlag);
2261
2262   if (isTailCall) {
2263     // We used to do:
2264     //// If this is the first return lowered for this function, add the regs
2265     //// to the liveout set for the function.
2266     // This isn't right, although it's probably harmless on x86; liveouts
2267     // should be computed from returns not tail calls.  Consider a void
2268     // function making a tail call to a function returning int.
2269     return DAG.getNode(X86ISD::TC_RETURN, dl,
2270                        NodeTys, &Ops[0], Ops.size());
2271   }
2272
2273   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2274   InFlag = Chain.getValue(1);
2275
2276   // Create the CALLSEQ_END node.
2277   unsigned NumBytesForCalleeToPush;
2278   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2279     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2280   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2281     // If this is a call to a struct-return function, the callee
2282     // pops the hidden struct pointer, so we have to push it back.
2283     // This is common for Darwin/X86, Linux & Mingw32 targets.
2284     NumBytesForCalleeToPush = 4;
2285   else
2286     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2287
2288   // Returns a flag for retval copy to use.
2289   if (!IsSibcall) {
2290     Chain = DAG.getCALLSEQ_END(Chain,
2291                                DAG.getIntPtrConstant(NumBytes, true),
2292                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2293                                                      true),
2294                                InFlag);
2295     InFlag = Chain.getValue(1);
2296   }
2297
2298   // Handle result values, copying them out of physregs into vregs that we
2299   // return.
2300   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2301                          Ins, dl, DAG, InVals);
2302 }
2303
2304
2305 //===----------------------------------------------------------------------===//
2306 //                Fast Calling Convention (tail call) implementation
2307 //===----------------------------------------------------------------------===//
2308
2309 //  Like std call, callee cleans arguments, convention except that ECX is
2310 //  reserved for storing the tail called function address. Only 2 registers are
2311 //  free for argument passing (inreg). Tail call optimization is performed
2312 //  provided:
2313 //                * tailcallopt is enabled
2314 //                * caller/callee are fastcc
2315 //  On X86_64 architecture with GOT-style position independent code only local
2316 //  (within module) calls are supported at the moment.
2317 //  To keep the stack aligned according to platform abi the function
2318 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2319 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2320 //  If a tail called function callee has more arguments than the caller the
2321 //  caller needs to make sure that there is room to move the RETADDR to. This is
2322 //  achieved by reserving an area the size of the argument delta right after the
2323 //  original REtADDR, but before the saved framepointer or the spilled registers
2324 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2325 //  stack layout:
2326 //    arg1
2327 //    arg2
2328 //    RETADDR
2329 //    [ new RETADDR
2330 //      move area ]
2331 //    (possible EBP)
2332 //    ESI
2333 //    EDI
2334 //    local1 ..
2335
2336 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2337 /// for a 16 byte align requirement.
2338 unsigned
2339 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2340                                                SelectionDAG& DAG) const {
2341   MachineFunction &MF = DAG.getMachineFunction();
2342   const TargetMachine &TM = MF.getTarget();
2343   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2344   unsigned StackAlignment = TFI.getStackAlignment();
2345   uint64_t AlignMask = StackAlignment - 1;
2346   int64_t Offset = StackSize;
2347   uint64_t SlotSize = TD->getPointerSize();
2348   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2349     // Number smaller than 12 so just add the difference.
2350     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2351   } else {
2352     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2353     Offset = ((~AlignMask) & Offset) + StackAlignment +
2354       (StackAlignment-SlotSize);
2355   }
2356   return Offset;
2357 }
2358
2359 /// MatchingStackOffset - Return true if the given stack call argument is
2360 /// already available in the same position (relatively) of the caller's
2361 /// incoming argument stack.
2362 static
2363 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2364                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2365                          const X86InstrInfo *TII) {
2366   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2367   int FI = INT_MAX;
2368   if (Arg.getOpcode() == ISD::CopyFromReg) {
2369     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2370     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2371       return false;
2372     MachineInstr *Def = MRI->getVRegDef(VR);
2373     if (!Def)
2374       return false;
2375     if (!Flags.isByVal()) {
2376       if (!TII->isLoadFromStackSlot(Def, FI))
2377         return false;
2378     } else {
2379       unsigned Opcode = Def->getOpcode();
2380       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2381           Def->getOperand(1).isFI()) {
2382         FI = Def->getOperand(1).getIndex();
2383         Bytes = Flags.getByValSize();
2384       } else
2385         return false;
2386     }
2387   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2388     if (Flags.isByVal())
2389       // ByVal argument is passed in as a pointer but it's now being
2390       // dereferenced. e.g.
2391       // define @foo(%struct.X* %A) {
2392       //   tail call @bar(%struct.X* byval %A)
2393       // }
2394       return false;
2395     SDValue Ptr = Ld->getBasePtr();
2396     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2397     if (!FINode)
2398       return false;
2399     FI = FINode->getIndex();
2400   } else
2401     return false;
2402
2403   assert(FI != INT_MAX);
2404   if (!MFI->isFixedObjectIndex(FI))
2405     return false;
2406   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2407 }
2408
2409 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2410 /// for tail call optimization. Targets which want to do tail call
2411 /// optimization should implement this function.
2412 bool
2413 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2414                                                      CallingConv::ID CalleeCC,
2415                                                      bool isVarArg,
2416                                                      bool isCalleeStructRet,
2417                                                      bool isCallerStructRet,
2418                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2419                                     const SmallVectorImpl<SDValue> &OutVals,
2420                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2421                                                      SelectionDAG& DAG) const {
2422   if (!IsTailCallConvention(CalleeCC) &&
2423       CalleeCC != CallingConv::C)
2424     return false;
2425
2426   // If -tailcallopt is specified, make fastcc functions tail-callable.
2427   const MachineFunction &MF = DAG.getMachineFunction();
2428   const Function *CallerF = DAG.getMachineFunction().getFunction();
2429   CallingConv::ID CallerCC = CallerF->getCallingConv();
2430   bool CCMatch = CallerCC == CalleeCC;
2431
2432   if (GuaranteedTailCallOpt) {
2433     if (IsTailCallConvention(CalleeCC) && CCMatch)
2434       return true;
2435     return false;
2436   }
2437
2438   // Look for obvious safe cases to perform tail call optimization that do not
2439   // require ABI changes. This is what gcc calls sibcall.
2440
2441   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2442   // emit a special epilogue.
2443   if (RegInfo->needsStackRealignment(MF))
2444     return false;
2445
2446   // Do not sibcall optimize vararg calls unless the call site is not passing
2447   // any arguments.
2448   if (isVarArg && !Outs.empty())
2449     return false;
2450
2451   // Also avoid sibcall optimization if either caller or callee uses struct
2452   // return semantics.
2453   if (isCalleeStructRet || isCallerStructRet)
2454     return false;
2455
2456   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2457   // Therefore if it's not used by the call it is not safe to optimize this into
2458   // a sibcall.
2459   bool Unused = false;
2460   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2461     if (!Ins[i].Used) {
2462       Unused = true;
2463       break;
2464     }
2465   }
2466   if (Unused) {
2467     SmallVector<CCValAssign, 16> RVLocs;
2468     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2469                    RVLocs, *DAG.getContext());
2470     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2471     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2472       CCValAssign &VA = RVLocs[i];
2473       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2474         return false;
2475     }
2476   }
2477
2478   // If the calling conventions do not match, then we'd better make sure the
2479   // results are returned in the same way as what the caller expects.
2480   if (!CCMatch) {
2481     SmallVector<CCValAssign, 16> RVLocs1;
2482     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2483                     RVLocs1, *DAG.getContext());
2484     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2485
2486     SmallVector<CCValAssign, 16> RVLocs2;
2487     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2488                     RVLocs2, *DAG.getContext());
2489     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2490
2491     if (RVLocs1.size() != RVLocs2.size())
2492       return false;
2493     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2494       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2495         return false;
2496       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2497         return false;
2498       if (RVLocs1[i].isRegLoc()) {
2499         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2500           return false;
2501       } else {
2502         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2503           return false;
2504       }
2505     }
2506   }
2507
2508   // If the callee takes no arguments then go on to check the results of the
2509   // call.
2510   if (!Outs.empty()) {
2511     // Check if stack adjustment is needed. For now, do not do this if any
2512     // argument is passed on the stack.
2513     SmallVector<CCValAssign, 16> ArgLocs;
2514     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2515                    ArgLocs, *DAG.getContext());
2516     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2517     if (CCInfo.getNextStackOffset()) {
2518       MachineFunction &MF = DAG.getMachineFunction();
2519       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2520         return false;
2521       if (Subtarget->isTargetWin64())
2522         // Win64 ABI has additional complications.
2523         return false;
2524
2525       // Check if the arguments are already laid out in the right way as
2526       // the caller's fixed stack objects.
2527       MachineFrameInfo *MFI = MF.getFrameInfo();
2528       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2529       const X86InstrInfo *TII =
2530         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2531       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2532         CCValAssign &VA = ArgLocs[i];
2533         SDValue Arg = OutVals[i];
2534         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2535         if (VA.getLocInfo() == CCValAssign::Indirect)
2536           return false;
2537         if (!VA.isRegLoc()) {
2538           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2539                                    MFI, MRI, TII))
2540             return false;
2541         }
2542       }
2543     }
2544
2545     // If the tailcall address may be in a register, then make sure it's
2546     // possible to register allocate for it. In 32-bit, the call address can
2547     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2548     // callee-saved registers are restored. These happen to be the same
2549     // registers used to pass 'inreg' arguments so watch out for those.
2550     if (!Subtarget->is64Bit() &&
2551         !isa<GlobalAddressSDNode>(Callee) &&
2552         !isa<ExternalSymbolSDNode>(Callee)) {
2553       unsigned NumInRegs = 0;
2554       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2555         CCValAssign &VA = ArgLocs[i];
2556         if (!VA.isRegLoc())
2557           continue;
2558         unsigned Reg = VA.getLocReg();
2559         switch (Reg) {
2560         default: break;
2561         case X86::EAX: case X86::EDX: case X86::ECX:
2562           if (++NumInRegs == 3)
2563             return false;
2564           break;
2565         }
2566       }
2567     }
2568   }
2569
2570   return true;
2571 }
2572
2573 FastISel *
2574 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2575   return X86::createFastISel(funcInfo);
2576 }
2577
2578
2579 //===----------------------------------------------------------------------===//
2580 //                           Other Lowering Hooks
2581 //===----------------------------------------------------------------------===//
2582
2583 static bool MayFoldLoad(SDValue Op) {
2584   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2585 }
2586
2587 static bool MayFoldIntoStore(SDValue Op) {
2588   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2589 }
2590
2591 static bool isTargetShuffle(unsigned Opcode) {
2592   switch(Opcode) {
2593   default: return false;
2594   case X86ISD::PSHUFD:
2595   case X86ISD::PSHUFHW:
2596   case X86ISD::PSHUFLW:
2597   case X86ISD::SHUFPD:
2598   case X86ISD::PALIGN:
2599   case X86ISD::SHUFPS:
2600   case X86ISD::MOVLHPS:
2601   case X86ISD::MOVLHPD:
2602   case X86ISD::MOVHLPS:
2603   case X86ISD::MOVLPS:
2604   case X86ISD::MOVLPD:
2605   case X86ISD::MOVSHDUP:
2606   case X86ISD::MOVSLDUP:
2607   case X86ISD::MOVDDUP:
2608   case X86ISD::MOVSS:
2609   case X86ISD::MOVSD:
2610   case X86ISD::UNPCKLPS:
2611   case X86ISD::UNPCKLPD:
2612   case X86ISD::PUNPCKLWD:
2613   case X86ISD::PUNPCKLBW:
2614   case X86ISD::PUNPCKLDQ:
2615   case X86ISD::PUNPCKLQDQ:
2616   case X86ISD::UNPCKHPS:
2617   case X86ISD::UNPCKHPD:
2618   case X86ISD::PUNPCKHWD:
2619   case X86ISD::PUNPCKHBW:
2620   case X86ISD::PUNPCKHDQ:
2621   case X86ISD::PUNPCKHQDQ:
2622     return true;
2623   }
2624   return false;
2625 }
2626
2627 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2628                                                SDValue V1, SelectionDAG &DAG) {
2629   switch(Opc) {
2630   default: llvm_unreachable("Unknown x86 shuffle node");
2631   case X86ISD::MOVSHDUP:
2632   case X86ISD::MOVSLDUP:
2633   case X86ISD::MOVDDUP:
2634     return DAG.getNode(Opc, dl, VT, V1);
2635   }
2636
2637   return SDValue();
2638 }
2639
2640 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2641                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2642   switch(Opc) {
2643   default: llvm_unreachable("Unknown x86 shuffle node");
2644   case X86ISD::PSHUFD:
2645   case X86ISD::PSHUFHW:
2646   case X86ISD::PSHUFLW:
2647     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2648   }
2649
2650   return SDValue();
2651 }
2652
2653 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2654                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2655   switch(Opc) {
2656   default: llvm_unreachable("Unknown x86 shuffle node");
2657   case X86ISD::PALIGN:
2658   case X86ISD::SHUFPD:
2659   case X86ISD::SHUFPS:
2660     return DAG.getNode(Opc, dl, VT, V1, V2,
2661                        DAG.getConstant(TargetMask, MVT::i8));
2662   }
2663   return SDValue();
2664 }
2665
2666 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2667                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2668   switch(Opc) {
2669   default: llvm_unreachable("Unknown x86 shuffle node");
2670   case X86ISD::MOVLHPS:
2671   case X86ISD::MOVLHPD:
2672   case X86ISD::MOVHLPS:
2673   case X86ISD::MOVLPS:
2674   case X86ISD::MOVLPD:
2675   case X86ISD::MOVSS:
2676   case X86ISD::MOVSD:
2677   case X86ISD::UNPCKLPS:
2678   case X86ISD::UNPCKLPD:
2679   case X86ISD::PUNPCKLWD:
2680   case X86ISD::PUNPCKLBW:
2681   case X86ISD::PUNPCKLDQ:
2682   case X86ISD::PUNPCKLQDQ:
2683   case X86ISD::UNPCKHPS:
2684   case X86ISD::UNPCKHPD:
2685   case X86ISD::PUNPCKHWD:
2686   case X86ISD::PUNPCKHBW:
2687   case X86ISD::PUNPCKHDQ:
2688   case X86ISD::PUNPCKHQDQ:
2689     return DAG.getNode(Opc, dl, VT, V1, V2);
2690   }
2691   return SDValue();
2692 }
2693
2694 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2695   MachineFunction &MF = DAG.getMachineFunction();
2696   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2697   int ReturnAddrIndex = FuncInfo->getRAIndex();
2698
2699   if (ReturnAddrIndex == 0) {
2700     // Set up a frame object for the return address.
2701     uint64_t SlotSize = TD->getPointerSize();
2702     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2703                                                            false);
2704     FuncInfo->setRAIndex(ReturnAddrIndex);
2705   }
2706
2707   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2708 }
2709
2710
2711 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2712                                        bool hasSymbolicDisplacement) {
2713   // Offset should fit into 32 bit immediate field.
2714   if (!isInt<32>(Offset))
2715     return false;
2716
2717   // If we don't have a symbolic displacement - we don't have any extra
2718   // restrictions.
2719   if (!hasSymbolicDisplacement)
2720     return true;
2721
2722   // FIXME: Some tweaks might be needed for medium code model.
2723   if (M != CodeModel::Small && M != CodeModel::Kernel)
2724     return false;
2725
2726   // For small code model we assume that latest object is 16MB before end of 31
2727   // bits boundary. We may also accept pretty large negative constants knowing
2728   // that all objects are in the positive half of address space.
2729   if (M == CodeModel::Small && Offset < 16*1024*1024)
2730     return true;
2731
2732   // For kernel code model we know that all object resist in the negative half
2733   // of 32bits address space. We may not accept negative offsets, since they may
2734   // be just off and we may accept pretty large positive ones.
2735   if (M == CodeModel::Kernel && Offset > 0)
2736     return true;
2737
2738   return false;
2739 }
2740
2741 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2742 /// specific condition code, returning the condition code and the LHS/RHS of the
2743 /// comparison to make.
2744 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2745                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2746   if (!isFP) {
2747     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2748       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2749         // X > -1   -> X == 0, jump !sign.
2750         RHS = DAG.getConstant(0, RHS.getValueType());
2751         return X86::COND_NS;
2752       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2753         // X < 0   -> X == 0, jump on sign.
2754         return X86::COND_S;
2755       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2756         // X < 1   -> X <= 0
2757         RHS = DAG.getConstant(0, RHS.getValueType());
2758         return X86::COND_LE;
2759       }
2760     }
2761
2762     switch (SetCCOpcode) {
2763     default: llvm_unreachable("Invalid integer condition!");
2764     case ISD::SETEQ:  return X86::COND_E;
2765     case ISD::SETGT:  return X86::COND_G;
2766     case ISD::SETGE:  return X86::COND_GE;
2767     case ISD::SETLT:  return X86::COND_L;
2768     case ISD::SETLE:  return X86::COND_LE;
2769     case ISD::SETNE:  return X86::COND_NE;
2770     case ISD::SETULT: return X86::COND_B;
2771     case ISD::SETUGT: return X86::COND_A;
2772     case ISD::SETULE: return X86::COND_BE;
2773     case ISD::SETUGE: return X86::COND_AE;
2774     }
2775   }
2776
2777   // First determine if it is required or is profitable to flip the operands.
2778
2779   // If LHS is a foldable load, but RHS is not, flip the condition.
2780   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2781       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2782     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2783     std::swap(LHS, RHS);
2784   }
2785
2786   switch (SetCCOpcode) {
2787   default: break;
2788   case ISD::SETOLT:
2789   case ISD::SETOLE:
2790   case ISD::SETUGT:
2791   case ISD::SETUGE:
2792     std::swap(LHS, RHS);
2793     break;
2794   }
2795
2796   // On a floating point condition, the flags are set as follows:
2797   // ZF  PF  CF   op
2798   //  0 | 0 | 0 | X > Y
2799   //  0 | 0 | 1 | X < Y
2800   //  1 | 0 | 0 | X == Y
2801   //  1 | 1 | 1 | unordered
2802   switch (SetCCOpcode) {
2803   default: llvm_unreachable("Condcode should be pre-legalized away");
2804   case ISD::SETUEQ:
2805   case ISD::SETEQ:   return X86::COND_E;
2806   case ISD::SETOLT:              // flipped
2807   case ISD::SETOGT:
2808   case ISD::SETGT:   return X86::COND_A;
2809   case ISD::SETOLE:              // flipped
2810   case ISD::SETOGE:
2811   case ISD::SETGE:   return X86::COND_AE;
2812   case ISD::SETUGT:              // flipped
2813   case ISD::SETULT:
2814   case ISD::SETLT:   return X86::COND_B;
2815   case ISD::SETUGE:              // flipped
2816   case ISD::SETULE:
2817   case ISD::SETLE:   return X86::COND_BE;
2818   case ISD::SETONE:
2819   case ISD::SETNE:   return X86::COND_NE;
2820   case ISD::SETUO:   return X86::COND_P;
2821   case ISD::SETO:    return X86::COND_NP;
2822   case ISD::SETOEQ:
2823   case ISD::SETUNE:  return X86::COND_INVALID;
2824   }
2825 }
2826
2827 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2828 /// code. Current x86 isa includes the following FP cmov instructions:
2829 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2830 static bool hasFPCMov(unsigned X86CC) {
2831   switch (X86CC) {
2832   default:
2833     return false;
2834   case X86::COND_B:
2835   case X86::COND_BE:
2836   case X86::COND_E:
2837   case X86::COND_P:
2838   case X86::COND_A:
2839   case X86::COND_AE:
2840   case X86::COND_NE:
2841   case X86::COND_NP:
2842     return true;
2843   }
2844 }
2845
2846 /// isFPImmLegal - Returns true if the target can instruction select the
2847 /// specified FP immediate natively. If false, the legalizer will
2848 /// materialize the FP immediate as a load from a constant pool.
2849 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2850   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2851     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2852       return true;
2853   }
2854   return false;
2855 }
2856
2857 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2858 /// the specified range (L, H].
2859 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2860   return (Val < 0) || (Val >= Low && Val < Hi);
2861 }
2862
2863 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2864 /// specified value.
2865 static bool isUndefOrEqual(int Val, int CmpVal) {
2866   if (Val < 0 || Val == CmpVal)
2867     return true;
2868   return false;
2869 }
2870
2871 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2872 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2873 /// the second operand.
2874 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2875   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2876     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2877   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2878     return (Mask[0] < 2 && Mask[1] < 2);
2879   return false;
2880 }
2881
2882 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2883   SmallVector<int, 8> M;
2884   N->getMask(M);
2885   return ::isPSHUFDMask(M, N->getValueType(0));
2886 }
2887
2888 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2889 /// is suitable for input to PSHUFHW.
2890 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2891   if (VT != MVT::v8i16)
2892     return false;
2893
2894   // Lower quadword copied in order or undef.
2895   for (int i = 0; i != 4; ++i)
2896     if (Mask[i] >= 0 && Mask[i] != i)
2897       return false;
2898
2899   // Upper quadword shuffled.
2900   for (int i = 4; i != 8; ++i)
2901     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2902       return false;
2903
2904   return true;
2905 }
2906
2907 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2908   SmallVector<int, 8> M;
2909   N->getMask(M);
2910   return ::isPSHUFHWMask(M, N->getValueType(0));
2911 }
2912
2913 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2914 /// is suitable for input to PSHUFLW.
2915 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2916   if (VT != MVT::v8i16)
2917     return false;
2918
2919   // Upper quadword copied in order.
2920   for (int i = 4; i != 8; ++i)
2921     if (Mask[i] >= 0 && Mask[i] != i)
2922       return false;
2923
2924   // Lower quadword shuffled.
2925   for (int i = 0; i != 4; ++i)
2926     if (Mask[i] >= 4)
2927       return false;
2928
2929   return true;
2930 }
2931
2932 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2933   SmallVector<int, 8> M;
2934   N->getMask(M);
2935   return ::isPSHUFLWMask(M, N->getValueType(0));
2936 }
2937
2938 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2939 /// is suitable for input to PALIGNR.
2940 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2941                           bool hasSSSE3) {
2942   int i, e = VT.getVectorNumElements();
2943   
2944   // Do not handle v2i64 / v2f64 shuffles with palignr.
2945   if (e < 4 || !hasSSSE3)
2946     return false;
2947   
2948   for (i = 0; i != e; ++i)
2949     if (Mask[i] >= 0)
2950       break;
2951   
2952   // All undef, not a palignr.
2953   if (i == e)
2954     return false;
2955
2956   // Determine if it's ok to perform a palignr with only the LHS, since we
2957   // don't have access to the actual shuffle elements to see if RHS is undef.
2958   bool Unary = Mask[i] < (int)e;
2959   bool NeedsUnary = false;
2960
2961   int s = Mask[i] - i;
2962   
2963   // Check the rest of the elements to see if they are consecutive.
2964   for (++i; i != e; ++i) {
2965     int m = Mask[i];
2966     if (m < 0) 
2967       continue;
2968     
2969     Unary = Unary && (m < (int)e);
2970     NeedsUnary = NeedsUnary || (m < s);
2971
2972     if (NeedsUnary && !Unary)
2973       return false;
2974     if (Unary && m != ((s+i) & (e-1)))
2975       return false;
2976     if (!Unary && m != (s+i))
2977       return false;
2978   }
2979   return true;
2980 }
2981
2982 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2983   SmallVector<int, 8> M;
2984   N->getMask(M);
2985   return ::isPALIGNRMask(M, N->getValueType(0), true);
2986 }
2987
2988 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2989 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2990 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2991   int NumElems = VT.getVectorNumElements();
2992   if (NumElems != 2 && NumElems != 4)
2993     return false;
2994
2995   int Half = NumElems / 2;
2996   for (int i = 0; i < Half; ++i)
2997     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2998       return false;
2999   for (int i = Half; i < NumElems; ++i)
3000     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3001       return false;
3002
3003   return true;
3004 }
3005
3006 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3007   SmallVector<int, 8> M;
3008   N->getMask(M);
3009   return ::isSHUFPMask(M, N->getValueType(0));
3010 }
3011
3012 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3013 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3014 /// half elements to come from vector 1 (which would equal the dest.) and
3015 /// the upper half to come from vector 2.
3016 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3017   int NumElems = VT.getVectorNumElements();
3018
3019   if (NumElems != 2 && NumElems != 4)
3020     return false;
3021
3022   int Half = NumElems / 2;
3023   for (int i = 0; i < Half; ++i)
3024     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3025       return false;
3026   for (int i = Half; i < NumElems; ++i)
3027     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3028       return false;
3029   return true;
3030 }
3031
3032 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3033   SmallVector<int, 8> M;
3034   N->getMask(M);
3035   return isCommutedSHUFPMask(M, N->getValueType(0));
3036 }
3037
3038 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3039 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3040 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3041   if (N->getValueType(0).getVectorNumElements() != 4)
3042     return false;
3043
3044   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3045   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3046          isUndefOrEqual(N->getMaskElt(1), 7) &&
3047          isUndefOrEqual(N->getMaskElt(2), 2) &&
3048          isUndefOrEqual(N->getMaskElt(3), 3);
3049 }
3050
3051 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3052 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3053 /// <2, 3, 2, 3>
3054 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3055   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3056   
3057   if (NumElems != 4)
3058     return false;
3059   
3060   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3061   isUndefOrEqual(N->getMaskElt(1), 3) &&
3062   isUndefOrEqual(N->getMaskElt(2), 2) &&
3063   isUndefOrEqual(N->getMaskElt(3), 3);
3064 }
3065
3066 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3067 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3068 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3069   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3070
3071   if (NumElems != 2 && NumElems != 4)
3072     return false;
3073
3074   for (unsigned i = 0; i < NumElems/2; ++i)
3075     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3076       return false;
3077
3078   for (unsigned i = NumElems/2; i < NumElems; ++i)
3079     if (!isUndefOrEqual(N->getMaskElt(i), i))
3080       return false;
3081
3082   return true;
3083 }
3084
3085 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3086 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3087 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3088   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3089
3090   if (NumElems != 2 && NumElems != 4)
3091     return false;
3092
3093   for (unsigned i = 0; i < NumElems/2; ++i)
3094     if (!isUndefOrEqual(N->getMaskElt(i), i))
3095       return false;
3096
3097   for (unsigned i = 0; i < NumElems/2; ++i)
3098     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3099       return false;
3100
3101   return true;
3102 }
3103
3104 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3105 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3106 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3107                          bool V2IsSplat = false) {
3108   int NumElts = VT.getVectorNumElements();
3109   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3110     return false;
3111
3112   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3113     int BitI  = Mask[i];
3114     int BitI1 = Mask[i+1];
3115     if (!isUndefOrEqual(BitI, j))
3116       return false;
3117     if (V2IsSplat) {
3118       if (!isUndefOrEqual(BitI1, NumElts))
3119         return false;
3120     } else {
3121       if (!isUndefOrEqual(BitI1, j + NumElts))
3122         return false;
3123     }
3124   }
3125   return true;
3126 }
3127
3128 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3129   SmallVector<int, 8> M;
3130   N->getMask(M);
3131   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3132 }
3133
3134 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3135 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3136 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3137                          bool V2IsSplat = false) {
3138   int NumElts = VT.getVectorNumElements();
3139   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3140     return false;
3141
3142   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3143     int BitI  = Mask[i];
3144     int BitI1 = Mask[i+1];
3145     if (!isUndefOrEqual(BitI, j + NumElts/2))
3146       return false;
3147     if (V2IsSplat) {
3148       if (isUndefOrEqual(BitI1, NumElts))
3149         return false;
3150     } else {
3151       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3152         return false;
3153     }
3154   }
3155   return true;
3156 }
3157
3158 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3159   SmallVector<int, 8> M;
3160   N->getMask(M);
3161   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3162 }
3163
3164 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3165 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3166 /// <0, 0, 1, 1>
3167 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3168   int NumElems = VT.getVectorNumElements();
3169   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3170     return false;
3171
3172   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3173     int BitI  = Mask[i];
3174     int BitI1 = Mask[i+1];
3175     if (!isUndefOrEqual(BitI, j))
3176       return false;
3177     if (!isUndefOrEqual(BitI1, j))
3178       return false;
3179   }
3180   return true;
3181 }
3182
3183 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3184   SmallVector<int, 8> M;
3185   N->getMask(M);
3186   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3187 }
3188
3189 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3190 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3191 /// <2, 2, 3, 3>
3192 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3193   int NumElems = VT.getVectorNumElements();
3194   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3195     return false;
3196
3197   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3198     int BitI  = Mask[i];
3199     int BitI1 = Mask[i+1];
3200     if (!isUndefOrEqual(BitI, j))
3201       return false;
3202     if (!isUndefOrEqual(BitI1, j))
3203       return false;
3204   }
3205   return true;
3206 }
3207
3208 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3209   SmallVector<int, 8> M;
3210   N->getMask(M);
3211   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3212 }
3213
3214 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3215 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3216 /// MOVSD, and MOVD, i.e. setting the lowest element.
3217 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3218   if (VT.getVectorElementType().getSizeInBits() < 32)
3219     return false;
3220
3221   int NumElts = VT.getVectorNumElements();
3222
3223   if (!isUndefOrEqual(Mask[0], NumElts))
3224     return false;
3225
3226   for (int i = 1; i < NumElts; ++i)
3227     if (!isUndefOrEqual(Mask[i], i))
3228       return false;
3229
3230   return true;
3231 }
3232
3233 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3234   SmallVector<int, 8> M;
3235   N->getMask(M);
3236   return ::isMOVLMask(M, N->getValueType(0));
3237 }
3238
3239 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3240 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3241 /// element of vector 2 and the other elements to come from vector 1 in order.
3242 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3243                                bool V2IsSplat = false, bool V2IsUndef = false) {
3244   int NumOps = VT.getVectorNumElements();
3245   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3246     return false;
3247
3248   if (!isUndefOrEqual(Mask[0], 0))
3249     return false;
3250
3251   for (int i = 1; i < NumOps; ++i)
3252     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3253           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3254           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3255       return false;
3256
3257   return true;
3258 }
3259
3260 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3261                            bool V2IsUndef = false) {
3262   SmallVector<int, 8> M;
3263   N->getMask(M);
3264   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3265 }
3266
3267 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3268 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3269 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3270   if (N->getValueType(0).getVectorNumElements() != 4)
3271     return false;
3272
3273   // Expect 1, 1, 3, 3
3274   for (unsigned i = 0; i < 2; ++i) {
3275     int Elt = N->getMaskElt(i);
3276     if (Elt >= 0 && Elt != 1)
3277       return false;
3278   }
3279
3280   bool HasHi = false;
3281   for (unsigned i = 2; i < 4; ++i) {
3282     int Elt = N->getMaskElt(i);
3283     if (Elt >= 0 && Elt != 3)
3284       return false;
3285     if (Elt == 3)
3286       HasHi = true;
3287   }
3288   // Don't use movshdup if it can be done with a shufps.
3289   // FIXME: verify that matching u, u, 3, 3 is what we want.
3290   return HasHi;
3291 }
3292
3293 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3294 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3295 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3296   if (N->getValueType(0).getVectorNumElements() != 4)
3297     return false;
3298
3299   // Expect 0, 0, 2, 2
3300   for (unsigned i = 0; i < 2; ++i)
3301     if (N->getMaskElt(i) > 0)
3302       return false;
3303
3304   bool HasHi = false;
3305   for (unsigned i = 2; i < 4; ++i) {
3306     int Elt = N->getMaskElt(i);
3307     if (Elt >= 0 && Elt != 2)
3308       return false;
3309     if (Elt == 2)
3310       HasHi = true;
3311   }
3312   // Don't use movsldup if it can be done with a shufps.
3313   return HasHi;
3314 }
3315
3316 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3317 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3318 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3319   int e = N->getValueType(0).getVectorNumElements() / 2;
3320
3321   for (int i = 0; i < e; ++i)
3322     if (!isUndefOrEqual(N->getMaskElt(i), i))
3323       return false;
3324   for (int i = 0; i < e; ++i)
3325     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3326       return false;
3327   return true;
3328 }
3329
3330 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3331 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3332 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3333   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3334   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3335
3336   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3337   unsigned Mask = 0;
3338   for (int i = 0; i < NumOperands; ++i) {
3339     int Val = SVOp->getMaskElt(NumOperands-i-1);
3340     if (Val < 0) Val = 0;
3341     if (Val >= NumOperands) Val -= NumOperands;
3342     Mask |= Val;
3343     if (i != NumOperands - 1)
3344       Mask <<= Shift;
3345   }
3346   return Mask;
3347 }
3348
3349 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3350 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3351 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3352   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3353   unsigned Mask = 0;
3354   // 8 nodes, but we only care about the last 4.
3355   for (unsigned i = 7; i >= 4; --i) {
3356     int Val = SVOp->getMaskElt(i);
3357     if (Val >= 0)
3358       Mask |= (Val - 4);
3359     if (i != 4)
3360       Mask <<= 2;
3361   }
3362   return Mask;
3363 }
3364
3365 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3366 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3367 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3369   unsigned Mask = 0;
3370   // 8 nodes, but we only care about the first 4.
3371   for (int i = 3; i >= 0; --i) {
3372     int Val = SVOp->getMaskElt(i);
3373     if (Val >= 0)
3374       Mask |= Val;
3375     if (i != 0)
3376       Mask <<= 2;
3377   }
3378   return Mask;
3379 }
3380
3381 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3382 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3383 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3384   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3385   EVT VVT = N->getValueType(0);
3386   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3387   int Val = 0;
3388
3389   unsigned i, e;
3390   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3391     Val = SVOp->getMaskElt(i);
3392     if (Val >= 0)
3393       break;
3394   }
3395   return (Val - i) * EltSize;
3396 }
3397
3398 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3399 /// constant +0.0.
3400 bool X86::isZeroNode(SDValue Elt) {
3401   return ((isa<ConstantSDNode>(Elt) &&
3402            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3403           (isa<ConstantFPSDNode>(Elt) &&
3404            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3405 }
3406
3407 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3408 /// their permute mask.
3409 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3410                                     SelectionDAG &DAG) {
3411   EVT VT = SVOp->getValueType(0);
3412   unsigned NumElems = VT.getVectorNumElements();
3413   SmallVector<int, 8> MaskVec;
3414
3415   for (unsigned i = 0; i != NumElems; ++i) {
3416     int idx = SVOp->getMaskElt(i);
3417     if (idx < 0)
3418       MaskVec.push_back(idx);
3419     else if (idx < (int)NumElems)
3420       MaskVec.push_back(idx + NumElems);
3421     else
3422       MaskVec.push_back(idx - NumElems);
3423   }
3424   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3425                               SVOp->getOperand(0), &MaskVec[0]);
3426 }
3427
3428 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3429 /// the two vector operands have swapped position.
3430 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3431   unsigned NumElems = VT.getVectorNumElements();
3432   for (unsigned i = 0; i != NumElems; ++i) {
3433     int idx = Mask[i];
3434     if (idx < 0)
3435       continue;
3436     else if (idx < (int)NumElems)
3437       Mask[i] = idx + NumElems;
3438     else
3439       Mask[i] = idx - NumElems;
3440   }
3441 }
3442
3443 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3444 /// match movhlps. The lower half elements should come from upper half of
3445 /// V1 (and in order), and the upper half elements should come from the upper
3446 /// half of V2 (and in order).
3447 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3448   if (Op->getValueType(0).getVectorNumElements() != 4)
3449     return false;
3450   for (unsigned i = 0, e = 2; i != e; ++i)
3451     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3452       return false;
3453   for (unsigned i = 2; i != 4; ++i)
3454     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3455       return false;
3456   return true;
3457 }
3458
3459 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3460 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3461 /// required.
3462 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3463   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3464     return false;
3465   N = N->getOperand(0).getNode();
3466   if (!ISD::isNON_EXTLoad(N))
3467     return false;
3468   if (LD)
3469     *LD = cast<LoadSDNode>(N);
3470   return true;
3471 }
3472
3473 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3474 /// match movlp{s|d}. The lower half elements should come from lower half of
3475 /// V1 (and in order), and the upper half elements should come from the upper
3476 /// half of V2 (and in order). And since V1 will become the source of the
3477 /// MOVLP, it must be either a vector load or a scalar load to vector.
3478 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3479                                ShuffleVectorSDNode *Op) {
3480   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3481     return false;
3482   // Is V2 is a vector load, don't do this transformation. We will try to use
3483   // load folding shufps op.
3484   if (ISD::isNON_EXTLoad(V2))
3485     return false;
3486
3487   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3488
3489   if (NumElems != 2 && NumElems != 4)
3490     return false;
3491   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3492     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3493       return false;
3494   for (unsigned i = NumElems/2; i != NumElems; ++i)
3495     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3496       return false;
3497   return true;
3498 }
3499
3500 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3501 /// all the same.
3502 static bool isSplatVector(SDNode *N) {
3503   if (N->getOpcode() != ISD::BUILD_VECTOR)
3504     return false;
3505
3506   SDValue SplatValue = N->getOperand(0);
3507   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3508     if (N->getOperand(i) != SplatValue)
3509       return false;
3510   return true;
3511 }
3512
3513 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3514 /// to an zero vector.
3515 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3516 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3517   SDValue V1 = N->getOperand(0);
3518   SDValue V2 = N->getOperand(1);
3519   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3520   for (unsigned i = 0; i != NumElems; ++i) {
3521     int Idx = N->getMaskElt(i);
3522     if (Idx >= (int)NumElems) {
3523       unsigned Opc = V2.getOpcode();
3524       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3525         continue;
3526       if (Opc != ISD::BUILD_VECTOR ||
3527           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3528         return false;
3529     } else if (Idx >= 0) {
3530       unsigned Opc = V1.getOpcode();
3531       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3532         continue;
3533       if (Opc != ISD::BUILD_VECTOR ||
3534           !X86::isZeroNode(V1.getOperand(Idx)))
3535         return false;
3536     }
3537   }
3538   return true;
3539 }
3540
3541 /// getZeroVector - Returns a vector of specified type with all zero elements.
3542 ///
3543 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3544                              DebugLoc dl) {
3545   assert(VT.isVector() && "Expected a vector type");
3546
3547   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted
3548   // to their dest type. This ensures they get CSE'd.
3549   SDValue Vec;
3550   if (VT.getSizeInBits() == 64) { // MMX
3551     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3552     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3553   } else if (VT.getSizeInBits() == 128) {
3554     if (HasSSE2) {  // SSE2
3555       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3556       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3557     } else { // SSE1
3558       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3559       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3560     }
3561   } else if (VT.getSizeInBits() == 256) { // AVX
3562     // 256-bit logic and arithmetic instructions in AVX are
3563     // all floating-point, no support for integer ops. Default
3564     // to emitting fp zeroed vectors then.
3565     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3566     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3567     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3568   }
3569   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3570 }
3571
3572 /// getOnesVector - Returns a vector of specified type with all bits set.
3573 ///
3574 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3575   assert(VT.isVector() && "Expected a vector type");
3576
3577   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3578   // type.  This ensures they get CSE'd.
3579   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3580   SDValue Vec;
3581   if (VT.getSizeInBits() == 64) // MMX
3582     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3583   else // SSE
3584     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3585   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3586 }
3587
3588
3589 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3590 /// that point to V2 points to its first element.
3591 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3592   EVT VT = SVOp->getValueType(0);
3593   unsigned NumElems = VT.getVectorNumElements();
3594
3595   bool Changed = false;
3596   SmallVector<int, 8> MaskVec;
3597   SVOp->getMask(MaskVec);
3598
3599   for (unsigned i = 0; i != NumElems; ++i) {
3600     if (MaskVec[i] > (int)NumElems) {
3601       MaskVec[i] = NumElems;
3602       Changed = true;
3603     }
3604   }
3605   if (Changed)
3606     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3607                                 SVOp->getOperand(1), &MaskVec[0]);
3608   return SDValue(SVOp, 0);
3609 }
3610
3611 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3612 /// operation of specified width.
3613 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3614                        SDValue V2) {
3615   unsigned NumElems = VT.getVectorNumElements();
3616   SmallVector<int, 8> Mask;
3617   Mask.push_back(NumElems);
3618   for (unsigned i = 1; i != NumElems; ++i)
3619     Mask.push_back(i);
3620   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3621 }
3622
3623 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3624 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3625                           SDValue V2) {
3626   unsigned NumElems = VT.getVectorNumElements();
3627   SmallVector<int, 8> Mask;
3628   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3629     Mask.push_back(i);
3630     Mask.push_back(i + NumElems);
3631   }
3632   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3633 }
3634
3635 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3636 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3637                           SDValue V2) {
3638   unsigned NumElems = VT.getVectorNumElements();
3639   unsigned Half = NumElems/2;
3640   SmallVector<int, 8> Mask;
3641   for (unsigned i = 0; i != Half; ++i) {
3642     Mask.push_back(i + Half);
3643     Mask.push_back(i + NumElems + Half);
3644   }
3645   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3646 }
3647
3648 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3649 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3650   EVT PVT = MVT::v4f32;
3651   EVT VT = SV->getValueType(0);
3652   DebugLoc dl = SV->getDebugLoc();
3653   SDValue V1 = SV->getOperand(0);
3654   int NumElems = VT.getVectorNumElements();
3655   int EltNo = SV->getSplatIndex();
3656
3657   // unpack elements to the correct location
3658   while (NumElems > 4) {
3659     if (EltNo < NumElems/2) {
3660       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3661     } else {
3662       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3663       EltNo -= NumElems/2;
3664     }
3665     NumElems >>= 1;
3666   }
3667
3668   // Perform the splat.
3669   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3670   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3671   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3672   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3673 }
3674
3675 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3676 /// vector of zero or undef vector.  This produces a shuffle where the low
3677 /// element of V2 is swizzled into the zero/undef vector, landing at element
3678 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3679 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3680                                              bool isZero, bool HasSSE2,
3681                                              SelectionDAG &DAG) {
3682   EVT VT = V2.getValueType();
3683   SDValue V1 = isZero
3684     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3685   unsigned NumElems = VT.getVectorNumElements();
3686   SmallVector<int, 16> MaskVec;
3687   for (unsigned i = 0; i != NumElems; ++i)
3688     // If this is the insertion idx, put the low elt of V2 here.
3689     MaskVec.push_back(i == Idx ? NumElems : i);
3690   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3691 }
3692
3693 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3694 /// element of the result of the vector shuffle.
3695 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3696                             unsigned Depth) {
3697   if (Depth == 6)
3698     return SDValue();  // Limit search depth.
3699
3700   SDValue V = SDValue(N, 0);
3701   EVT VT = V.getValueType();
3702   unsigned Opcode = V.getOpcode();
3703
3704   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3705   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3706     Index = SV->getMaskElt(Index);
3707
3708     if (Index < 0)
3709       return DAG.getUNDEF(VT.getVectorElementType());
3710
3711     int NumElems = VT.getVectorNumElements();
3712     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3713     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3714   }
3715
3716   // Recurse into target specific vector shuffles to find scalars.
3717   if (isTargetShuffle(Opcode)) {
3718     int NumElems = VT.getVectorNumElements();
3719     SmallVector<unsigned, 16> ShuffleMask;
3720     SDValue ImmN;
3721
3722     switch(Opcode) {
3723     case X86ISD::SHUFPS:
3724     case X86ISD::SHUFPD:
3725       ImmN = N->getOperand(N->getNumOperands()-1);
3726       DecodeSHUFPSMask(NumElems,
3727                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3728                        ShuffleMask);
3729       break;
3730     case X86ISD::PUNPCKHBW:
3731     case X86ISD::PUNPCKHWD:
3732     case X86ISD::PUNPCKHDQ:
3733     case X86ISD::PUNPCKHQDQ:
3734       DecodePUNPCKHMask(NumElems, ShuffleMask);
3735       break;
3736     case X86ISD::UNPCKHPS:
3737     case X86ISD::UNPCKHPD:
3738       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3739       break;
3740     case X86ISD::PUNPCKLBW:
3741     case X86ISD::PUNPCKLWD:
3742     case X86ISD::PUNPCKLDQ:
3743     case X86ISD::PUNPCKLQDQ:
3744       DecodePUNPCKLMask(NumElems, ShuffleMask);
3745       break;
3746     case X86ISD::UNPCKLPS:
3747     case X86ISD::UNPCKLPD:
3748       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3749       break;
3750     case X86ISD::MOVHLPS:
3751       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3752       break;
3753     case X86ISD::MOVLHPS:
3754       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3755       break;
3756     case X86ISD::PSHUFD:
3757       ImmN = N->getOperand(N->getNumOperands()-1);
3758       DecodePSHUFMask(NumElems,
3759                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3760                       ShuffleMask);
3761       break;
3762     case X86ISD::PSHUFHW:
3763       ImmN = N->getOperand(N->getNumOperands()-1);
3764       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3765                         ShuffleMask);
3766       break;
3767     case X86ISD::PSHUFLW:
3768       ImmN = N->getOperand(N->getNumOperands()-1);
3769       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3770                         ShuffleMask);
3771       break;
3772     case X86ISD::MOVSS:
3773     case X86ISD::MOVSD: {
3774       // The index 0 always comes from the first element of the second source,
3775       // this is why MOVSS and MOVSD are used in the first place. The other
3776       // elements come from the other positions of the first source vector.
3777       unsigned OpNum = (Index == 0) ? 1 : 0;
3778       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3779                                  Depth+1);
3780     }
3781     default:
3782       assert("not implemented for target shuffle node");
3783       return SDValue();
3784     }
3785
3786     Index = ShuffleMask[Index];
3787     if (Index < 0)
3788       return DAG.getUNDEF(VT.getVectorElementType());
3789
3790     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3791     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3792                                Depth+1);
3793   }
3794
3795   // Actual nodes that may contain scalar elements
3796   if (Opcode == ISD::BIT_CONVERT) {
3797     V = V.getOperand(0);
3798     EVT SrcVT = V.getValueType();
3799     unsigned NumElems = VT.getVectorNumElements();
3800
3801     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3802       return SDValue();
3803   }
3804
3805   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3806     return (Index == 0) ? V.getOperand(0)
3807                           : DAG.getUNDEF(VT.getVectorElementType());
3808
3809   if (V.getOpcode() == ISD::BUILD_VECTOR)
3810     return V.getOperand(Index);
3811
3812   return SDValue();
3813 }
3814
3815 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3816 /// shuffle operation which come from a consecutively from a zero. The
3817 /// search can start in two diferent directions, from left or right.
3818 static
3819 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3820                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3821   int i = 0;
3822
3823   while (i < NumElems) {
3824     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3825     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3826     if (!(Elt.getNode() &&
3827          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3828       break;
3829     ++i;
3830   }
3831
3832   return i;
3833 }
3834
3835 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3836 /// MaskE correspond consecutively to elements from one of the vector operands,
3837 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3838 static
3839 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3840                               int OpIdx, int NumElems, unsigned &OpNum) {
3841   bool SeenV1 = false;
3842   bool SeenV2 = false;
3843
3844   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3845     int Idx = SVOp->getMaskElt(i);
3846     // Ignore undef indicies
3847     if (Idx < 0)
3848       continue;
3849
3850     if (Idx < NumElems)
3851       SeenV1 = true;
3852     else
3853       SeenV2 = true;
3854
3855     // Only accept consecutive elements from the same vector
3856     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3857       return false;
3858   }
3859
3860   OpNum = SeenV1 ? 0 : 1;
3861   return true;
3862 }
3863
3864 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3865 /// logical left shift of a vector.
3866 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3867                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3868   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3869   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3870               false /* check zeros from right */, DAG);
3871   unsigned OpSrc;
3872
3873   if (!NumZeros)
3874     return false;
3875
3876   // Considering the elements in the mask that are not consecutive zeros,
3877   // check if they consecutively come from only one of the source vectors.
3878   //
3879   //               V1 = {X, A, B, C}     0
3880   //                         \  \  \    /
3881   //   vector_shuffle V1, V2 <1, 2, 3, X>
3882   //
3883   if (!isShuffleMaskConsecutive(SVOp,
3884             0,                   // Mask Start Index
3885             NumElems-NumZeros-1, // Mask End Index
3886             NumZeros,            // Where to start looking in the src vector
3887             NumElems,            // Number of elements in vector
3888             OpSrc))              // Which source operand ?
3889     return false;
3890
3891   isLeft = false;
3892   ShAmt = NumZeros;
3893   ShVal = SVOp->getOperand(OpSrc);
3894   return true;
3895 }
3896
3897 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3898 /// logical left shift of a vector.
3899 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3900                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3901   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3902   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3903               true /* check zeros from left */, DAG);
3904   unsigned OpSrc;
3905
3906   if (!NumZeros)
3907     return false;
3908
3909   // Considering the elements in the mask that are not consecutive zeros,
3910   // check if they consecutively come from only one of the source vectors.
3911   //
3912   //                           0    { A, B, X, X } = V2
3913   //                          / \    /  /
3914   //   vector_shuffle V1, V2 <X, X, 4, 5>
3915   //
3916   if (!isShuffleMaskConsecutive(SVOp,
3917             NumZeros,     // Mask Start Index
3918             NumElems-1,   // Mask End Index
3919             0,            // Where to start looking in the src vector
3920             NumElems,     // Number of elements in vector
3921             OpSrc))       // Which source operand ?
3922     return false;
3923
3924   isLeft = true;
3925   ShAmt = NumZeros;
3926   ShVal = SVOp->getOperand(OpSrc);
3927   return true;
3928 }
3929
3930 /// isVectorShift - Returns true if the shuffle can be implemented as a
3931 /// logical left or right shift of a vector.
3932 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3933                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3934   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3935       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3936     return true;
3937
3938   return false;
3939 }
3940
3941 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3942 ///
3943 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3944                                        unsigned NumNonZero, unsigned NumZero,
3945                                        SelectionDAG &DAG,
3946                                        const TargetLowering &TLI) {
3947   if (NumNonZero > 8)
3948     return SDValue();
3949
3950   DebugLoc dl = Op.getDebugLoc();
3951   SDValue V(0, 0);
3952   bool First = true;
3953   for (unsigned i = 0; i < 16; ++i) {
3954     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3955     if (ThisIsNonZero && First) {
3956       if (NumZero)
3957         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3958       else
3959         V = DAG.getUNDEF(MVT::v8i16);
3960       First = false;
3961     }
3962
3963     if ((i & 1) != 0) {
3964       SDValue ThisElt(0, 0), LastElt(0, 0);
3965       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3966       if (LastIsNonZero) {
3967         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3968                               MVT::i16, Op.getOperand(i-1));
3969       }
3970       if (ThisIsNonZero) {
3971         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3972         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3973                               ThisElt, DAG.getConstant(8, MVT::i8));
3974         if (LastIsNonZero)
3975           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3976       } else
3977         ThisElt = LastElt;
3978
3979       if (ThisElt.getNode())
3980         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3981                         DAG.getIntPtrConstant(i/2));
3982     }
3983   }
3984
3985   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3986 }
3987
3988 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3989 ///
3990 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3991                                      unsigned NumNonZero, unsigned NumZero,
3992                                      SelectionDAG &DAG,
3993                                      const TargetLowering &TLI) {
3994   if (NumNonZero > 4)
3995     return SDValue();
3996
3997   DebugLoc dl = Op.getDebugLoc();
3998   SDValue V(0, 0);
3999   bool First = true;
4000   for (unsigned i = 0; i < 8; ++i) {
4001     bool isNonZero = (NonZeros & (1 << i)) != 0;
4002     if (isNonZero) {
4003       if (First) {
4004         if (NumZero)
4005           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4006         else
4007           V = DAG.getUNDEF(MVT::v8i16);
4008         First = false;
4009       }
4010       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4011                       MVT::v8i16, V, Op.getOperand(i),
4012                       DAG.getIntPtrConstant(i));
4013     }
4014   }
4015
4016   return V;
4017 }
4018
4019 /// getVShift - Return a vector logical shift node.
4020 ///
4021 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4022                          unsigned NumBits, SelectionDAG &DAG,
4023                          const TargetLowering &TLI, DebugLoc dl) {
4024   bool isMMX = VT.getSizeInBits() == 64;
4025   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
4026   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4027   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
4028   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4029                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4030                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4031 }
4032
4033 SDValue
4034 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4035                                           SelectionDAG &DAG) const {
4036   
4037   // Check if the scalar load can be widened into a vector load. And if
4038   // the address is "base + cst" see if the cst can be "absorbed" into
4039   // the shuffle mask.
4040   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4041     SDValue Ptr = LD->getBasePtr();
4042     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4043       return SDValue();
4044     EVT PVT = LD->getValueType(0);
4045     if (PVT != MVT::i32 && PVT != MVT::f32)
4046       return SDValue();
4047
4048     int FI = -1;
4049     int64_t Offset = 0;
4050     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4051       FI = FINode->getIndex();
4052       Offset = 0;
4053     } else if (Ptr.getOpcode() == ISD::ADD &&
4054                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4055                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4056       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4057       Offset = Ptr.getConstantOperandVal(1);
4058       Ptr = Ptr.getOperand(0);
4059     } else {
4060       return SDValue();
4061     }
4062
4063     SDValue Chain = LD->getChain();
4064     // Make sure the stack object alignment is at least 16.
4065     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4066     if (DAG.InferPtrAlignment(Ptr) < 16) {
4067       if (MFI->isFixedObjectIndex(FI)) {
4068         // Can't change the alignment. FIXME: It's possible to compute
4069         // the exact stack offset and reference FI + adjust offset instead.
4070         // If someone *really* cares about this. That's the way to implement it.
4071         return SDValue();
4072       } else {
4073         MFI->setObjectAlignment(FI, 16);
4074       }
4075     }
4076
4077     // (Offset % 16) must be multiple of 4. Then address is then
4078     // Ptr + (Offset & ~15).
4079     if (Offset < 0)
4080       return SDValue();
4081     if ((Offset % 16) & 3)
4082       return SDValue();
4083     int64_t StartOffset = Offset & ~15;
4084     if (StartOffset)
4085       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4086                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4087
4088     int EltNo = (Offset - StartOffset) >> 2;
4089     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4090     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4091     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
4092                              false, false, 0);
4093     // Canonicalize it to a v4i32 shuffle.
4094     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4095     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4096                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4097                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
4098   }
4099
4100   return SDValue();
4101 }
4102
4103 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
4104 /// vector of type 'VT', see if the elements can be replaced by a single large 
4105 /// load which has the same value as a build_vector whose operands are 'elts'.
4106 ///
4107 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4108 /// 
4109 /// FIXME: we'd also like to handle the case where the last elements are zero
4110 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4111 /// There's even a handy isZeroNode for that purpose.
4112 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4113                                         DebugLoc &dl, SelectionDAG &DAG) {
4114   EVT EltVT = VT.getVectorElementType();
4115   unsigned NumElems = Elts.size();
4116   
4117   LoadSDNode *LDBase = NULL;
4118   unsigned LastLoadedElt = -1U;
4119   
4120   // For each element in the initializer, see if we've found a load or an undef.
4121   // If we don't find an initial load element, or later load elements are 
4122   // non-consecutive, bail out.
4123   for (unsigned i = 0; i < NumElems; ++i) {
4124     SDValue Elt = Elts[i];
4125     
4126     if (!Elt.getNode() ||
4127         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4128       return SDValue();
4129     if (!LDBase) {
4130       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4131         return SDValue();
4132       LDBase = cast<LoadSDNode>(Elt.getNode());
4133       LastLoadedElt = i;
4134       continue;
4135     }
4136     if (Elt.getOpcode() == ISD::UNDEF)
4137       continue;
4138
4139     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4140     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4141       return SDValue();
4142     LastLoadedElt = i;
4143   }
4144
4145   // If we have found an entire vector of loads and undefs, then return a large
4146   // load of the entire vector width starting at the base pointer.  If we found
4147   // consecutive loads for the low half, generate a vzext_load node.
4148   if (LastLoadedElt == NumElems - 1) {
4149     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4150       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
4151                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
4152                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4153     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
4154                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
4155                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4156                        LDBase->getAlignment());
4157   } else if (NumElems == 4 && LastLoadedElt == 1) {
4158     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4159     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4160     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
4161     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
4162   }
4163   return SDValue();
4164 }
4165
4166 SDValue
4167 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4168   DebugLoc dl = Op.getDebugLoc();
4169   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4170   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4171   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4172   // is present, so AllOnes is ignored.
4173   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4174       (Op.getValueType().getSizeInBits() != 256 &&
4175        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4176     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
4177     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4178     // eliminated on x86-32 hosts.
4179     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
4180       return Op;
4181
4182     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4183       return getOnesVector(Op.getValueType(), DAG, dl);
4184     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4185   }
4186
4187   EVT VT = Op.getValueType();
4188   EVT ExtVT = VT.getVectorElementType();
4189   unsigned EVTBits = ExtVT.getSizeInBits();
4190
4191   unsigned NumElems = Op.getNumOperands();
4192   unsigned NumZero  = 0;
4193   unsigned NumNonZero = 0;
4194   unsigned NonZeros = 0;
4195   bool IsAllConstants = true;
4196   SmallSet<SDValue, 8> Values;
4197   for (unsigned i = 0; i < NumElems; ++i) {
4198     SDValue Elt = Op.getOperand(i);
4199     if (Elt.getOpcode() == ISD::UNDEF)
4200       continue;
4201     Values.insert(Elt);
4202     if (Elt.getOpcode() != ISD::Constant &&
4203         Elt.getOpcode() != ISD::ConstantFP)
4204       IsAllConstants = false;
4205     if (X86::isZeroNode(Elt))
4206       NumZero++;
4207     else {
4208       NonZeros |= (1 << i);
4209       NumNonZero++;
4210     }
4211   }
4212
4213   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4214   if (NumNonZero == 0)
4215     return DAG.getUNDEF(VT);
4216
4217   // Special case for single non-zero, non-undef, element.
4218   if (NumNonZero == 1) {
4219     unsigned Idx = CountTrailingZeros_32(NonZeros);
4220     SDValue Item = Op.getOperand(Idx);
4221
4222     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4223     // the value are obviously zero, truncate the value to i32 and do the
4224     // insertion that way.  Only do this if the value is non-constant or if the
4225     // value is a constant being inserted into element 0.  It is cheaper to do
4226     // a constant pool load than it is to do a movd + shuffle.
4227     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4228         (!IsAllConstants || Idx == 0)) {
4229       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4230         // Handle MMX and SSE both.
4231         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
4232         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
4233
4234         // Truncate the value (which may itself be a constant) to i32, and
4235         // convert it to a vector with movd (S2V+shuffle to zero extend).
4236         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4237         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4238         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4239                                            Subtarget->hasSSE2(), DAG);
4240
4241         // Now we have our 32-bit value zero extended in the low element of
4242         // a vector.  If Idx != 0, swizzle it into place.
4243         if (Idx != 0) {
4244           SmallVector<int, 4> Mask;
4245           Mask.push_back(Idx);
4246           for (unsigned i = 1; i != VecElts; ++i)
4247             Mask.push_back(i);
4248           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4249                                       DAG.getUNDEF(Item.getValueType()),
4250                                       &Mask[0]);
4251         }
4252         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4253       }
4254     }
4255
4256     // If we have a constant or non-constant insertion into the low element of
4257     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4258     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4259     // depending on what the source datatype is.
4260     if (Idx == 0) {
4261       if (NumZero == 0) {
4262         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4263       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4264           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4265         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4266         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4267         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4268                                            DAG);
4269       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4270         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4271         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
4272         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4273         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4274                                            Subtarget->hasSSE2(), DAG);
4275         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4276       }
4277     }
4278
4279     // Is it a vector logical left shift?
4280     if (NumElems == 2 && Idx == 1 &&
4281         X86::isZeroNode(Op.getOperand(0)) &&
4282         !X86::isZeroNode(Op.getOperand(1))) {
4283       unsigned NumBits = VT.getSizeInBits();
4284       return getVShift(true, VT,
4285                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4286                                    VT, Op.getOperand(1)),
4287                        NumBits/2, DAG, *this, dl);
4288     }
4289
4290     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4291       return SDValue();
4292
4293     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4294     // is a non-constant being inserted into an element other than the low one,
4295     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4296     // movd/movss) to move this into the low element, then shuffle it into
4297     // place.
4298     if (EVTBits == 32) {
4299       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4300
4301       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4302       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4303                                          Subtarget->hasSSE2(), DAG);
4304       SmallVector<int, 8> MaskVec;
4305       for (unsigned i = 0; i < NumElems; i++)
4306         MaskVec.push_back(i == Idx ? 0 : 1);
4307       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4308     }
4309   }
4310
4311   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4312   if (Values.size() == 1) {
4313     if (EVTBits == 32) {
4314       // Instead of a shuffle like this:
4315       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4316       // Check if it's possible to issue this instead.
4317       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4318       unsigned Idx = CountTrailingZeros_32(NonZeros);
4319       SDValue Item = Op.getOperand(Idx);
4320       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4321         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4322     }
4323     return SDValue();
4324   }
4325
4326   // A vector full of immediates; various special cases are already
4327   // handled, so this is best done with a single constant-pool load.
4328   if (IsAllConstants)
4329     return SDValue();
4330
4331   // Let legalizer expand 2-wide build_vectors.
4332   if (EVTBits == 64) {
4333     if (NumNonZero == 1) {
4334       // One half is zero or undef.
4335       unsigned Idx = CountTrailingZeros_32(NonZeros);
4336       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4337                                  Op.getOperand(Idx));
4338       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4339                                          Subtarget->hasSSE2(), DAG);
4340     }
4341     return SDValue();
4342   }
4343
4344   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4345   if (EVTBits == 8 && NumElems == 16) {
4346     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4347                                         *this);
4348     if (V.getNode()) return V;
4349   }
4350
4351   if (EVTBits == 16 && NumElems == 8) {
4352     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4353                                       *this);
4354     if (V.getNode()) return V;
4355   }
4356
4357   // If element VT is == 32 bits, turn it into a number of shuffles.
4358   SmallVector<SDValue, 8> V;
4359   V.resize(NumElems);
4360   if (NumElems == 4 && NumZero > 0) {
4361     for (unsigned i = 0; i < 4; ++i) {
4362       bool isZero = !(NonZeros & (1 << i));
4363       if (isZero)
4364         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4365       else
4366         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4367     }
4368
4369     for (unsigned i = 0; i < 2; ++i) {
4370       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4371         default: break;
4372         case 0:
4373           V[i] = V[i*2];  // Must be a zero vector.
4374           break;
4375         case 1:
4376           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4377           break;
4378         case 2:
4379           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4380           break;
4381         case 3:
4382           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4383           break;
4384       }
4385     }
4386
4387     SmallVector<int, 8> MaskVec;
4388     bool Reverse = (NonZeros & 0x3) == 2;
4389     for (unsigned i = 0; i < 2; ++i)
4390       MaskVec.push_back(Reverse ? 1-i : i);
4391     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4392     for (unsigned i = 0; i < 2; ++i)
4393       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4394     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4395   }
4396
4397   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4398     // Check for a build vector of consecutive loads.
4399     for (unsigned i = 0; i < NumElems; ++i)
4400       V[i] = Op.getOperand(i);
4401     
4402     // Check for elements which are consecutive loads.
4403     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4404     if (LD.getNode())
4405       return LD;
4406     
4407     // For SSE 4.1, use insertps to put the high elements into the low element. 
4408     if (getSubtarget()->hasSSE41()) {
4409       SDValue Result;
4410       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4411         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4412       else
4413         Result = DAG.getUNDEF(VT);
4414       
4415       for (unsigned i = 1; i < NumElems; ++i) {
4416         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4417         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4418                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4419       }
4420       return Result;
4421     }
4422     
4423     // Otherwise, expand into a number of unpckl*, start by extending each of
4424     // our (non-undef) elements to the full vector width with the element in the
4425     // bottom slot of the vector (which generates no code for SSE).
4426     for (unsigned i = 0; i < NumElems; ++i) {
4427       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4428         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4429       else
4430         V[i] = DAG.getUNDEF(VT);
4431     }
4432
4433     // Next, we iteratively mix elements, e.g. for v4f32:
4434     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4435     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4436     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4437     unsigned EltStride = NumElems >> 1;
4438     while (EltStride != 0) {
4439       for (unsigned i = 0; i < EltStride; ++i) {
4440         // If V[i+EltStride] is undef and this is the first round of mixing,
4441         // then it is safe to just drop this shuffle: V[i] is already in the
4442         // right place, the one element (since it's the first round) being
4443         // inserted as undef can be dropped.  This isn't safe for successive
4444         // rounds because they will permute elements within both vectors.
4445         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4446             EltStride == NumElems/2)
4447           continue;
4448         
4449         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4450       }
4451       EltStride >>= 1;
4452     }
4453     return V[0];
4454   }
4455   return SDValue();
4456 }
4457
4458 SDValue
4459 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4460   // We support concatenate two MMX registers and place them in a MMX
4461   // register.  This is better than doing a stack convert.
4462   DebugLoc dl = Op.getDebugLoc();
4463   EVT ResVT = Op.getValueType();
4464   assert(Op.getNumOperands() == 2);
4465   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4466          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4467   int Mask[2];
4468   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4469   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4470   InVec = Op.getOperand(1);
4471   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4472     unsigned NumElts = ResVT.getVectorNumElements();
4473     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4474     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4475                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4476   } else {
4477     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4478     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4479     Mask[0] = 0; Mask[1] = 2;
4480     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4481   }
4482   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4483 }
4484
4485 // v8i16 shuffles - Prefer shuffles in the following order:
4486 // 1. [all]   pshuflw, pshufhw, optional move
4487 // 2. [ssse3] 1 x pshufb
4488 // 3. [ssse3] 2 x pshufb + 1 x por
4489 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4490 SDValue
4491 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4492                                             SelectionDAG &DAG) const {
4493   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4494   SDValue V1 = SVOp->getOperand(0);
4495   SDValue V2 = SVOp->getOperand(1);
4496   DebugLoc dl = SVOp->getDebugLoc();
4497   SmallVector<int, 8> MaskVals;
4498
4499   // Determine if more than 1 of the words in each of the low and high quadwords
4500   // of the result come from the same quadword of one of the two inputs.  Undef
4501   // mask values count as coming from any quadword, for better codegen.
4502   SmallVector<unsigned, 4> LoQuad(4);
4503   SmallVector<unsigned, 4> HiQuad(4);
4504   BitVector InputQuads(4);
4505   for (unsigned i = 0; i < 8; ++i) {
4506     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4507     int EltIdx = SVOp->getMaskElt(i);
4508     MaskVals.push_back(EltIdx);
4509     if (EltIdx < 0) {
4510       ++Quad[0];
4511       ++Quad[1];
4512       ++Quad[2];
4513       ++Quad[3];
4514       continue;
4515     }
4516     ++Quad[EltIdx / 4];
4517     InputQuads.set(EltIdx / 4);
4518   }
4519
4520   int BestLoQuad = -1;
4521   unsigned MaxQuad = 1;
4522   for (unsigned i = 0; i < 4; ++i) {
4523     if (LoQuad[i] > MaxQuad) {
4524       BestLoQuad = i;
4525       MaxQuad = LoQuad[i];
4526     }
4527   }
4528
4529   int BestHiQuad = -1;
4530   MaxQuad = 1;
4531   for (unsigned i = 0; i < 4; ++i) {
4532     if (HiQuad[i] > MaxQuad) {
4533       BestHiQuad = i;
4534       MaxQuad = HiQuad[i];
4535     }
4536   }
4537
4538   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4539   // of the two input vectors, shuffle them into one input vector so only a
4540   // single pshufb instruction is necessary. If There are more than 2 input
4541   // quads, disable the next transformation since it does not help SSSE3.
4542   bool V1Used = InputQuads[0] || InputQuads[1];
4543   bool V2Used = InputQuads[2] || InputQuads[3];
4544   if (Subtarget->hasSSSE3()) {
4545     if (InputQuads.count() == 2 && V1Used && V2Used) {
4546       BestLoQuad = InputQuads.find_first();
4547       BestHiQuad = InputQuads.find_next(BestLoQuad);
4548     }
4549     if (InputQuads.count() > 2) {
4550       BestLoQuad = -1;
4551       BestHiQuad = -1;
4552     }
4553   }
4554
4555   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4556   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4557   // words from all 4 input quadwords.
4558   SDValue NewV;
4559   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4560     SmallVector<int, 8> MaskV;
4561     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4562     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4563     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4564                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4565                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4566     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4567
4568     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4569     // source words for the shuffle, to aid later transformations.
4570     bool AllWordsInNewV = true;
4571     bool InOrder[2] = { true, true };
4572     for (unsigned i = 0; i != 8; ++i) {
4573       int idx = MaskVals[i];
4574       if (idx != (int)i)
4575         InOrder[i/4] = false;
4576       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4577         continue;
4578       AllWordsInNewV = false;
4579       break;
4580     }
4581
4582     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4583     if (AllWordsInNewV) {
4584       for (int i = 0; i != 8; ++i) {
4585         int idx = MaskVals[i];
4586         if (idx < 0)
4587           continue;
4588         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4589         if ((idx != i) && idx < 4)
4590           pshufhw = false;
4591         if ((idx != i) && idx > 3)
4592           pshuflw = false;
4593       }
4594       V1 = NewV;
4595       V2Used = false;
4596       BestLoQuad = 0;
4597       BestHiQuad = 1;
4598     }
4599
4600     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4601     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4602     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4603       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4604       unsigned TargetMask = 0;
4605       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4606                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4607       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4608                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4609       V1 = NewV.getOperand(0);
4610       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4611     }
4612   }
4613
4614   // If we have SSSE3, and all words of the result are from 1 input vector,
4615   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4616   // is present, fall back to case 4.
4617   if (Subtarget->hasSSSE3()) {
4618     SmallVector<SDValue,16> pshufbMask;
4619
4620     // If we have elements from both input vectors, set the high bit of the
4621     // shuffle mask element to zero out elements that come from V2 in the V1
4622     // mask, and elements that come from V1 in the V2 mask, so that the two
4623     // results can be OR'd together.
4624     bool TwoInputs = V1Used && V2Used;
4625     for (unsigned i = 0; i != 8; ++i) {
4626       int EltIdx = MaskVals[i] * 2;
4627       if (TwoInputs && (EltIdx >= 16)) {
4628         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4629         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4630         continue;
4631       }
4632       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4633       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4634     }
4635     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4636     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4637                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4638                                  MVT::v16i8, &pshufbMask[0], 16));
4639     if (!TwoInputs)
4640       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4641
4642     // Calculate the shuffle mask for the second input, shuffle it, and
4643     // OR it with the first shuffled input.
4644     pshufbMask.clear();
4645     for (unsigned i = 0; i != 8; ++i) {
4646       int EltIdx = MaskVals[i] * 2;
4647       if (EltIdx < 16) {
4648         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4649         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4650         continue;
4651       }
4652       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4653       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4654     }
4655     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4656     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4657                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4658                                  MVT::v16i8, &pshufbMask[0], 16));
4659     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4660     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4661   }
4662
4663   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4664   // and update MaskVals with new element order.
4665   BitVector InOrder(8);
4666   if (BestLoQuad >= 0) {
4667     SmallVector<int, 8> MaskV;
4668     for (int i = 0; i != 4; ++i) {
4669       int idx = MaskVals[i];
4670       if (idx < 0) {
4671         MaskV.push_back(-1);
4672         InOrder.set(i);
4673       } else if ((idx / 4) == BestLoQuad) {
4674         MaskV.push_back(idx & 3);
4675         InOrder.set(i);
4676       } else {
4677         MaskV.push_back(-1);
4678       }
4679     }
4680     for (unsigned i = 4; i != 8; ++i)
4681       MaskV.push_back(i);
4682     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4683                                 &MaskV[0]);
4684
4685     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4686       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4687                                NewV.getOperand(0),
4688                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4689                                DAG);
4690   }
4691
4692   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4693   // and update MaskVals with the new element order.
4694   if (BestHiQuad >= 0) {
4695     SmallVector<int, 8> MaskV;
4696     for (unsigned i = 0; i != 4; ++i)
4697       MaskV.push_back(i);
4698     for (unsigned i = 4; i != 8; ++i) {
4699       int idx = MaskVals[i];
4700       if (idx < 0) {
4701         MaskV.push_back(-1);
4702         InOrder.set(i);
4703       } else if ((idx / 4) == BestHiQuad) {
4704         MaskV.push_back((idx & 3) + 4);
4705         InOrder.set(i);
4706       } else {
4707         MaskV.push_back(-1);
4708       }
4709     }
4710     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4711                                 &MaskV[0]);
4712
4713     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4714       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4715                               NewV.getOperand(0),
4716                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4717                               DAG);
4718   }
4719
4720   // In case BestHi & BestLo were both -1, which means each quadword has a word
4721   // from each of the four input quadwords, calculate the InOrder bitvector now
4722   // before falling through to the insert/extract cleanup.
4723   if (BestLoQuad == -1 && BestHiQuad == -1) {
4724     NewV = V1;
4725     for (int i = 0; i != 8; ++i)
4726       if (MaskVals[i] < 0 || MaskVals[i] == i)
4727         InOrder.set(i);
4728   }
4729
4730   // The other elements are put in the right place using pextrw and pinsrw.
4731   for (unsigned i = 0; i != 8; ++i) {
4732     if (InOrder[i])
4733       continue;
4734     int EltIdx = MaskVals[i];
4735     if (EltIdx < 0)
4736       continue;
4737     SDValue ExtOp = (EltIdx < 8)
4738     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4739                   DAG.getIntPtrConstant(EltIdx))
4740     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4741                   DAG.getIntPtrConstant(EltIdx - 8));
4742     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4743                        DAG.getIntPtrConstant(i));
4744   }
4745   return NewV;
4746 }
4747
4748 // v16i8 shuffles - Prefer shuffles in the following order:
4749 // 1. [ssse3] 1 x pshufb
4750 // 2. [ssse3] 2 x pshufb + 1 x por
4751 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4752 static
4753 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4754                                  SelectionDAG &DAG,
4755                                  const X86TargetLowering &TLI) {
4756   SDValue V1 = SVOp->getOperand(0);
4757   SDValue V2 = SVOp->getOperand(1);
4758   DebugLoc dl = SVOp->getDebugLoc();
4759   SmallVector<int, 16> MaskVals;
4760   SVOp->getMask(MaskVals);
4761
4762   // If we have SSSE3, case 1 is generated when all result bytes come from
4763   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4764   // present, fall back to case 3.
4765   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4766   bool V1Only = true;
4767   bool V2Only = true;
4768   for (unsigned i = 0; i < 16; ++i) {
4769     int EltIdx = MaskVals[i];
4770     if (EltIdx < 0)
4771       continue;
4772     if (EltIdx < 16)
4773       V2Only = false;
4774     else
4775       V1Only = false;
4776   }
4777
4778   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4779   if (TLI.getSubtarget()->hasSSSE3()) {
4780     SmallVector<SDValue,16> pshufbMask;
4781
4782     // If all result elements are from one input vector, then only translate
4783     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4784     //
4785     // Otherwise, we have elements from both input vectors, and must zero out
4786     // elements that come from V2 in the first mask, and V1 in the second mask
4787     // so that we can OR them together.
4788     bool TwoInputs = !(V1Only || V2Only);
4789     for (unsigned i = 0; i != 16; ++i) {
4790       int EltIdx = MaskVals[i];
4791       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4792         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4793         continue;
4794       }
4795       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4796     }
4797     // If all the elements are from V2, assign it to V1 and return after
4798     // building the first pshufb.
4799     if (V2Only)
4800       V1 = V2;
4801     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4802                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4803                                  MVT::v16i8, &pshufbMask[0], 16));
4804     if (!TwoInputs)
4805       return V1;
4806
4807     // Calculate the shuffle mask for the second input, shuffle it, and
4808     // OR it with the first shuffled input.
4809     pshufbMask.clear();
4810     for (unsigned i = 0; i != 16; ++i) {
4811       int EltIdx = MaskVals[i];
4812       if (EltIdx < 16) {
4813         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4814         continue;
4815       }
4816       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4817     }
4818     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4819                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4820                                  MVT::v16i8, &pshufbMask[0], 16));
4821     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4822   }
4823
4824   // No SSSE3 - Calculate in place words and then fix all out of place words
4825   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4826   // the 16 different words that comprise the two doublequadword input vectors.
4827   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4828   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4829   SDValue NewV = V2Only ? V2 : V1;
4830   for (int i = 0; i != 8; ++i) {
4831     int Elt0 = MaskVals[i*2];
4832     int Elt1 = MaskVals[i*2+1];
4833
4834     // This word of the result is all undef, skip it.
4835     if (Elt0 < 0 && Elt1 < 0)
4836       continue;
4837
4838     // This word of the result is already in the correct place, skip it.
4839     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4840       continue;
4841     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4842       continue;
4843
4844     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4845     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4846     SDValue InsElt;
4847
4848     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4849     // using a single extract together, load it and store it.
4850     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4851       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4852                            DAG.getIntPtrConstant(Elt1 / 2));
4853       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4854                         DAG.getIntPtrConstant(i));
4855       continue;
4856     }
4857
4858     // If Elt1 is defined, extract it from the appropriate source.  If the
4859     // source byte is not also odd, shift the extracted word left 8 bits
4860     // otherwise clear the bottom 8 bits if we need to do an or.
4861     if (Elt1 >= 0) {
4862       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4863                            DAG.getIntPtrConstant(Elt1 / 2));
4864       if ((Elt1 & 1) == 0)
4865         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4866                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4867       else if (Elt0 >= 0)
4868         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4869                              DAG.getConstant(0xFF00, MVT::i16));
4870     }
4871     // If Elt0 is defined, extract it from the appropriate source.  If the
4872     // source byte is not also even, shift the extracted word right 8 bits. If
4873     // Elt1 was also defined, OR the extracted values together before
4874     // inserting them in the result.
4875     if (Elt0 >= 0) {
4876       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4877                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4878       if ((Elt0 & 1) != 0)
4879         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4880                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4881       else if (Elt1 >= 0)
4882         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4883                              DAG.getConstant(0x00FF, MVT::i16));
4884       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4885                          : InsElt0;
4886     }
4887     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4888                        DAG.getIntPtrConstant(i));
4889   }
4890   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4891 }
4892
4893 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4894 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4895 /// done when every pair / quad of shuffle mask elements point to elements in
4896 /// the right sequence. e.g.
4897 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4898 static
4899 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4900                                  SelectionDAG &DAG, DebugLoc dl) {
4901   EVT VT = SVOp->getValueType(0);
4902   SDValue V1 = SVOp->getOperand(0);
4903   SDValue V2 = SVOp->getOperand(1);
4904   unsigned NumElems = VT.getVectorNumElements();
4905   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4906   EVT NewVT;
4907   switch (VT.getSimpleVT().SimpleTy) {
4908   default: assert(false && "Unexpected!");
4909   case MVT::v4f32: NewVT = MVT::v2f64; break;
4910   case MVT::v4i32: NewVT = MVT::v2i64; break;
4911   case MVT::v8i16: NewVT = MVT::v4i32; break;
4912   case MVT::v16i8: NewVT = MVT::v4i32; break;
4913   }
4914
4915   int Scale = NumElems / NewWidth;
4916   SmallVector<int, 8> MaskVec;
4917   for (unsigned i = 0; i < NumElems; i += Scale) {
4918     int StartIdx = -1;
4919     for (int j = 0; j < Scale; ++j) {
4920       int EltIdx = SVOp->getMaskElt(i+j);
4921       if (EltIdx < 0)
4922         continue;
4923       if (StartIdx == -1)
4924         StartIdx = EltIdx - (EltIdx % Scale);
4925       if (EltIdx != StartIdx + j)
4926         return SDValue();
4927     }
4928     if (StartIdx == -1)
4929       MaskVec.push_back(-1);
4930     else
4931       MaskVec.push_back(StartIdx / Scale);
4932   }
4933
4934   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4935   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4936   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4937 }
4938
4939 /// getVZextMovL - Return a zero-extending vector move low node.
4940 ///
4941 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4942                             SDValue SrcOp, SelectionDAG &DAG,
4943                             const X86Subtarget *Subtarget, DebugLoc dl) {
4944   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4945     LoadSDNode *LD = NULL;
4946     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4947       LD = dyn_cast<LoadSDNode>(SrcOp);
4948     if (!LD) {
4949       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4950       // instead.
4951       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4952       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4953           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4954           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4955           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4956         // PR2108
4957         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4958         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4959                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4960                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4961                                                    OpVT,
4962                                                    SrcOp.getOperand(0)
4963                                                           .getOperand(0))));
4964       }
4965     }
4966   }
4967
4968   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4969                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4970                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4971                                              OpVT, SrcOp)));
4972 }
4973
4974 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4975 /// shuffles.
4976 static SDValue
4977 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4978   SDValue V1 = SVOp->getOperand(0);
4979   SDValue V2 = SVOp->getOperand(1);
4980   DebugLoc dl = SVOp->getDebugLoc();
4981   EVT VT = SVOp->getValueType(0);
4982
4983   SmallVector<std::pair<int, int>, 8> Locs;
4984   Locs.resize(4);
4985   SmallVector<int, 8> Mask1(4U, -1);
4986   SmallVector<int, 8> PermMask;
4987   SVOp->getMask(PermMask);
4988
4989   unsigned NumHi = 0;
4990   unsigned NumLo = 0;
4991   for (unsigned i = 0; i != 4; ++i) {
4992     int Idx = PermMask[i];
4993     if (Idx < 0) {
4994       Locs[i] = std::make_pair(-1, -1);
4995     } else {
4996       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4997       if (Idx < 4) {
4998         Locs[i] = std::make_pair(0, NumLo);
4999         Mask1[NumLo] = Idx;
5000         NumLo++;
5001       } else {
5002         Locs[i] = std::make_pair(1, NumHi);
5003         if (2+NumHi < 4)
5004           Mask1[2+NumHi] = Idx;
5005         NumHi++;
5006       }
5007     }
5008   }
5009
5010   if (NumLo <= 2 && NumHi <= 2) {
5011     // If no more than two elements come from either vector. This can be
5012     // implemented with two shuffles. First shuffle gather the elements.
5013     // The second shuffle, which takes the first shuffle as both of its
5014     // vector operands, put the elements into the right order.
5015     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5016
5017     SmallVector<int, 8> Mask2(4U, -1);
5018
5019     for (unsigned i = 0; i != 4; ++i) {
5020       if (Locs[i].first == -1)
5021         continue;
5022       else {
5023         unsigned Idx = (i < 2) ? 0 : 4;
5024         Idx += Locs[i].first * 2 + Locs[i].second;
5025         Mask2[i] = Idx;
5026       }
5027     }
5028
5029     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5030   } else if (NumLo == 3 || NumHi == 3) {
5031     // Otherwise, we must have three elements from one vector, call it X, and
5032     // one element from the other, call it Y.  First, use a shufps to build an
5033     // intermediate vector with the one element from Y and the element from X
5034     // that will be in the same half in the final destination (the indexes don't
5035     // matter). Then, use a shufps to build the final vector, taking the half
5036     // containing the element from Y from the intermediate, and the other half
5037     // from X.
5038     if (NumHi == 3) {
5039       // Normalize it so the 3 elements come from V1.
5040       CommuteVectorShuffleMask(PermMask, VT);
5041       std::swap(V1, V2);
5042     }
5043
5044     // Find the element from V2.
5045     unsigned HiIndex;
5046     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5047       int Val = PermMask[HiIndex];
5048       if (Val < 0)
5049         continue;
5050       if (Val >= 4)
5051         break;
5052     }
5053
5054     Mask1[0] = PermMask[HiIndex];
5055     Mask1[1] = -1;
5056     Mask1[2] = PermMask[HiIndex^1];
5057     Mask1[3] = -1;
5058     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5059
5060     if (HiIndex >= 2) {
5061       Mask1[0] = PermMask[0];
5062       Mask1[1] = PermMask[1];
5063       Mask1[2] = HiIndex & 1 ? 6 : 4;
5064       Mask1[3] = HiIndex & 1 ? 4 : 6;
5065       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5066     } else {
5067       Mask1[0] = HiIndex & 1 ? 2 : 0;
5068       Mask1[1] = HiIndex & 1 ? 0 : 2;
5069       Mask1[2] = PermMask[2];
5070       Mask1[3] = PermMask[3];
5071       if (Mask1[2] >= 0)
5072         Mask1[2] += 4;
5073       if (Mask1[3] >= 0)
5074         Mask1[3] += 4;
5075       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5076     }
5077   }
5078
5079   // Break it into (shuffle shuffle_hi, shuffle_lo).
5080   Locs.clear();
5081   SmallVector<int,8> LoMask(4U, -1);
5082   SmallVector<int,8> HiMask(4U, -1);
5083
5084   SmallVector<int,8> *MaskPtr = &LoMask;
5085   unsigned MaskIdx = 0;
5086   unsigned LoIdx = 0;
5087   unsigned HiIdx = 2;
5088   for (unsigned i = 0; i != 4; ++i) {
5089     if (i == 2) {
5090       MaskPtr = &HiMask;
5091       MaskIdx = 1;
5092       LoIdx = 0;
5093       HiIdx = 2;
5094     }
5095     int Idx = PermMask[i];
5096     if (Idx < 0) {
5097       Locs[i] = std::make_pair(-1, -1);
5098     } else if (Idx < 4) {
5099       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5100       (*MaskPtr)[LoIdx] = Idx;
5101       LoIdx++;
5102     } else {
5103       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5104       (*MaskPtr)[HiIdx] = Idx;
5105       HiIdx++;
5106     }
5107   }
5108
5109   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5110   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5111   SmallVector<int, 8> MaskOps;
5112   for (unsigned i = 0; i != 4; ++i) {
5113     if (Locs[i].first == -1) {
5114       MaskOps.push_back(-1);
5115     } else {
5116       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5117       MaskOps.push_back(Idx);
5118     }
5119   }
5120   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5121 }
5122
5123 static bool MayFoldVectorLoad(SDValue V) {
5124   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5125     V = V.getOperand(0);
5126   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5127     V = V.getOperand(0);
5128   if (MayFoldLoad(V))
5129     return true;
5130   return false;
5131 }
5132
5133 // FIXME: the version above should always be used. Since there's
5134 // a bug where several vector shuffles can't be folded because the
5135 // DAG is not updated during lowering and a node claims to have two
5136 // uses while it only has one, use this version, and let isel match
5137 // another instruction if the load really happens to have more than
5138 // one use. Remove this version after this bug get fixed.
5139 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5140   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5141     V = V.getOperand(0);
5142   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5143     V = V.getOperand(0);
5144   if (ISD::isNormalLoad(V.getNode()))
5145     return true;
5146   return false;
5147 }
5148
5149 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5150 /// a vector extract, and if both can be later optimized into a single load.
5151 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5152 /// here because otherwise a target specific shuffle node is going to be
5153 /// emitted for this shuffle, and the optimization not done.
5154 /// FIXME: This is probably not the best approach, but fix the problem
5155 /// until the right path is decided.
5156 static
5157 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5158                                          const TargetLowering &TLI) {
5159   EVT VT = V.getValueType();
5160   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5161
5162   // Be sure that the vector shuffle is present in a pattern like this:
5163   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5164   if (!V.hasOneUse())
5165     return false;
5166
5167   SDNode *N = *V.getNode()->use_begin();
5168   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5169     return false;
5170
5171   SDValue EltNo = N->getOperand(1);
5172   if (!isa<ConstantSDNode>(EltNo))
5173     return false;
5174
5175   // If the bit convert changed the number of elements, it is unsafe
5176   // to examine the mask.
5177   bool HasShuffleIntoBitcast = false;
5178   if (V.getOpcode() == ISD::BIT_CONVERT) {
5179     EVT SrcVT = V.getOperand(0).getValueType();
5180     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5181       return false;
5182     V = V.getOperand(0);
5183     HasShuffleIntoBitcast = true;
5184   }
5185
5186   // Select the input vector, guarding against out of range extract vector.
5187   unsigned NumElems = VT.getVectorNumElements();
5188   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5189   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5190   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5191
5192   // Skip one more bit_convert if necessary
5193   if (V.getOpcode() == ISD::BIT_CONVERT)
5194     V = V.getOperand(0);
5195
5196   if (ISD::isNormalLoad(V.getNode())) {
5197     // Is the original load suitable?
5198     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5199
5200     // FIXME: avoid the multi-use bug that is preventing lots of
5201     // of foldings to be detected, this is still wrong of course, but
5202     // give the temporary desired behavior, and if it happens that
5203     // the load has real more uses, during isel it will not fold, and
5204     // will generate poor code.
5205     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5206       return false;
5207
5208     if (!HasShuffleIntoBitcast)
5209       return true;
5210
5211     // If there's a bitcast before the shuffle, check if the load type and
5212     // alignment is valid.
5213     unsigned Align = LN0->getAlignment();
5214     unsigned NewAlign =
5215       TLI.getTargetData()->getABITypeAlignment(
5216                                     VT.getTypeForEVT(*DAG.getContext()));
5217
5218     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5219       return false;
5220   }
5221
5222   return true;
5223 }
5224
5225 static
5226 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5227                         bool HasSSE2) {
5228   SDValue V1 = Op.getOperand(0);
5229   SDValue V2 = Op.getOperand(1);
5230   EVT VT = Op.getValueType();
5231
5232   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5233
5234   if (HasSSE2 && VT == MVT::v2f64)
5235     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5236
5237   // v4f32 or v4i32
5238   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5239 }
5240
5241 static
5242 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5243   SDValue V1 = Op.getOperand(0);
5244   SDValue V2 = Op.getOperand(1);
5245   EVT VT = Op.getValueType();
5246
5247   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5248          "unsupported shuffle type");
5249
5250   if (V2.getOpcode() == ISD::UNDEF)
5251     V2 = V1;
5252
5253   // v4i32 or v4f32
5254   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5255 }
5256
5257 static
5258 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5259   SDValue V1 = Op.getOperand(0);
5260   SDValue V2 = Op.getOperand(1);
5261   EVT VT = Op.getValueType();
5262   unsigned NumElems = VT.getVectorNumElements();
5263
5264   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5265   // operand of these instructions is only memory, so check if there's a
5266   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5267   // same masks.
5268   bool CanFoldLoad = false;
5269
5270   // Trivial case, when V2 comes from a load.
5271   if (MayFoldVectorLoad(V2))
5272     CanFoldLoad = true;
5273
5274   // When V1 is a load, it can be folded later into a store in isel, example:
5275   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5276   //    turns into:
5277   //  (MOVLPSmr addr:$src1, VR128:$src2)
5278   // So, recognize this potential and also use MOVLPS or MOVLPD
5279   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5280     CanFoldLoad = true;
5281
5282   if (CanFoldLoad) {
5283     if (HasSSE2 && NumElems == 2)
5284       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5285
5286     if (NumElems == 4)
5287       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5288   }
5289
5290   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5291   // movl and movlp will both match v2i64, but v2i64 is never matched by
5292   // movl earlier because we make it strict to avoid messing with the movlp load
5293   // folding logic (see the code above getMOVLP call). Match it here then,
5294   // this is horrible, but will stay like this until we move all shuffle
5295   // matching to x86 specific nodes. Note that for the 1st condition all
5296   // types are matched with movsd.
5297   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5298     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5299   else if (HasSSE2)
5300     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5301
5302
5303   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5304
5305   // Invert the operand order and use SHUFPS to match it.
5306   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5307                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5308 }
5309
5310 static inline unsigned getUNPCKLOpcode(EVT VT) {
5311   switch(VT.getSimpleVT().SimpleTy) {
5312   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5313   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5314   case MVT::v4f32: return X86ISD::UNPCKLPS;
5315   case MVT::v2f64: return X86ISD::UNPCKLPD;
5316   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5317   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5318   default:
5319     llvm_unreachable("Unknow type for unpckl");
5320   }
5321   return 0;
5322 }
5323
5324 static inline unsigned getUNPCKHOpcode(EVT VT) {
5325   switch(VT.getSimpleVT().SimpleTy) {
5326   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5327   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5328   case MVT::v4f32: return X86ISD::UNPCKHPS;
5329   case MVT::v2f64: return X86ISD::UNPCKHPD;
5330   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5331   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5332   default:
5333     llvm_unreachable("Unknow type for unpckh");
5334   }
5335   return 0;
5336 }
5337
5338 static
5339 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5340                                const TargetLowering &TLI,
5341                                const X86Subtarget *Subtarget) {
5342   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5343   EVT VT = Op.getValueType();
5344   DebugLoc dl = Op.getDebugLoc();
5345   SDValue V1 = Op.getOperand(0);
5346   SDValue V2 = Op.getOperand(1);
5347
5348   if (isZeroShuffle(SVOp))
5349     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5350
5351   // Handle splat operations
5352   if (SVOp->isSplat()) {
5353     // Special case, this is the only place now where it's
5354     // allowed to return a vector_shuffle operation without
5355     // using a target specific node, because *hopefully* it
5356     // will be optimized away by the dag combiner.
5357     if (VT.getVectorNumElements() <= 4 &&
5358         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5359       return Op;
5360
5361     // Handle splats by matching through known masks
5362     if (VT.getVectorNumElements() <= 4)
5363       return SDValue();
5364
5365     // Canonize all of the remaining to v4f32.
5366     return PromoteSplat(SVOp, DAG);
5367   }
5368
5369   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5370   // do it!
5371   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5372     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5373     if (NewOp.getNode())
5374       return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5375   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5376     // FIXME: Figure out a cleaner way to do this.
5377     // Try to make use of movq to zero out the top part.
5378     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5379       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5380       if (NewOp.getNode()) {
5381         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5382           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5383                               DAG, Subtarget, dl);
5384       }
5385     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5386       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5387       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5388         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5389                             DAG, Subtarget, dl);
5390     }
5391   }
5392   return SDValue();
5393 }
5394
5395 SDValue
5396 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5397   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5398   SDValue V1 = Op.getOperand(0);
5399   SDValue V2 = Op.getOperand(1);
5400   EVT VT = Op.getValueType();
5401   DebugLoc dl = Op.getDebugLoc();
5402   unsigned NumElems = VT.getVectorNumElements();
5403   bool isMMX = VT.getSizeInBits() == 64;
5404   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5405   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5406   bool V1IsSplat = false;
5407   bool V2IsSplat = false;
5408   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5409   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5410   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5411   MachineFunction &MF = DAG.getMachineFunction();
5412   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5413
5414   // FIXME: this is somehow handled during isel by MMX pattern fragments. Remove
5415   // the check or come up with another solution when all MMX move to intrinsics,
5416   // but don't allow this to be considered legal, we don't want vector_shuffle
5417   // operations to be matched during isel anymore.
5418   if (isMMX && SVOp->isSplat())
5419     return Op;
5420
5421   // Vector shuffle lowering takes 3 steps:
5422   //
5423   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5424   //    narrowing and commutation of operands should be handled.
5425   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5426   //    shuffle nodes.
5427   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5428   //    so the shuffle can be broken into other shuffles and the legalizer can
5429   //    try the lowering again.
5430   //
5431   // The general ideia is that no vector_shuffle operation should be left to
5432   // be matched during isel, all of them must be converted to a target specific
5433   // node here.
5434
5435   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5436   // narrowing and commutation of operands should be handled. The actual code
5437   // doesn't include all of those, work in progress...
5438   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5439   if (NewOp.getNode())
5440     return NewOp;
5441
5442   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5443   // unpckh_undef). Only use pshufd if speed is more important than size.
5444   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5445     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5446       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5447   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5448     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5449       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5450
5451   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5452       RelaxedMayFoldVectorLoad(V1) && !isMMX)
5453     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
5454
5455   if (!isMMX && X86::isMOVHLPS_v_undef_Mask(SVOp))
5456     return getMOVHighToLow(Op, dl, DAG);
5457
5458   // Use to match splats
5459   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5460       (VT == MVT::v2f64 || VT == MVT::v2i64))
5461     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5462
5463   if (X86::isPSHUFDMask(SVOp)) {
5464     // The actual implementation will match the mask in the if above and then
5465     // during isel it can match several different instructions, not only pshufd
5466     // as its name says, sad but true, emulate the behavior for now...
5467     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5468         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5469
5470     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5471
5472     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5473       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5474
5475     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5476       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5477                                   TargetMask, DAG);
5478
5479     if (VT == MVT::v4f32)
5480       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5481                                   TargetMask, DAG);
5482   }
5483
5484   // Check if this can be converted into a logical shift.
5485   bool isLeft = false;
5486   unsigned ShAmt = 0;
5487   SDValue ShVal;
5488   bool isShift = getSubtarget()->hasSSE2() &&
5489     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5490   if (isShift && ShVal.hasOneUse()) {
5491     // If the shifted value has multiple uses, it may be cheaper to use
5492     // v_set0 + movlhps or movhlps, etc.
5493     EVT EltVT = VT.getVectorElementType();
5494     ShAmt *= EltVT.getSizeInBits();
5495     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5496   }
5497
5498   if (X86::isMOVLMask(SVOp)) {
5499     if (V1IsUndef)
5500       return V2;
5501     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5502       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5503     if (!isMMX && !X86::isMOVLPMask(SVOp)) {
5504       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5505         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5506
5507       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5508         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5509     }
5510   }
5511
5512   // FIXME: fold these into legal mask.
5513   if (!isMMX) {
5514     if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5515       return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5516
5517     if (X86::isMOVHLPSMask(SVOp))
5518       return getMOVHighToLow(Op, dl, DAG);
5519
5520     if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5521       return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5522
5523     if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5524       return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5525
5526     if (X86::isMOVLPMask(SVOp))
5527       return getMOVLP(Op, dl, DAG, HasSSE2);
5528   }
5529
5530   if (ShouldXformToMOVHLPS(SVOp) ||
5531       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5532     return CommuteVectorShuffle(SVOp, DAG);
5533
5534   if (isShift) {
5535     // No better options. Use a vshl / vsrl.
5536     EVT EltVT = VT.getVectorElementType();
5537     ShAmt *= EltVT.getSizeInBits();
5538     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5539   }
5540
5541   bool Commuted = false;
5542   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5543   // 1,1,1,1 -> v8i16 though.
5544   V1IsSplat = isSplatVector(V1.getNode());
5545   V2IsSplat = isSplatVector(V2.getNode());
5546
5547   // Canonicalize the splat or undef, if present, to be on the RHS.
5548   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5549     Op = CommuteVectorShuffle(SVOp, DAG);
5550     SVOp = cast<ShuffleVectorSDNode>(Op);
5551     V1 = SVOp->getOperand(0);
5552     V2 = SVOp->getOperand(1);
5553     std::swap(V1IsSplat, V2IsSplat);
5554     std::swap(V1IsUndef, V2IsUndef);
5555     Commuted = true;
5556   }
5557
5558   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5559     // Shuffling low element of v1 into undef, just return v1.
5560     if (V2IsUndef)
5561       return V1;
5562     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5563     // the instruction selector will not match, so get a canonical MOVL with
5564     // swapped operands to undo the commute.
5565     return getMOVL(DAG, dl, VT, V2, V1);
5566   }
5567
5568   if (X86::isUNPCKLMask(SVOp))
5569     return (isMMX) ?
5570       Op : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5571
5572   if (X86::isUNPCKHMask(SVOp))
5573     return (isMMX) ?
5574       Op : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5575
5576   if (V2IsSplat) {
5577     // Normalize mask so all entries that point to V2 points to its first
5578     // element then try to match unpck{h|l} again. If match, return a
5579     // new vector_shuffle with the corrected mask.
5580     SDValue NewMask = NormalizeMask(SVOp, DAG);
5581     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5582     if (NSVOp != SVOp) {
5583       if (X86::isUNPCKLMask(NSVOp, true)) {
5584         return NewMask;
5585       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5586         return NewMask;
5587       }
5588     }
5589   }
5590
5591   if (Commuted) {
5592     // Commute is back and try unpck* again.
5593     // FIXME: this seems wrong.
5594     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5595     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5596
5597     if (X86::isUNPCKLMask(NewSVOp))
5598       return (isMMX) ?
5599         NewOp : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5600
5601     if (X86::isUNPCKHMask(NewSVOp))
5602       return (isMMX) ?
5603         NewOp : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5604   }
5605
5606   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
5607
5608   // Normalize the node to match x86 shuffle ops if needed
5609   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5610     return CommuteVectorShuffle(SVOp, DAG);
5611
5612   // The checks below are all present in isShuffleMaskLegal, but they are
5613   // inlined here right now to enable us to directly emit target specific
5614   // nodes, and remove one by one until they don't return Op anymore.
5615   SmallVector<int, 16> M;
5616   SVOp->getMask(M);
5617
5618   if (isPALIGNRMask(M, VT, HasSSSE3))
5619     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5620                                 X86::getShufflePALIGNRImmediate(SVOp),
5621                                 DAG);
5622
5623   // Only a few shuffle masks are handled for 64-bit vectors (MMX), and
5624   // 64-bit vectors which made to this point can't be handled, they are
5625   // expanded.
5626   if (isMMX)
5627     return SDValue();
5628
5629   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5630       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5631     if (VT == MVT::v2f64)
5632       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5633     if (VT == MVT::v2i64)
5634       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5635   }
5636
5637   if (isPSHUFHWMask(M, VT))
5638     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5639                                 X86::getShufflePSHUFHWImmediate(SVOp),
5640                                 DAG);
5641
5642   if (isPSHUFLWMask(M, VT))
5643     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5644                                 X86::getShufflePSHUFLWImmediate(SVOp),
5645                                 DAG);
5646
5647   if (isSHUFPMask(M, VT)) {
5648     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5649     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5650       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5651                                   TargetMask, DAG);
5652     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5653       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5654                                   TargetMask, DAG);
5655   }
5656
5657   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5658     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5659       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5660   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5661     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5662       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5663
5664   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5665   if (VT == MVT::v8i16) {
5666     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5667     if (NewOp.getNode())
5668       return NewOp;
5669   }
5670
5671   if (VT == MVT::v16i8) {
5672     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5673     if (NewOp.getNode())
5674       return NewOp;
5675   }
5676
5677   // Handle all 4 wide cases with a number of shuffles except for MMX.
5678   if (NumElems == 4 && !isMMX)
5679     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5680
5681   return SDValue();
5682 }
5683
5684 SDValue
5685 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5686                                                 SelectionDAG &DAG) const {
5687   EVT VT = Op.getValueType();
5688   DebugLoc dl = Op.getDebugLoc();
5689   if (VT.getSizeInBits() == 8) {
5690     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5691                                     Op.getOperand(0), Op.getOperand(1));
5692     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5693                                     DAG.getValueType(VT));
5694     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5695   } else if (VT.getSizeInBits() == 16) {
5696     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5697     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5698     if (Idx == 0)
5699       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5700                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5701                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5702                                                  MVT::v4i32,
5703                                                  Op.getOperand(0)),
5704                                      Op.getOperand(1)));
5705     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5706                                     Op.getOperand(0), Op.getOperand(1));
5707     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5708                                     DAG.getValueType(VT));
5709     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5710   } else if (VT == MVT::f32) {
5711     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5712     // the result back to FR32 register. It's only worth matching if the
5713     // result has a single use which is a store or a bitcast to i32.  And in
5714     // the case of a store, it's not worth it if the index is a constant 0,
5715     // because a MOVSSmr can be used instead, which is smaller and faster.
5716     if (!Op.hasOneUse())
5717       return SDValue();
5718     SDNode *User = *Op.getNode()->use_begin();
5719     if ((User->getOpcode() != ISD::STORE ||
5720          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5721           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5722         (User->getOpcode() != ISD::BIT_CONVERT ||
5723          User->getValueType(0) != MVT::i32))
5724       return SDValue();
5725     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5726                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5727                                               Op.getOperand(0)),
5728                                               Op.getOperand(1));
5729     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5730   } else if (VT == MVT::i32) {
5731     // ExtractPS works with constant index.
5732     if (isa<ConstantSDNode>(Op.getOperand(1)))
5733       return Op;
5734   }
5735   return SDValue();
5736 }
5737
5738
5739 SDValue
5740 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5741                                            SelectionDAG &DAG) const {
5742   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5743     return SDValue();
5744
5745   if (Subtarget->hasSSE41()) {
5746     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5747     if (Res.getNode())
5748       return Res;
5749   }
5750
5751   EVT VT = Op.getValueType();
5752   DebugLoc dl = Op.getDebugLoc();
5753   // TODO: handle v16i8.
5754   if (VT.getSizeInBits() == 16) {
5755     SDValue Vec = Op.getOperand(0);
5756     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5757     if (Idx == 0)
5758       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5759                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5760                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5761                                                  MVT::v4i32, Vec),
5762                                      Op.getOperand(1)));
5763     // Transform it so it match pextrw which produces a 32-bit result.
5764     EVT EltVT = MVT::i32;
5765     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5766                                     Op.getOperand(0), Op.getOperand(1));
5767     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5768                                     DAG.getValueType(VT));
5769     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5770   } else if (VT.getSizeInBits() == 32) {
5771     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5772     if (Idx == 0)
5773       return Op;
5774
5775     // SHUFPS the element to the lowest double word, then movss.
5776     int Mask[4] = { Idx, -1, -1, -1 };
5777     EVT VVT = Op.getOperand(0).getValueType();
5778     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5779                                        DAG.getUNDEF(VVT), Mask);
5780     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5781                        DAG.getIntPtrConstant(0));
5782   } else if (VT.getSizeInBits() == 64) {
5783     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5784     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5785     //        to match extract_elt for f64.
5786     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5787     if (Idx == 0)
5788       return Op;
5789
5790     // UNPCKHPD the element to the lowest double word, then movsd.
5791     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5792     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5793     int Mask[2] = { 1, -1 };
5794     EVT VVT = Op.getOperand(0).getValueType();
5795     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5796                                        DAG.getUNDEF(VVT), Mask);
5797     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5798                        DAG.getIntPtrConstant(0));
5799   }
5800
5801   return SDValue();
5802 }
5803
5804 SDValue
5805 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5806                                                SelectionDAG &DAG) const {
5807   EVT VT = Op.getValueType();
5808   EVT EltVT = VT.getVectorElementType();
5809   DebugLoc dl = Op.getDebugLoc();
5810
5811   SDValue N0 = Op.getOperand(0);
5812   SDValue N1 = Op.getOperand(1);
5813   SDValue N2 = Op.getOperand(2);
5814
5815   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5816       isa<ConstantSDNode>(N2)) {
5817     unsigned Opc;
5818     if (VT == MVT::v8i16)
5819       Opc = X86ISD::PINSRW;
5820     else if (VT == MVT::v4i16)
5821       Opc = X86ISD::MMX_PINSRW;
5822     else if (VT == MVT::v16i8)
5823       Opc = X86ISD::PINSRB;
5824     else
5825       Opc = X86ISD::PINSRB;
5826
5827     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5828     // argument.
5829     if (N1.getValueType() != MVT::i32)
5830       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5831     if (N2.getValueType() != MVT::i32)
5832       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5833     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5834   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5835     // Bits [7:6] of the constant are the source select.  This will always be
5836     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5837     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5838     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5839     // Bits [5:4] of the constant are the destination select.  This is the
5840     //  value of the incoming immediate.
5841     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5842     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5843     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5844     // Create this as a scalar to vector..
5845     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5846     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5847   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5848     // PINSR* works with constant index.
5849     return Op;
5850   }
5851   return SDValue();
5852 }
5853
5854 SDValue
5855 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5856   EVT VT = Op.getValueType();
5857   EVT EltVT = VT.getVectorElementType();
5858
5859   if (Subtarget->hasSSE41())
5860     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5861
5862   if (EltVT == MVT::i8)
5863     return SDValue();
5864
5865   DebugLoc dl = Op.getDebugLoc();
5866   SDValue N0 = Op.getOperand(0);
5867   SDValue N1 = Op.getOperand(1);
5868   SDValue N2 = Op.getOperand(2);
5869
5870   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5871     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5872     // as its second argument.
5873     if (N1.getValueType() != MVT::i32)
5874       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5875     if (N2.getValueType() != MVT::i32)
5876       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5877     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5878                        dl, VT, N0, N1, N2);
5879   }
5880   return SDValue();
5881 }
5882
5883 SDValue
5884 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5885   DebugLoc dl = Op.getDebugLoc();
5886   
5887   if (Op.getValueType() == MVT::v1i64 &&
5888       Op.getOperand(0).getValueType() == MVT::i64)
5889     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5890
5891   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5892   EVT VT = MVT::v2i32;
5893   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5894   default: break;
5895   case MVT::v16i8:
5896   case MVT::v8i16:
5897     VT = MVT::v4i32;
5898     break;
5899   }
5900   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5901                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5902 }
5903
5904 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5905 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5906 // one of the above mentioned nodes. It has to be wrapped because otherwise
5907 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5908 // be used to form addressing mode. These wrapped nodes will be selected
5909 // into MOV32ri.
5910 SDValue
5911 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5912   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5913
5914   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5915   // global base reg.
5916   unsigned char OpFlag = 0;
5917   unsigned WrapperKind = X86ISD::Wrapper;
5918   CodeModel::Model M = getTargetMachine().getCodeModel();
5919
5920   if (Subtarget->isPICStyleRIPRel() &&
5921       (M == CodeModel::Small || M == CodeModel::Kernel))
5922     WrapperKind = X86ISD::WrapperRIP;
5923   else if (Subtarget->isPICStyleGOT())
5924     OpFlag = X86II::MO_GOTOFF;
5925   else if (Subtarget->isPICStyleStubPIC())
5926     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5927
5928   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5929                                              CP->getAlignment(),
5930                                              CP->getOffset(), OpFlag);
5931   DebugLoc DL = CP->getDebugLoc();
5932   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5933   // With PIC, the address is actually $g + Offset.
5934   if (OpFlag) {
5935     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5936                          DAG.getNode(X86ISD::GlobalBaseReg,
5937                                      DebugLoc(), getPointerTy()),
5938                          Result);
5939   }
5940
5941   return Result;
5942 }
5943
5944 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5945   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5946
5947   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5948   // global base reg.
5949   unsigned char OpFlag = 0;
5950   unsigned WrapperKind = X86ISD::Wrapper;
5951   CodeModel::Model M = getTargetMachine().getCodeModel();
5952
5953   if (Subtarget->isPICStyleRIPRel() &&
5954       (M == CodeModel::Small || M == CodeModel::Kernel))
5955     WrapperKind = X86ISD::WrapperRIP;
5956   else if (Subtarget->isPICStyleGOT())
5957     OpFlag = X86II::MO_GOTOFF;
5958   else if (Subtarget->isPICStyleStubPIC())
5959     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5960
5961   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5962                                           OpFlag);
5963   DebugLoc DL = JT->getDebugLoc();
5964   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5965
5966   // With PIC, the address is actually $g + Offset.
5967   if (OpFlag) {
5968     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5969                          DAG.getNode(X86ISD::GlobalBaseReg,
5970                                      DebugLoc(), getPointerTy()),
5971                          Result);
5972   }
5973
5974   return Result;
5975 }
5976
5977 SDValue
5978 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5979   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5980
5981   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5982   // global base reg.
5983   unsigned char OpFlag = 0;
5984   unsigned WrapperKind = X86ISD::Wrapper;
5985   CodeModel::Model M = getTargetMachine().getCodeModel();
5986
5987   if (Subtarget->isPICStyleRIPRel() &&
5988       (M == CodeModel::Small || M == CodeModel::Kernel))
5989     WrapperKind = X86ISD::WrapperRIP;
5990   else if (Subtarget->isPICStyleGOT())
5991     OpFlag = X86II::MO_GOTOFF;
5992   else if (Subtarget->isPICStyleStubPIC())
5993     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5994
5995   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5996
5997   DebugLoc DL = Op.getDebugLoc();
5998   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5999
6000
6001   // With PIC, the address is actually $g + Offset.
6002   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6003       !Subtarget->is64Bit()) {
6004     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6005                          DAG.getNode(X86ISD::GlobalBaseReg,
6006                                      DebugLoc(), getPointerTy()),
6007                          Result);
6008   }
6009
6010   return Result;
6011 }
6012
6013 SDValue
6014 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6015   // Create the TargetBlockAddressAddress node.
6016   unsigned char OpFlags =
6017     Subtarget->ClassifyBlockAddressReference();
6018   CodeModel::Model M = getTargetMachine().getCodeModel();
6019   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6020   DebugLoc dl = Op.getDebugLoc();
6021   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6022                                        /*isTarget=*/true, OpFlags);
6023
6024   if (Subtarget->isPICStyleRIPRel() &&
6025       (M == CodeModel::Small || M == CodeModel::Kernel))
6026     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6027   else
6028     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6029
6030   // With PIC, the address is actually $g + Offset.
6031   if (isGlobalRelativeToPICBase(OpFlags)) {
6032     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6033                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6034                          Result);
6035   }
6036
6037   return Result;
6038 }
6039
6040 SDValue
6041 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6042                                       int64_t Offset,
6043                                       SelectionDAG &DAG) const {
6044   // Create the TargetGlobalAddress node, folding in the constant
6045   // offset if it is legal.
6046   unsigned char OpFlags =
6047     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6048   CodeModel::Model M = getTargetMachine().getCodeModel();
6049   SDValue Result;
6050   if (OpFlags == X86II::MO_NO_FLAG &&
6051       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6052     // A direct static reference to a global.
6053     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6054     Offset = 0;
6055   } else {
6056     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6057   }
6058
6059   if (Subtarget->isPICStyleRIPRel() &&
6060       (M == CodeModel::Small || M == CodeModel::Kernel))
6061     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6062   else
6063     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6064
6065   // With PIC, the address is actually $g + Offset.
6066   if (isGlobalRelativeToPICBase(OpFlags)) {
6067     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6068                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6069                          Result);
6070   }
6071
6072   // For globals that require a load from a stub to get the address, emit the
6073   // load.
6074   if (isGlobalStubReference(OpFlags))
6075     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6076                          PseudoSourceValue::getGOT(), 0, false, false, 0);
6077
6078   // If there was a non-zero offset that we didn't fold, create an explicit
6079   // addition for it.
6080   if (Offset != 0)
6081     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6082                          DAG.getConstant(Offset, getPointerTy()));
6083
6084   return Result;
6085 }
6086
6087 SDValue
6088 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6089   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6090   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6091   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6092 }
6093
6094 static SDValue
6095 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6096            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6097            unsigned char OperandFlags) {
6098   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6099   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6100   DebugLoc dl = GA->getDebugLoc();
6101   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6102                                            GA->getValueType(0),
6103                                            GA->getOffset(),
6104                                            OperandFlags);
6105   if (InFlag) {
6106     SDValue Ops[] = { Chain,  TGA, *InFlag };
6107     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6108   } else {
6109     SDValue Ops[]  = { Chain, TGA };
6110     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6111   }
6112
6113   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6114   MFI->setAdjustsStack(true);
6115
6116   SDValue Flag = Chain.getValue(1);
6117   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6118 }
6119
6120 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6121 static SDValue
6122 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6123                                 const EVT PtrVT) {
6124   SDValue InFlag;
6125   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6126   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6127                                      DAG.getNode(X86ISD::GlobalBaseReg,
6128                                                  DebugLoc(), PtrVT), InFlag);
6129   InFlag = Chain.getValue(1);
6130
6131   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6132 }
6133
6134 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6135 static SDValue
6136 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6137                                 const EVT PtrVT) {
6138   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6139                     X86::RAX, X86II::MO_TLSGD);
6140 }
6141
6142 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6143 // "local exec" model.
6144 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6145                                    const EVT PtrVT, TLSModel::Model model,
6146                                    bool is64Bit) {
6147   DebugLoc dl = GA->getDebugLoc();
6148   // Get the Thread Pointer
6149   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
6150                              DebugLoc(), PtrVT,
6151                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
6152                                              MVT::i32));
6153
6154   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
6155                                       NULL, 0, false, false, 0);
6156
6157   unsigned char OperandFlags = 0;
6158   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6159   // initialexec.
6160   unsigned WrapperKind = X86ISD::Wrapper;
6161   if (model == TLSModel::LocalExec) {
6162     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6163   } else if (is64Bit) {
6164     assert(model == TLSModel::InitialExec);
6165     OperandFlags = X86II::MO_GOTTPOFF;
6166     WrapperKind = X86ISD::WrapperRIP;
6167   } else {
6168     assert(model == TLSModel::InitialExec);
6169     OperandFlags = X86II::MO_INDNTPOFF;
6170   }
6171
6172   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6173   // exec)
6174   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 
6175                                            GA->getValueType(0),
6176                                            GA->getOffset(), OperandFlags);
6177   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6178
6179   if (model == TLSModel::InitialExec)
6180     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6181                          PseudoSourceValue::getGOT(), 0, false, false, 0);
6182
6183   // The address of the thread local variable is the add of the thread
6184   // pointer with the offset of the variable.
6185   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6186 }
6187
6188 SDValue
6189 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6190   
6191   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6192   const GlobalValue *GV = GA->getGlobal();
6193
6194   if (Subtarget->isTargetELF()) {
6195     // TODO: implement the "local dynamic" model
6196     // TODO: implement the "initial exec"model for pic executables
6197     
6198     // If GV is an alias then use the aliasee for determining
6199     // thread-localness.
6200     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6201       GV = GA->resolveAliasedGlobal(false);
6202     
6203     TLSModel::Model model 
6204       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6205     
6206     switch (model) {
6207       case TLSModel::GeneralDynamic:
6208       case TLSModel::LocalDynamic: // not implemented
6209         if (Subtarget->is64Bit())
6210           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6211         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6212         
6213       case TLSModel::InitialExec:
6214       case TLSModel::LocalExec:
6215         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6216                                    Subtarget->is64Bit());
6217     }
6218   } else if (Subtarget->isTargetDarwin()) {
6219     // Darwin only has one model of TLS.  Lower to that.
6220     unsigned char OpFlag = 0;
6221     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6222                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6223     
6224     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6225     // global base reg.
6226     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6227                   !Subtarget->is64Bit();
6228     if (PIC32)
6229       OpFlag = X86II::MO_TLVP_PIC_BASE;
6230     else
6231       OpFlag = X86II::MO_TLVP;
6232     DebugLoc DL = Op.getDebugLoc();    
6233     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6234                                                 getPointerTy(),
6235                                                 GA->getOffset(), OpFlag);
6236     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6237   
6238     // With PIC32, the address is actually $g + Offset.
6239     if (PIC32)
6240       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6241                            DAG.getNode(X86ISD::GlobalBaseReg,
6242                                        DebugLoc(), getPointerTy()),
6243                            Offset);
6244     
6245     // Lowering the machine isd will make sure everything is in the right
6246     // location.
6247     SDValue Args[] = { Offset };
6248     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6249     
6250     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6251     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6252     MFI->setAdjustsStack(true);
6253
6254     // And our return value (tls address) is in the standard call return value
6255     // location.
6256     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6257     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6258   }
6259   
6260   assert(false &&
6261          "TLS not implemented for this target.");
6262
6263   llvm_unreachable("Unreachable");
6264   return SDValue();
6265 }
6266
6267
6268 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6269 /// take a 2 x i32 value to shift plus a shift amount.
6270 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6271   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6272   EVT VT = Op.getValueType();
6273   unsigned VTBits = VT.getSizeInBits();
6274   DebugLoc dl = Op.getDebugLoc();
6275   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6276   SDValue ShOpLo = Op.getOperand(0);
6277   SDValue ShOpHi = Op.getOperand(1);
6278   SDValue ShAmt  = Op.getOperand(2);
6279   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6280                                      DAG.getConstant(VTBits - 1, MVT::i8))
6281                        : DAG.getConstant(0, VT);
6282
6283   SDValue Tmp2, Tmp3;
6284   if (Op.getOpcode() == ISD::SHL_PARTS) {
6285     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6286     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6287   } else {
6288     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6289     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6290   }
6291
6292   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6293                                 DAG.getConstant(VTBits, MVT::i8));
6294   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6295                              AndNode, DAG.getConstant(0, MVT::i8));
6296
6297   SDValue Hi, Lo;
6298   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6299   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6300   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6301
6302   if (Op.getOpcode() == ISD::SHL_PARTS) {
6303     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6304     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6305   } else {
6306     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6307     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6308   }
6309
6310   SDValue Ops[2] = { Lo, Hi };
6311   return DAG.getMergeValues(Ops, 2, dl);
6312 }
6313
6314 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6315                                            SelectionDAG &DAG) const {
6316   EVT SrcVT = Op.getOperand(0).getValueType();
6317
6318   if (SrcVT.isVector()) {
6319     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
6320       return Op;
6321     }
6322     return SDValue();
6323   }
6324
6325   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6326          "Unknown SINT_TO_FP to lower!");
6327
6328   // These are really Legal; return the operand so the caller accepts it as
6329   // Legal.
6330   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6331     return Op;
6332   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6333       Subtarget->is64Bit()) {
6334     return Op;
6335   }
6336
6337   DebugLoc dl = Op.getDebugLoc();
6338   unsigned Size = SrcVT.getSizeInBits()/8;
6339   MachineFunction &MF = DAG.getMachineFunction();
6340   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6341   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6342   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6343                                StackSlot,
6344                                PseudoSourceValue::getFixedStack(SSFI), 0,
6345                                false, false, 0);
6346   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6347 }
6348
6349 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6350                                      SDValue StackSlot, 
6351                                      SelectionDAG &DAG) const {
6352   // Build the FILD
6353   DebugLoc dl = Op.getDebugLoc();
6354   SDVTList Tys;
6355   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6356   if (useSSE)
6357     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6358   else
6359     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6360   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6361   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
6362                                Tys, Ops, array_lengthof(Ops));
6363
6364   if (useSSE) {
6365     Chain = Result.getValue(1);
6366     SDValue InFlag = Result.getValue(2);
6367
6368     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6369     // shouldn't be necessary except that RFP cannot be live across
6370     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6371     MachineFunction &MF = DAG.getMachineFunction();
6372     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6373     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6374     Tys = DAG.getVTList(MVT::Other);
6375     SDValue Ops[] = {
6376       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6377     };
6378     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
6379     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
6380                          PseudoSourceValue::getFixedStack(SSFI), 0,
6381                          false, false, 0);
6382   }
6383
6384   return Result;
6385 }
6386
6387 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6388 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6389                                                SelectionDAG &DAG) const {
6390   // This algorithm is not obvious. Here it is in C code, more or less:
6391   /*
6392     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6393       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6394       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6395
6396       // Copy ints to xmm registers.
6397       __m128i xh = _mm_cvtsi32_si128( hi );
6398       __m128i xl = _mm_cvtsi32_si128( lo );
6399
6400       // Combine into low half of a single xmm register.
6401       __m128i x = _mm_unpacklo_epi32( xh, xl );
6402       __m128d d;
6403       double sd;
6404
6405       // Merge in appropriate exponents to give the integer bits the right
6406       // magnitude.
6407       x = _mm_unpacklo_epi32( x, exp );
6408
6409       // Subtract away the biases to deal with the IEEE-754 double precision
6410       // implicit 1.
6411       d = _mm_sub_pd( (__m128d) x, bias );
6412
6413       // All conversions up to here are exact. The correctly rounded result is
6414       // calculated using the current rounding mode using the following
6415       // horizontal add.
6416       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6417       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6418                                 // store doesn't really need to be here (except
6419                                 // maybe to zero the other double)
6420       return sd;
6421     }
6422   */
6423
6424   DebugLoc dl = Op.getDebugLoc();
6425   LLVMContext *Context = DAG.getContext();
6426
6427   // Build some magic constants.
6428   std::vector<Constant*> CV0;
6429   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6430   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6431   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6432   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6433   Constant *C0 = ConstantVector::get(CV0);
6434   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6435
6436   std::vector<Constant*> CV1;
6437   CV1.push_back(
6438     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6439   CV1.push_back(
6440     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6441   Constant *C1 = ConstantVector::get(CV1);
6442   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6443
6444   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6445                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6446                                         Op.getOperand(0),
6447                                         DAG.getIntPtrConstant(1)));
6448   SDValue XR2 = 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(0)));
6452   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6453   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6454                               PseudoSourceValue::getConstantPool(), 0,
6455                               false, false, 16);
6456   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6457   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6458   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6459                               PseudoSourceValue::getConstantPool(), 0,
6460                               false, false, 16);
6461   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6462
6463   // Add the halves; easiest way is to swap them into another reg first.
6464   int ShufMask[2] = { 1, -1 };
6465   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6466                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6467   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6468   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6469                      DAG.getIntPtrConstant(0));
6470 }
6471
6472 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6473 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6474                                                SelectionDAG &DAG) const {
6475   DebugLoc dl = Op.getDebugLoc();
6476   // FP constant to bias correct the final result.
6477   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6478                                    MVT::f64);
6479
6480   // Load the 32-bit value into an XMM register.
6481   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6482                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6483                                          Op.getOperand(0),
6484                                          DAG.getIntPtrConstant(0)));
6485
6486   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6487                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6488                      DAG.getIntPtrConstant(0));
6489
6490   // Or the load with the bias.
6491   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6492                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6493                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6494                                                    MVT::v2f64, Load)),
6495                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6496                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6497                                                    MVT::v2f64, Bias)));
6498   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6499                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6500                    DAG.getIntPtrConstant(0));
6501
6502   // Subtract the bias.
6503   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6504
6505   // Handle final rounding.
6506   EVT DestVT = Op.getValueType();
6507
6508   if (DestVT.bitsLT(MVT::f64)) {
6509     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6510                        DAG.getIntPtrConstant(0));
6511   } else if (DestVT.bitsGT(MVT::f64)) {
6512     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6513   }
6514
6515   // Handle final rounding.
6516   return Sub;
6517 }
6518
6519 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6520                                            SelectionDAG &DAG) const {
6521   SDValue N0 = Op.getOperand(0);
6522   DebugLoc dl = Op.getDebugLoc();
6523
6524   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6525   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6526   // the optimization here.
6527   if (DAG.SignBitIsZero(N0))
6528     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6529
6530   EVT SrcVT = N0.getValueType();
6531   EVT DstVT = Op.getValueType();
6532   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6533     return LowerUINT_TO_FP_i64(Op, DAG);
6534   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6535     return LowerUINT_TO_FP_i32(Op, DAG);
6536
6537   // Make a 64-bit buffer, and use it to build an FILD.
6538   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6539   if (SrcVT == MVT::i32) {
6540     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6541     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6542                                      getPointerTy(), StackSlot, WordOff);
6543     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6544                                   StackSlot, NULL, 0, false, false, 0);
6545     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6546                                   OffsetSlot, NULL, 0, false, false, 0);
6547     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6548     return Fild;
6549   }
6550
6551   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6552   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6553                                 StackSlot, NULL, 0, false, false, 0);
6554   // For i64 source, we need to add the appropriate power of 2 if the input
6555   // was negative.  This is the same as the optimization in
6556   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6557   // we must be careful to do the computation in x87 extended precision, not
6558   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6559   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6560   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6561   SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
6562
6563   APInt FF(32, 0x5F800000ULL);
6564
6565   // Check whether the sign bit is set.
6566   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6567                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6568                                  ISD::SETLT);
6569
6570   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6571   SDValue FudgePtr = DAG.getConstantPool(
6572                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6573                                          getPointerTy());
6574
6575   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6576   SDValue Zero = DAG.getIntPtrConstant(0);
6577   SDValue Four = DAG.getIntPtrConstant(4);
6578   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6579                                Zero, Four);
6580   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6581
6582   // Load the value out, extending it from f32 to f80.
6583   // FIXME: Avoid the extend by constructing the right constant pool?
6584   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6585                                  FudgePtr, PseudoSourceValue::getConstantPool(),
6586                                  0, MVT::f32, false, false, 4);
6587   // Extend everything to 80 bits to force it to be done on x87.
6588   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6589   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6590 }
6591
6592 std::pair<SDValue,SDValue> X86TargetLowering::
6593 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6594   DebugLoc dl = Op.getDebugLoc();
6595
6596   EVT DstTy = Op.getValueType();
6597
6598   if (!IsSigned) {
6599     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6600     DstTy = MVT::i64;
6601   }
6602
6603   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6604          DstTy.getSimpleVT() >= MVT::i16 &&
6605          "Unknown FP_TO_SINT to lower!");
6606
6607   // These are really Legal.
6608   if (DstTy == MVT::i32 &&
6609       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6610     return std::make_pair(SDValue(), SDValue());
6611   if (Subtarget->is64Bit() &&
6612       DstTy == MVT::i64 &&
6613       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6614     return std::make_pair(SDValue(), SDValue());
6615
6616   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6617   // stack slot.
6618   MachineFunction &MF = DAG.getMachineFunction();
6619   unsigned MemSize = DstTy.getSizeInBits()/8;
6620   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6621   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6622
6623   unsigned Opc;
6624   switch (DstTy.getSimpleVT().SimpleTy) {
6625   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6626   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6627   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6628   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6629   }
6630
6631   SDValue Chain = DAG.getEntryNode();
6632   SDValue Value = Op.getOperand(0);
6633   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
6634     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6635     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
6636                          PseudoSourceValue::getFixedStack(SSFI), 0,
6637                          false, false, 0);
6638     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6639     SDValue Ops[] = {
6640       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
6641     };
6642     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
6643     Chain = Value.getValue(1);
6644     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6645     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6646   }
6647
6648   // Build the FP_TO_INT*_IN_MEM
6649   SDValue Ops[] = { Chain, Value, StackSlot };
6650   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
6651
6652   return std::make_pair(FIST, StackSlot);
6653 }
6654
6655 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6656                                            SelectionDAG &DAG) const {
6657   if (Op.getValueType().isVector()) {
6658     if (Op.getValueType() == MVT::v2i32 &&
6659         Op.getOperand(0).getValueType() == MVT::v2f64) {
6660       return Op;
6661     }
6662     return SDValue();
6663   }
6664
6665   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6666   SDValue FIST = Vals.first, StackSlot = Vals.second;
6667   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6668   if (FIST.getNode() == 0) return Op;
6669
6670   // Load the result.
6671   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6672                      FIST, StackSlot, NULL, 0, false, false, 0);
6673 }
6674
6675 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6676                                            SelectionDAG &DAG) const {
6677   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6678   SDValue FIST = Vals.first, StackSlot = Vals.second;
6679   assert(FIST.getNode() && "Unexpected failure");
6680
6681   // Load the result.
6682   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6683                      FIST, StackSlot, NULL, 0, false, false, 0);
6684 }
6685
6686 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6687                                      SelectionDAG &DAG) const {
6688   LLVMContext *Context = DAG.getContext();
6689   DebugLoc dl = Op.getDebugLoc();
6690   EVT VT = Op.getValueType();
6691   EVT EltVT = VT;
6692   if (VT.isVector())
6693     EltVT = VT.getVectorElementType();
6694   std::vector<Constant*> CV;
6695   if (EltVT == MVT::f64) {
6696     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6697     CV.push_back(C);
6698     CV.push_back(C);
6699   } else {
6700     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6701     CV.push_back(C);
6702     CV.push_back(C);
6703     CV.push_back(C);
6704     CV.push_back(C);
6705   }
6706   Constant *C = ConstantVector::get(CV);
6707   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6708   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6709                              PseudoSourceValue::getConstantPool(), 0,
6710                              false, false, 16);
6711   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6712 }
6713
6714 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6715   LLVMContext *Context = DAG.getContext();
6716   DebugLoc dl = Op.getDebugLoc();
6717   EVT VT = Op.getValueType();
6718   EVT EltVT = VT;
6719   if (VT.isVector())
6720     EltVT = VT.getVectorElementType();
6721   std::vector<Constant*> CV;
6722   if (EltVT == MVT::f64) {
6723     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6724     CV.push_back(C);
6725     CV.push_back(C);
6726   } else {
6727     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6728     CV.push_back(C);
6729     CV.push_back(C);
6730     CV.push_back(C);
6731     CV.push_back(C);
6732   }
6733   Constant *C = ConstantVector::get(CV);
6734   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6735   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6736                              PseudoSourceValue::getConstantPool(), 0,
6737                              false, false, 16);
6738   if (VT.isVector()) {
6739     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6740                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6741                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6742                                 Op.getOperand(0)),
6743                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6744   } else {
6745     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6746   }
6747 }
6748
6749 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6750   LLVMContext *Context = DAG.getContext();
6751   SDValue Op0 = Op.getOperand(0);
6752   SDValue Op1 = Op.getOperand(1);
6753   DebugLoc dl = Op.getDebugLoc();
6754   EVT VT = Op.getValueType();
6755   EVT SrcVT = Op1.getValueType();
6756
6757   // If second operand is smaller, extend it first.
6758   if (SrcVT.bitsLT(VT)) {
6759     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6760     SrcVT = VT;
6761   }
6762   // And if it is bigger, shrink it first.
6763   if (SrcVT.bitsGT(VT)) {
6764     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6765     SrcVT = VT;
6766   }
6767
6768   // At this point the operands and the result should have the same
6769   // type, and that won't be f80 since that is not custom lowered.
6770
6771   // First get the sign bit of second operand.
6772   std::vector<Constant*> CV;
6773   if (SrcVT == MVT::f64) {
6774     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6775     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6776   } else {
6777     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6778     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6779     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6780     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6781   }
6782   Constant *C = ConstantVector::get(CV);
6783   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6784   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6785                               PseudoSourceValue::getConstantPool(), 0,
6786                               false, false, 16);
6787   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6788
6789   // Shift sign bit right or left if the two operands have different types.
6790   if (SrcVT.bitsGT(VT)) {
6791     // Op0 is MVT::f32, Op1 is MVT::f64.
6792     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6793     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6794                           DAG.getConstant(32, MVT::i32));
6795     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6796     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6797                           DAG.getIntPtrConstant(0));
6798   }
6799
6800   // Clear first operand sign bit.
6801   CV.clear();
6802   if (VT == MVT::f64) {
6803     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6804     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6805   } else {
6806     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6807     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6808     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6809     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6810   }
6811   C = ConstantVector::get(CV);
6812   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6813   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6814                               PseudoSourceValue::getConstantPool(), 0,
6815                               false, false, 16);
6816   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6817
6818   // Or the value with the sign bit.
6819   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6820 }
6821
6822 /// Emit nodes that will be selected as "test Op0,Op0", or something
6823 /// equivalent.
6824 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6825                                     SelectionDAG &DAG) const {
6826   DebugLoc dl = Op.getDebugLoc();
6827
6828   // CF and OF aren't always set the way we want. Determine which
6829   // of these we need.
6830   bool NeedCF = false;
6831   bool NeedOF = false;
6832   switch (X86CC) {
6833   default: break;
6834   case X86::COND_A: case X86::COND_AE:
6835   case X86::COND_B: case X86::COND_BE:
6836     NeedCF = true;
6837     break;
6838   case X86::COND_G: case X86::COND_GE:
6839   case X86::COND_L: case X86::COND_LE:
6840   case X86::COND_O: case X86::COND_NO:
6841     NeedOF = true;
6842     break;
6843   }
6844
6845   // See if we can use the EFLAGS value from the operand instead of
6846   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6847   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6848   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6849     // Emit a CMP with 0, which is the TEST pattern.
6850     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6851                        DAG.getConstant(0, Op.getValueType()));
6852
6853   unsigned Opcode = 0;
6854   unsigned NumOperands = 0;
6855   switch (Op.getNode()->getOpcode()) {
6856   case ISD::ADD:
6857     // Due to an isel shortcoming, be conservative if this add is likely to be
6858     // selected as part of a load-modify-store instruction. When the root node
6859     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6860     // uses of other nodes in the match, such as the ADD in this case. This
6861     // leads to the ADD being left around and reselected, with the result being
6862     // two adds in the output.  Alas, even if none our users are stores, that
6863     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6864     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6865     // climbing the DAG back to the root, and it doesn't seem to be worth the
6866     // effort.
6867     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6868            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6869       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6870         goto default_case;
6871
6872     if (ConstantSDNode *C =
6873         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6874       // An add of one will be selected as an INC.
6875       if (C->getAPIntValue() == 1) {
6876         Opcode = X86ISD::INC;
6877         NumOperands = 1;
6878         break;
6879       }
6880
6881       // An add of negative one (subtract of one) will be selected as a DEC.
6882       if (C->getAPIntValue().isAllOnesValue()) {
6883         Opcode = X86ISD::DEC;
6884         NumOperands = 1;
6885         break;
6886       }
6887     }
6888
6889     // Otherwise use a regular EFLAGS-setting add.
6890     Opcode = X86ISD::ADD;
6891     NumOperands = 2;
6892     break;
6893   case ISD::AND: {
6894     // If the primary and result isn't used, don't bother using X86ISD::AND,
6895     // because a TEST instruction will be better.
6896     bool NonFlagUse = false;
6897     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6898            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6899       SDNode *User = *UI;
6900       unsigned UOpNo = UI.getOperandNo();
6901       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6902         // Look pass truncate.
6903         UOpNo = User->use_begin().getOperandNo();
6904         User = *User->use_begin();
6905       }
6906
6907       if (User->getOpcode() != ISD::BRCOND &&
6908           User->getOpcode() != ISD::SETCC &&
6909           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6910         NonFlagUse = true;
6911         break;
6912       }
6913     }
6914
6915     if (!NonFlagUse)
6916       break;
6917   }
6918     // FALL THROUGH
6919   case ISD::SUB:
6920   case ISD::OR:
6921   case ISD::XOR:
6922     // Due to the ISEL shortcoming noted above, be conservative if this op is
6923     // likely to be selected as part of a load-modify-store instruction.
6924     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6925            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6926       if (UI->getOpcode() == ISD::STORE)
6927         goto default_case;
6928
6929     // Otherwise use a regular EFLAGS-setting instruction.
6930     switch (Op.getNode()->getOpcode()) {
6931     default: llvm_unreachable("unexpected operator!");
6932     case ISD::SUB: Opcode = X86ISD::SUB; break;
6933     case ISD::OR:  Opcode = X86ISD::OR;  break;
6934     case ISD::XOR: Opcode = X86ISD::XOR; break;
6935     case ISD::AND: Opcode = X86ISD::AND; break;
6936     }
6937
6938     NumOperands = 2;
6939     break;
6940   case X86ISD::ADD:
6941   case X86ISD::SUB:
6942   case X86ISD::INC:
6943   case X86ISD::DEC:
6944   case X86ISD::OR:
6945   case X86ISD::XOR:
6946   case X86ISD::AND:
6947     return SDValue(Op.getNode(), 1);
6948   default:
6949   default_case:
6950     break;
6951   }
6952
6953   if (Opcode == 0)
6954     // Emit a CMP with 0, which is the TEST pattern.
6955     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6956                        DAG.getConstant(0, Op.getValueType()));
6957
6958   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6959   SmallVector<SDValue, 4> Ops;
6960   for (unsigned i = 0; i != NumOperands; ++i)
6961     Ops.push_back(Op.getOperand(i));
6962
6963   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6964   DAG.ReplaceAllUsesWith(Op, New);
6965   return SDValue(New.getNode(), 1);
6966 }
6967
6968 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6969 /// equivalent.
6970 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6971                                    SelectionDAG &DAG) const {
6972   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6973     if (C->getAPIntValue() == 0)
6974       return EmitTest(Op0, X86CC, DAG);
6975
6976   DebugLoc dl = Op0.getDebugLoc();
6977   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6978 }
6979
6980 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6981 /// if it's possible.
6982 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6983                                      DebugLoc dl, SelectionDAG &DAG) const {
6984   SDValue Op0 = And.getOperand(0);
6985   SDValue Op1 = And.getOperand(1);
6986   if (Op0.getOpcode() == ISD::TRUNCATE)
6987     Op0 = Op0.getOperand(0);
6988   if (Op1.getOpcode() == ISD::TRUNCATE)
6989     Op1 = Op1.getOperand(0);
6990
6991   SDValue LHS, RHS;
6992   if (Op1.getOpcode() == ISD::SHL)
6993     std::swap(Op0, Op1);
6994   if (Op0.getOpcode() == ISD::SHL) {
6995     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6996       if (And00C->getZExtValue() == 1) {
6997         // If we looked past a truncate, check that it's only truncating away
6998         // known zeros.
6999         unsigned BitWidth = Op0.getValueSizeInBits();
7000         unsigned AndBitWidth = And.getValueSizeInBits();
7001         if (BitWidth > AndBitWidth) {
7002           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7003           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7004           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7005             return SDValue();
7006         }
7007         LHS = Op1;
7008         RHS = Op0.getOperand(1);
7009       }
7010   } else if (Op1.getOpcode() == ISD::Constant) {
7011     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7012     SDValue AndLHS = Op0;
7013     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7014       LHS = AndLHS.getOperand(0);
7015       RHS = AndLHS.getOperand(1);
7016     }
7017   }
7018
7019   if (LHS.getNode()) {
7020     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7021     // instruction.  Since the shift amount is in-range-or-undefined, we know
7022     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7023     // the encoding for the i16 version is larger than the i32 version.
7024     // Also promote i16 to i32 for performance / code size reason.
7025     if (LHS.getValueType() == MVT::i8 ||
7026         LHS.getValueType() == MVT::i16)
7027       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7028
7029     // If the operand types disagree, extend the shift amount to match.  Since
7030     // BT ignores high bits (like shifts) we can use anyextend.
7031     if (LHS.getValueType() != RHS.getValueType())
7032       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7033
7034     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7035     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7036     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7037                        DAG.getConstant(Cond, MVT::i8), BT);
7038   }
7039
7040   return SDValue();
7041 }
7042
7043 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7044   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7045   SDValue Op0 = Op.getOperand(0);
7046   SDValue Op1 = Op.getOperand(1);
7047   DebugLoc dl = Op.getDebugLoc();
7048   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7049
7050   // Optimize to BT if possible.
7051   // Lower (X & (1 << N)) == 0 to BT(X, N).
7052   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7053   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7054   if (Op0.getOpcode() == ISD::AND &&
7055       Op0.hasOneUse() &&
7056       Op1.getOpcode() == ISD::Constant &&
7057       cast<ConstantSDNode>(Op1)->isNullValue() &&
7058       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7059     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7060     if (NewSetCC.getNode())
7061       return NewSetCC;
7062   }
7063
7064   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7065   if (Op0.getOpcode() == X86ISD::SETCC &&
7066       Op1.getOpcode() == ISD::Constant &&
7067       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7068        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7069       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7070     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7071     bool Invert = (CC == ISD::SETNE) ^
7072       cast<ConstantSDNode>(Op1)->isNullValue();
7073     if (Invert)
7074       CCode = X86::GetOppositeBranchCondition(CCode);
7075     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7076                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7077   }
7078
7079   bool isFP = Op1.getValueType().isFloatingPoint();
7080   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7081   if (X86CC == X86::COND_INVALID)
7082     return SDValue();
7083
7084   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7085
7086   // Use sbb x, x to materialize carry bit into a GPR.
7087   if (X86CC == X86::COND_B)
7088     return DAG.getNode(ISD::AND, dl, MVT::i8,
7089                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7090                                    DAG.getConstant(X86CC, MVT::i8), Cond),
7091                        DAG.getConstant(1, MVT::i8));
7092
7093   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7094                      DAG.getConstant(X86CC, MVT::i8), Cond);
7095 }
7096
7097 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7098   SDValue Cond;
7099   SDValue Op0 = Op.getOperand(0);
7100   SDValue Op1 = Op.getOperand(1);
7101   SDValue CC = Op.getOperand(2);
7102   EVT VT = Op.getValueType();
7103   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7104   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7105   DebugLoc dl = Op.getDebugLoc();
7106
7107   if (isFP) {
7108     unsigned SSECC = 8;
7109     EVT VT0 = Op0.getValueType();
7110     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7111     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7112     bool Swap = false;
7113
7114     switch (SetCCOpcode) {
7115     default: break;
7116     case ISD::SETOEQ:
7117     case ISD::SETEQ:  SSECC = 0; break;
7118     case ISD::SETOGT:
7119     case ISD::SETGT: Swap = true; // Fallthrough
7120     case ISD::SETLT:
7121     case ISD::SETOLT: SSECC = 1; break;
7122     case ISD::SETOGE:
7123     case ISD::SETGE: Swap = true; // Fallthrough
7124     case ISD::SETLE:
7125     case ISD::SETOLE: SSECC = 2; break;
7126     case ISD::SETUO:  SSECC = 3; break;
7127     case ISD::SETUNE:
7128     case ISD::SETNE:  SSECC = 4; break;
7129     case ISD::SETULE: Swap = true;
7130     case ISD::SETUGE: SSECC = 5; break;
7131     case ISD::SETULT: Swap = true;
7132     case ISD::SETUGT: SSECC = 6; break;
7133     case ISD::SETO:   SSECC = 7; break;
7134     }
7135     if (Swap)
7136       std::swap(Op0, Op1);
7137
7138     // In the two special cases we can't handle, emit two comparisons.
7139     if (SSECC == 8) {
7140       if (SetCCOpcode == ISD::SETUEQ) {
7141         SDValue UNORD, EQ;
7142         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7143         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7144         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7145       }
7146       else if (SetCCOpcode == ISD::SETONE) {
7147         SDValue ORD, NEQ;
7148         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7149         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7150         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7151       }
7152       llvm_unreachable("Illegal FP comparison");
7153     }
7154     // Handle all other FP comparisons here.
7155     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7156   }
7157
7158   // We are handling one of the integer comparisons here.  Since SSE only has
7159   // GT and EQ comparisons for integer, swapping operands and multiple
7160   // operations may be required for some comparisons.
7161   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7162   bool Swap = false, Invert = false, FlipSigns = false;
7163
7164   switch (VT.getSimpleVT().SimpleTy) {
7165   default: break;
7166   case MVT::v8i8:
7167   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7168   case MVT::v4i16:
7169   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7170   case MVT::v2i32:
7171   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7172   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7173   }
7174
7175   switch (SetCCOpcode) {
7176   default: break;
7177   case ISD::SETNE:  Invert = true;
7178   case ISD::SETEQ:  Opc = EQOpc; break;
7179   case ISD::SETLT:  Swap = true;
7180   case ISD::SETGT:  Opc = GTOpc; break;
7181   case ISD::SETGE:  Swap = true;
7182   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7183   case ISD::SETULT: Swap = true;
7184   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7185   case ISD::SETUGE: Swap = true;
7186   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7187   }
7188   if (Swap)
7189     std::swap(Op0, Op1);
7190
7191   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7192   // bits of the inputs before performing those operations.
7193   if (FlipSigns) {
7194     EVT EltVT = VT.getVectorElementType();
7195     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7196                                       EltVT);
7197     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7198     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7199                                     SignBits.size());
7200     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7201     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7202   }
7203
7204   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7205
7206   // If the logical-not of the result is required, perform that now.
7207   if (Invert)
7208     Result = DAG.getNOT(dl, Result, VT);
7209
7210   return Result;
7211 }
7212
7213 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7214 static bool isX86LogicalCmp(SDValue Op) {
7215   unsigned Opc = Op.getNode()->getOpcode();
7216   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7217     return true;
7218   if (Op.getResNo() == 1 &&
7219       (Opc == X86ISD::ADD ||
7220        Opc == X86ISD::SUB ||
7221        Opc == X86ISD::SMUL ||
7222        Opc == X86ISD::UMUL ||
7223        Opc == X86ISD::INC ||
7224        Opc == X86ISD::DEC ||
7225        Opc == X86ISD::OR ||
7226        Opc == X86ISD::XOR ||
7227        Opc == X86ISD::AND))
7228     return true;
7229
7230   return false;
7231 }
7232
7233 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7234   bool addTest = true;
7235   SDValue Cond  = Op.getOperand(0);
7236   DebugLoc dl = Op.getDebugLoc();
7237   SDValue CC;
7238
7239   if (Cond.getOpcode() == ISD::SETCC) {
7240     SDValue NewCond = LowerSETCC(Cond, DAG);
7241     if (NewCond.getNode())
7242       Cond = NewCond;
7243   }
7244
7245   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7246   SDValue Op1 = Op.getOperand(1);
7247   SDValue Op2 = Op.getOperand(2);
7248   if (Cond.getOpcode() == X86ISD::SETCC &&
7249       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7250     SDValue Cmp = Cond.getOperand(1);
7251     if (Cmp.getOpcode() == X86ISD::CMP) {
7252       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7253       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7254       ConstantSDNode *RHSC =
7255         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7256       if (N1C && N1C->isAllOnesValue() &&
7257           N2C && N2C->isNullValue() &&
7258           RHSC && RHSC->isNullValue()) {
7259         SDValue CmpOp0 = Cmp.getOperand(0);
7260         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7261                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7262         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7263                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7264       }
7265     }
7266   }
7267
7268   // Look pass (and (setcc_carry (cmp ...)), 1).
7269   if (Cond.getOpcode() == ISD::AND &&
7270       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7271     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7272     if (C && C->getAPIntValue() == 1) 
7273       Cond = Cond.getOperand(0);
7274   }
7275
7276   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7277   // setting operand in place of the X86ISD::SETCC.
7278   if (Cond.getOpcode() == X86ISD::SETCC ||
7279       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7280     CC = Cond.getOperand(0);
7281
7282     SDValue Cmp = Cond.getOperand(1);
7283     unsigned Opc = Cmp.getOpcode();
7284     EVT VT = Op.getValueType();
7285
7286     bool IllegalFPCMov = false;
7287     if (VT.isFloatingPoint() && !VT.isVector() &&
7288         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7289       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7290
7291     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7292         Opc == X86ISD::BT) { // FIXME
7293       Cond = Cmp;
7294       addTest = false;
7295     }
7296   }
7297
7298   if (addTest) {
7299     // Look pass the truncate.
7300     if (Cond.getOpcode() == ISD::TRUNCATE)
7301       Cond = Cond.getOperand(0);
7302
7303     // We know the result of AND is compared against zero. Try to match
7304     // it to BT.
7305     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7306       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7307       if (NewSetCC.getNode()) {
7308         CC = NewSetCC.getOperand(0);
7309         Cond = NewSetCC.getOperand(1);
7310         addTest = false;
7311       }
7312     }
7313   }
7314
7315   if (addTest) {
7316     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7317     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7318   }
7319
7320   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7321   // condition is true.
7322   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7323   SDValue Ops[] = { Op2, Op1, CC, Cond };
7324   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7325 }
7326
7327 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7328 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7329 // from the AND / OR.
7330 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7331   Opc = Op.getOpcode();
7332   if (Opc != ISD::OR && Opc != ISD::AND)
7333     return false;
7334   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7335           Op.getOperand(0).hasOneUse() &&
7336           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7337           Op.getOperand(1).hasOneUse());
7338 }
7339
7340 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7341 // 1 and that the SETCC node has a single use.
7342 static bool isXor1OfSetCC(SDValue Op) {
7343   if (Op.getOpcode() != ISD::XOR)
7344     return false;
7345   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7346   if (N1C && N1C->getAPIntValue() == 1) {
7347     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7348       Op.getOperand(0).hasOneUse();
7349   }
7350   return false;
7351 }
7352
7353 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7354   bool addTest = true;
7355   SDValue Chain = Op.getOperand(0);
7356   SDValue Cond  = Op.getOperand(1);
7357   SDValue Dest  = Op.getOperand(2);
7358   DebugLoc dl = Op.getDebugLoc();
7359   SDValue CC;
7360
7361   if (Cond.getOpcode() == ISD::SETCC) {
7362     SDValue NewCond = LowerSETCC(Cond, DAG);
7363     if (NewCond.getNode())
7364       Cond = NewCond;
7365   }
7366 #if 0
7367   // FIXME: LowerXALUO doesn't handle these!!
7368   else if (Cond.getOpcode() == X86ISD::ADD  ||
7369            Cond.getOpcode() == X86ISD::SUB  ||
7370            Cond.getOpcode() == X86ISD::SMUL ||
7371            Cond.getOpcode() == X86ISD::UMUL)
7372     Cond = LowerXALUO(Cond, DAG);
7373 #endif
7374
7375   // Look pass (and (setcc_carry (cmp ...)), 1).
7376   if (Cond.getOpcode() == ISD::AND &&
7377       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7378     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7379     if (C && C->getAPIntValue() == 1) 
7380       Cond = Cond.getOperand(0);
7381   }
7382
7383   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7384   // setting operand in place of the X86ISD::SETCC.
7385   if (Cond.getOpcode() == X86ISD::SETCC ||
7386       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7387     CC = Cond.getOperand(0);
7388
7389     SDValue Cmp = Cond.getOperand(1);
7390     unsigned Opc = Cmp.getOpcode();
7391     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7392     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7393       Cond = Cmp;
7394       addTest = false;
7395     } else {
7396       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7397       default: break;
7398       case X86::COND_O:
7399       case X86::COND_B:
7400         // These can only come from an arithmetic instruction with overflow,
7401         // e.g. SADDO, UADDO.
7402         Cond = Cond.getNode()->getOperand(1);
7403         addTest = false;
7404         break;
7405       }
7406     }
7407   } else {
7408     unsigned CondOpc;
7409     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7410       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7411       if (CondOpc == ISD::OR) {
7412         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7413         // two branches instead of an explicit OR instruction with a
7414         // separate test.
7415         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7416             isX86LogicalCmp(Cmp)) {
7417           CC = Cond.getOperand(0).getOperand(0);
7418           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7419                               Chain, Dest, CC, Cmp);
7420           CC = Cond.getOperand(1).getOperand(0);
7421           Cond = Cmp;
7422           addTest = false;
7423         }
7424       } else { // ISD::AND
7425         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7426         // two branches instead of an explicit AND instruction with a
7427         // separate test. However, we only do this if this block doesn't
7428         // have a fall-through edge, because this requires an explicit
7429         // jmp when the condition is false.
7430         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7431             isX86LogicalCmp(Cmp) &&
7432             Op.getNode()->hasOneUse()) {
7433           X86::CondCode CCode =
7434             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7435           CCode = X86::GetOppositeBranchCondition(CCode);
7436           CC = DAG.getConstant(CCode, MVT::i8);
7437           SDNode *User = *Op.getNode()->use_begin();
7438           // Look for an unconditional branch following this conditional branch.
7439           // We need this because we need to reverse the successors in order
7440           // to implement FCMP_OEQ.
7441           if (User->getOpcode() == ISD::BR) {
7442             SDValue FalseBB = User->getOperand(1);
7443             SDNode *NewBR =
7444               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7445             assert(NewBR == User);
7446             (void)NewBR;
7447             Dest = FalseBB;
7448
7449             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7450                                 Chain, Dest, CC, Cmp);
7451             X86::CondCode CCode =
7452               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7453             CCode = X86::GetOppositeBranchCondition(CCode);
7454             CC = DAG.getConstant(CCode, MVT::i8);
7455             Cond = Cmp;
7456             addTest = false;
7457           }
7458         }
7459       }
7460     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7461       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7462       // It should be transformed during dag combiner except when the condition
7463       // is set by a arithmetics with overflow node.
7464       X86::CondCode CCode =
7465         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7466       CCode = X86::GetOppositeBranchCondition(CCode);
7467       CC = DAG.getConstant(CCode, MVT::i8);
7468       Cond = Cond.getOperand(0).getOperand(1);
7469       addTest = false;
7470     }
7471   }
7472
7473   if (addTest) {
7474     // Look pass the truncate.
7475     if (Cond.getOpcode() == ISD::TRUNCATE)
7476       Cond = Cond.getOperand(0);
7477
7478     // We know the result of AND is compared against zero. Try to match
7479     // it to BT.
7480     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7481       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7482       if (NewSetCC.getNode()) {
7483         CC = NewSetCC.getOperand(0);
7484         Cond = NewSetCC.getOperand(1);
7485         addTest = false;
7486       }
7487     }
7488   }
7489
7490   if (addTest) {
7491     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7492     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7493   }
7494   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7495                      Chain, Dest, CC, Cond);
7496 }
7497
7498
7499 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7500 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7501 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7502 // that the guard pages used by the OS virtual memory manager are allocated in
7503 // correct sequence.
7504 SDValue
7505 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7506                                            SelectionDAG &DAG) const {
7507   assert(Subtarget->isTargetCygMing() &&
7508          "This should be used only on Cygwin/Mingw targets");
7509   DebugLoc dl = Op.getDebugLoc();
7510
7511   // Get the inputs.
7512   SDValue Chain = Op.getOperand(0);
7513   SDValue Size  = Op.getOperand(1);
7514   // FIXME: Ensure alignment here
7515
7516   SDValue Flag;
7517
7518   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7519
7520   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7521   Flag = Chain.getValue(1);
7522
7523   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7524
7525   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7526   Flag = Chain.getValue(1);
7527
7528   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7529
7530   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7531   return DAG.getMergeValues(Ops1, 2, dl);
7532 }
7533
7534 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7535   MachineFunction &MF = DAG.getMachineFunction();
7536   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7537
7538   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7539   DebugLoc dl = Op.getDebugLoc();
7540
7541   if (!Subtarget->is64Bit()) {
7542     // vastart just stores the address of the VarArgsFrameIndex slot into the
7543     // memory location argument.
7544     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7545                                    getPointerTy());
7546     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
7547                         false, false, 0);
7548   }
7549
7550   // __va_list_tag:
7551   //   gp_offset         (0 - 6 * 8)
7552   //   fp_offset         (48 - 48 + 8 * 16)
7553   //   overflow_arg_area (point to parameters coming in memory).
7554   //   reg_save_area
7555   SmallVector<SDValue, 8> MemOps;
7556   SDValue FIN = Op.getOperand(1);
7557   // Store gp_offset
7558   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
7559                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7560                                                MVT::i32),
7561                                FIN, SV, 0, false, false, 0);
7562   MemOps.push_back(Store);
7563
7564   // Store fp_offset
7565   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7566                     FIN, DAG.getIntPtrConstant(4));
7567   Store = DAG.getStore(Op.getOperand(0), dl,
7568                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7569                                        MVT::i32),
7570                        FIN, SV, 4, false, false, 0);
7571   MemOps.push_back(Store);
7572
7573   // Store ptr to overflow_arg_area
7574   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7575                     FIN, DAG.getIntPtrConstant(4));
7576   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7577                                     getPointerTy());
7578   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 8,
7579                        false, false, 0);
7580   MemOps.push_back(Store);
7581
7582   // Store ptr to reg_save_area.
7583   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7584                     FIN, DAG.getIntPtrConstant(8));
7585   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7586                                     getPointerTy());
7587   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 16,
7588                        false, false, 0);
7589   MemOps.push_back(Store);
7590   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7591                      &MemOps[0], MemOps.size());
7592 }
7593
7594 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7595   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7596   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7597
7598   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7599   return SDValue();
7600 }
7601
7602 SDValue X86TargetLowering::LowerVACOPY(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_copy!");
7605   SDValue Chain = Op.getOperand(0);
7606   SDValue DstPtr = Op.getOperand(1);
7607   SDValue SrcPtr = Op.getOperand(2);
7608   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7609   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7610   DebugLoc dl = Op.getDebugLoc();
7611
7612   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
7613                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7614                        false, DstSV, 0, SrcSV, 0);
7615 }
7616
7617 SDValue
7618 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7619   DebugLoc dl = Op.getDebugLoc();
7620   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7621   switch (IntNo) {
7622   default: return SDValue();    // Don't custom lower most intrinsics.
7623   // Comparison intrinsics.
7624   case Intrinsic::x86_sse_comieq_ss:
7625   case Intrinsic::x86_sse_comilt_ss:
7626   case Intrinsic::x86_sse_comile_ss:
7627   case Intrinsic::x86_sse_comigt_ss:
7628   case Intrinsic::x86_sse_comige_ss:
7629   case Intrinsic::x86_sse_comineq_ss:
7630   case Intrinsic::x86_sse_ucomieq_ss:
7631   case Intrinsic::x86_sse_ucomilt_ss:
7632   case Intrinsic::x86_sse_ucomile_ss:
7633   case Intrinsic::x86_sse_ucomigt_ss:
7634   case Intrinsic::x86_sse_ucomige_ss:
7635   case Intrinsic::x86_sse_ucomineq_ss:
7636   case Intrinsic::x86_sse2_comieq_sd:
7637   case Intrinsic::x86_sse2_comilt_sd:
7638   case Intrinsic::x86_sse2_comile_sd:
7639   case Intrinsic::x86_sse2_comigt_sd:
7640   case Intrinsic::x86_sse2_comige_sd:
7641   case Intrinsic::x86_sse2_comineq_sd:
7642   case Intrinsic::x86_sse2_ucomieq_sd:
7643   case Intrinsic::x86_sse2_ucomilt_sd:
7644   case Intrinsic::x86_sse2_ucomile_sd:
7645   case Intrinsic::x86_sse2_ucomigt_sd:
7646   case Intrinsic::x86_sse2_ucomige_sd:
7647   case Intrinsic::x86_sse2_ucomineq_sd: {
7648     unsigned Opc = 0;
7649     ISD::CondCode CC = ISD::SETCC_INVALID;
7650     switch (IntNo) {
7651     default: break;
7652     case Intrinsic::x86_sse_comieq_ss:
7653     case Intrinsic::x86_sse2_comieq_sd:
7654       Opc = X86ISD::COMI;
7655       CC = ISD::SETEQ;
7656       break;
7657     case Intrinsic::x86_sse_comilt_ss:
7658     case Intrinsic::x86_sse2_comilt_sd:
7659       Opc = X86ISD::COMI;
7660       CC = ISD::SETLT;
7661       break;
7662     case Intrinsic::x86_sse_comile_ss:
7663     case Intrinsic::x86_sse2_comile_sd:
7664       Opc = X86ISD::COMI;
7665       CC = ISD::SETLE;
7666       break;
7667     case Intrinsic::x86_sse_comigt_ss:
7668     case Intrinsic::x86_sse2_comigt_sd:
7669       Opc = X86ISD::COMI;
7670       CC = ISD::SETGT;
7671       break;
7672     case Intrinsic::x86_sse_comige_ss:
7673     case Intrinsic::x86_sse2_comige_sd:
7674       Opc = X86ISD::COMI;
7675       CC = ISD::SETGE;
7676       break;
7677     case Intrinsic::x86_sse_comineq_ss:
7678     case Intrinsic::x86_sse2_comineq_sd:
7679       Opc = X86ISD::COMI;
7680       CC = ISD::SETNE;
7681       break;
7682     case Intrinsic::x86_sse_ucomieq_ss:
7683     case Intrinsic::x86_sse2_ucomieq_sd:
7684       Opc = X86ISD::UCOMI;
7685       CC = ISD::SETEQ;
7686       break;
7687     case Intrinsic::x86_sse_ucomilt_ss:
7688     case Intrinsic::x86_sse2_ucomilt_sd:
7689       Opc = X86ISD::UCOMI;
7690       CC = ISD::SETLT;
7691       break;
7692     case Intrinsic::x86_sse_ucomile_ss:
7693     case Intrinsic::x86_sse2_ucomile_sd:
7694       Opc = X86ISD::UCOMI;
7695       CC = ISD::SETLE;
7696       break;
7697     case Intrinsic::x86_sse_ucomigt_ss:
7698     case Intrinsic::x86_sse2_ucomigt_sd:
7699       Opc = X86ISD::UCOMI;
7700       CC = ISD::SETGT;
7701       break;
7702     case Intrinsic::x86_sse_ucomige_ss:
7703     case Intrinsic::x86_sse2_ucomige_sd:
7704       Opc = X86ISD::UCOMI;
7705       CC = ISD::SETGE;
7706       break;
7707     case Intrinsic::x86_sse_ucomineq_ss:
7708     case Intrinsic::x86_sse2_ucomineq_sd:
7709       Opc = X86ISD::UCOMI;
7710       CC = ISD::SETNE;
7711       break;
7712     }
7713
7714     SDValue LHS = Op.getOperand(1);
7715     SDValue RHS = Op.getOperand(2);
7716     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7717     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7718     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7719     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7720                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7721     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7722   }
7723   // ptest and testp intrinsics. The intrinsic these come from are designed to
7724   // return an integer value, not just an instruction so lower it to the ptest
7725   // or testp pattern and a setcc for the result.
7726   case Intrinsic::x86_sse41_ptestz:
7727   case Intrinsic::x86_sse41_ptestc:
7728   case Intrinsic::x86_sse41_ptestnzc:
7729   case Intrinsic::x86_avx_ptestz_256:
7730   case Intrinsic::x86_avx_ptestc_256:
7731   case Intrinsic::x86_avx_ptestnzc_256:
7732   case Intrinsic::x86_avx_vtestz_ps:
7733   case Intrinsic::x86_avx_vtestc_ps:
7734   case Intrinsic::x86_avx_vtestnzc_ps:
7735   case Intrinsic::x86_avx_vtestz_pd:
7736   case Intrinsic::x86_avx_vtestc_pd:
7737   case Intrinsic::x86_avx_vtestnzc_pd:
7738   case Intrinsic::x86_avx_vtestz_ps_256:
7739   case Intrinsic::x86_avx_vtestc_ps_256:
7740   case Intrinsic::x86_avx_vtestnzc_ps_256:
7741   case Intrinsic::x86_avx_vtestz_pd_256:
7742   case Intrinsic::x86_avx_vtestc_pd_256:
7743   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7744     bool IsTestPacked = false;
7745     unsigned X86CC = 0;
7746     switch (IntNo) {
7747     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7748     case Intrinsic::x86_avx_vtestz_ps:
7749     case Intrinsic::x86_avx_vtestz_pd:
7750     case Intrinsic::x86_avx_vtestz_ps_256:
7751     case Intrinsic::x86_avx_vtestz_pd_256:
7752       IsTestPacked = true; // Fallthrough
7753     case Intrinsic::x86_sse41_ptestz:
7754     case Intrinsic::x86_avx_ptestz_256:
7755       // ZF = 1
7756       X86CC = X86::COND_E;
7757       break;
7758     case Intrinsic::x86_avx_vtestc_ps:
7759     case Intrinsic::x86_avx_vtestc_pd:
7760     case Intrinsic::x86_avx_vtestc_ps_256:
7761     case Intrinsic::x86_avx_vtestc_pd_256:
7762       IsTestPacked = true; // Fallthrough
7763     case Intrinsic::x86_sse41_ptestc:
7764     case Intrinsic::x86_avx_ptestc_256:
7765       // CF = 1
7766       X86CC = X86::COND_B;
7767       break;
7768     case Intrinsic::x86_avx_vtestnzc_ps:
7769     case Intrinsic::x86_avx_vtestnzc_pd:
7770     case Intrinsic::x86_avx_vtestnzc_ps_256:
7771     case Intrinsic::x86_avx_vtestnzc_pd_256:
7772       IsTestPacked = true; // Fallthrough
7773     case Intrinsic::x86_sse41_ptestnzc:
7774     case Intrinsic::x86_avx_ptestnzc_256:
7775       // ZF and CF = 0
7776       X86CC = X86::COND_A;
7777       break;
7778     }
7779
7780     SDValue LHS = Op.getOperand(1);
7781     SDValue RHS = Op.getOperand(2);
7782     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7783     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7784     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7785     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7786     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7787   }
7788
7789   // Fix vector shift instructions where the last operand is a non-immediate
7790   // i32 value.
7791   case Intrinsic::x86_sse2_pslli_w:
7792   case Intrinsic::x86_sse2_pslli_d:
7793   case Intrinsic::x86_sse2_pslli_q:
7794   case Intrinsic::x86_sse2_psrli_w:
7795   case Intrinsic::x86_sse2_psrli_d:
7796   case Intrinsic::x86_sse2_psrli_q:
7797   case Intrinsic::x86_sse2_psrai_w:
7798   case Intrinsic::x86_sse2_psrai_d:
7799   case Intrinsic::x86_mmx_pslli_w:
7800   case Intrinsic::x86_mmx_pslli_d:
7801   case Intrinsic::x86_mmx_pslli_q:
7802   case Intrinsic::x86_mmx_psrli_w:
7803   case Intrinsic::x86_mmx_psrli_d:
7804   case Intrinsic::x86_mmx_psrli_q:
7805   case Intrinsic::x86_mmx_psrai_w:
7806   case Intrinsic::x86_mmx_psrai_d: {
7807     SDValue ShAmt = Op.getOperand(2);
7808     if (isa<ConstantSDNode>(ShAmt))
7809       return SDValue();
7810
7811     unsigned NewIntNo = 0;
7812     EVT ShAmtVT = MVT::v4i32;
7813     switch (IntNo) {
7814     case Intrinsic::x86_sse2_pslli_w:
7815       NewIntNo = Intrinsic::x86_sse2_psll_w;
7816       break;
7817     case Intrinsic::x86_sse2_pslli_d:
7818       NewIntNo = Intrinsic::x86_sse2_psll_d;
7819       break;
7820     case Intrinsic::x86_sse2_pslli_q:
7821       NewIntNo = Intrinsic::x86_sse2_psll_q;
7822       break;
7823     case Intrinsic::x86_sse2_psrli_w:
7824       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7825       break;
7826     case Intrinsic::x86_sse2_psrli_d:
7827       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7828       break;
7829     case Intrinsic::x86_sse2_psrli_q:
7830       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7831       break;
7832     case Intrinsic::x86_sse2_psrai_w:
7833       NewIntNo = Intrinsic::x86_sse2_psra_w;
7834       break;
7835     case Intrinsic::x86_sse2_psrai_d:
7836       NewIntNo = Intrinsic::x86_sse2_psra_d;
7837       break;
7838     default: {
7839       ShAmtVT = MVT::v2i32;
7840       switch (IntNo) {
7841       case Intrinsic::x86_mmx_pslli_w:
7842         NewIntNo = Intrinsic::x86_mmx_psll_w;
7843         break;
7844       case Intrinsic::x86_mmx_pslli_d:
7845         NewIntNo = Intrinsic::x86_mmx_psll_d;
7846         break;
7847       case Intrinsic::x86_mmx_pslli_q:
7848         NewIntNo = Intrinsic::x86_mmx_psll_q;
7849         break;
7850       case Intrinsic::x86_mmx_psrli_w:
7851         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7852         break;
7853       case Intrinsic::x86_mmx_psrli_d:
7854         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7855         break;
7856       case Intrinsic::x86_mmx_psrli_q:
7857         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7858         break;
7859       case Intrinsic::x86_mmx_psrai_w:
7860         NewIntNo = Intrinsic::x86_mmx_psra_w;
7861         break;
7862       case Intrinsic::x86_mmx_psrai_d:
7863         NewIntNo = Intrinsic::x86_mmx_psra_d;
7864         break;
7865       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7866       }
7867       break;
7868     }
7869     }
7870
7871     // The vector shift intrinsics with scalars uses 32b shift amounts but
7872     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7873     // to be zero.
7874     SDValue ShOps[4];
7875     ShOps[0] = ShAmt;
7876     ShOps[1] = DAG.getConstant(0, MVT::i32);
7877     if (ShAmtVT == MVT::v4i32) {
7878       ShOps[2] = DAG.getUNDEF(MVT::i32);
7879       ShOps[3] = DAG.getUNDEF(MVT::i32);
7880       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7881     } else {
7882       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7883     }
7884
7885     EVT VT = Op.getValueType();
7886     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7887     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7888                        DAG.getConstant(NewIntNo, MVT::i32),
7889                        Op.getOperand(1), ShAmt);
7890   }
7891   }
7892 }
7893
7894 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7895                                            SelectionDAG &DAG) const {
7896   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7897   MFI->setReturnAddressIsTaken(true);
7898
7899   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7900   DebugLoc dl = Op.getDebugLoc();
7901
7902   if (Depth > 0) {
7903     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7904     SDValue Offset =
7905       DAG.getConstant(TD->getPointerSize(),
7906                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7907     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7908                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7909                                    FrameAddr, Offset),
7910                        NULL, 0, false, false, 0);
7911   }
7912
7913   // Just load the return address.
7914   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7915   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7916                      RetAddrFI, NULL, 0, false, false, 0);
7917 }
7918
7919 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7920   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7921   MFI->setFrameAddressIsTaken(true);
7922
7923   EVT VT = Op.getValueType();
7924   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7925   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7926   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7927   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7928   while (Depth--)
7929     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7930                             false, false, 0);
7931   return FrameAddr;
7932 }
7933
7934 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7935                                                      SelectionDAG &DAG) const {
7936   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7937 }
7938
7939 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7940   MachineFunction &MF = DAG.getMachineFunction();
7941   SDValue Chain     = Op.getOperand(0);
7942   SDValue Offset    = Op.getOperand(1);
7943   SDValue Handler   = Op.getOperand(2);
7944   DebugLoc dl       = Op.getDebugLoc();
7945
7946   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7947                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7948                                      getPointerTy());
7949   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7950
7951   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7952                                   DAG.getIntPtrConstant(TD->getPointerSize()));
7953   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7954   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7955   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7956   MF.getRegInfo().addLiveOut(StoreAddrReg);
7957
7958   return DAG.getNode(X86ISD::EH_RETURN, dl,
7959                      MVT::Other,
7960                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7961 }
7962
7963 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7964                                              SelectionDAG &DAG) const {
7965   SDValue Root = Op.getOperand(0);
7966   SDValue Trmp = Op.getOperand(1); // trampoline
7967   SDValue FPtr = Op.getOperand(2); // nested function
7968   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7969   DebugLoc dl  = Op.getDebugLoc();
7970
7971   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7972
7973   if (Subtarget->is64Bit()) {
7974     SDValue OutChains[6];
7975
7976     // Large code-model.
7977     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7978     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7979
7980     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7981     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7982
7983     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7984
7985     // Load the pointer to the nested function into R11.
7986     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7987     SDValue Addr = Trmp;
7988     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7989                                 Addr, TrmpAddr, 0, false, false, 0);
7990
7991     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7992                        DAG.getConstant(2, MVT::i64));
7993     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7994                                 false, false, 2);
7995
7996     // Load the 'nest' parameter value into R10.
7997     // R10 is specified in X86CallingConv.td
7998     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7999     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8000                        DAG.getConstant(10, MVT::i64));
8001     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8002                                 Addr, TrmpAddr, 10, false, false, 0);
8003
8004     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8005                        DAG.getConstant(12, MVT::i64));
8006     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
8007                                 false, false, 2);
8008
8009     // Jump to the nested function.
8010     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8011     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8012                        DAG.getConstant(20, MVT::i64));
8013     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8014                                 Addr, TrmpAddr, 20, false, false, 0);
8015
8016     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8017     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8018                        DAG.getConstant(22, MVT::i64));
8019     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8020                                 TrmpAddr, 22, false, false, 0);
8021
8022     SDValue Ops[] =
8023       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8024     return DAG.getMergeValues(Ops, 2, dl);
8025   } else {
8026     const Function *Func =
8027       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8028     CallingConv::ID CC = Func->getCallingConv();
8029     unsigned NestReg;
8030
8031     switch (CC) {
8032     default:
8033       llvm_unreachable("Unsupported calling convention");
8034     case CallingConv::C:
8035     case CallingConv::X86_StdCall: {
8036       // Pass 'nest' parameter in ECX.
8037       // Must be kept in sync with X86CallingConv.td
8038       NestReg = X86::ECX;
8039
8040       // Check that ECX wasn't needed by an 'inreg' parameter.
8041       const FunctionType *FTy = Func->getFunctionType();
8042       const AttrListPtr &Attrs = Func->getAttributes();
8043
8044       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8045         unsigned InRegCount = 0;
8046         unsigned Idx = 1;
8047
8048         for (FunctionType::param_iterator I = FTy->param_begin(),
8049              E = FTy->param_end(); I != E; ++I, ++Idx)
8050           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8051             // FIXME: should only count parameters that are lowered to integers.
8052             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8053
8054         if (InRegCount > 2) {
8055           report_fatal_error("Nest register in use - reduce number of inreg"
8056                              " parameters!");
8057         }
8058       }
8059       break;
8060     }
8061     case CallingConv::X86_FastCall:
8062     case CallingConv::X86_ThisCall:
8063     case CallingConv::Fast:
8064       // Pass 'nest' parameter in EAX.
8065       // Must be kept in sync with X86CallingConv.td
8066       NestReg = X86::EAX;
8067       break;
8068     }
8069
8070     SDValue OutChains[4];
8071     SDValue Addr, Disp;
8072
8073     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8074                        DAG.getConstant(10, MVT::i32));
8075     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8076
8077     // This is storing the opcode for MOV32ri.
8078     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8079     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8080     OutChains[0] = DAG.getStore(Root, dl,
8081                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8082                                 Trmp, TrmpAddr, 0, false, false, 0);
8083
8084     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8085                        DAG.getConstant(1, MVT::i32));
8086     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
8087                                 false, false, 1);
8088
8089     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8090     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8091                        DAG.getConstant(5, MVT::i32));
8092     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8093                                 TrmpAddr, 5, false, false, 1);
8094
8095     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8096                        DAG.getConstant(6, MVT::i32));
8097     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
8098                                 false, false, 1);
8099
8100     SDValue Ops[] =
8101       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8102     return DAG.getMergeValues(Ops, 2, dl);
8103   }
8104 }
8105
8106 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8107                                             SelectionDAG &DAG) const {
8108   /*
8109    The rounding mode is in bits 11:10 of FPSR, and has the following
8110    settings:
8111      00 Round to nearest
8112      01 Round to -inf
8113      10 Round to +inf
8114      11 Round to 0
8115
8116   FLT_ROUNDS, on the other hand, expects the following:
8117     -1 Undefined
8118      0 Round to 0
8119      1 Round to nearest
8120      2 Round to +inf
8121      3 Round to -inf
8122
8123   To perform the conversion, we do:
8124     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8125   */
8126
8127   MachineFunction &MF = DAG.getMachineFunction();
8128   const TargetMachine &TM = MF.getTarget();
8129   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8130   unsigned StackAlignment = TFI.getStackAlignment();
8131   EVT VT = Op.getValueType();
8132   DebugLoc dl = Op.getDebugLoc();
8133
8134   // Save FP Control Word to stack slot
8135   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8136   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8137
8138   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
8139                               DAG.getEntryNode(), StackSlot);
8140
8141   // Load FP Control Word from stack slot
8142   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
8143                             false, false, 0);
8144
8145   // Transform as necessary
8146   SDValue CWD1 =
8147     DAG.getNode(ISD::SRL, dl, MVT::i16,
8148                 DAG.getNode(ISD::AND, dl, MVT::i16,
8149                             CWD, DAG.getConstant(0x800, MVT::i16)),
8150                 DAG.getConstant(11, MVT::i8));
8151   SDValue CWD2 =
8152     DAG.getNode(ISD::SRL, dl, MVT::i16,
8153                 DAG.getNode(ISD::AND, dl, MVT::i16,
8154                             CWD, DAG.getConstant(0x400, MVT::i16)),
8155                 DAG.getConstant(9, MVT::i8));
8156
8157   SDValue RetVal =
8158     DAG.getNode(ISD::AND, dl, MVT::i16,
8159                 DAG.getNode(ISD::ADD, dl, MVT::i16,
8160                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
8161                             DAG.getConstant(1, MVT::i16)),
8162                 DAG.getConstant(3, MVT::i16));
8163
8164
8165   return DAG.getNode((VT.getSizeInBits() < 16 ?
8166                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8167 }
8168
8169 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8170   EVT VT = Op.getValueType();
8171   EVT OpVT = VT;
8172   unsigned NumBits = VT.getSizeInBits();
8173   DebugLoc dl = Op.getDebugLoc();
8174
8175   Op = Op.getOperand(0);
8176   if (VT == MVT::i8) {
8177     // Zero extend to i32 since there is not an i8 bsr.
8178     OpVT = MVT::i32;
8179     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8180   }
8181
8182   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8183   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8184   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8185
8186   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8187   SDValue Ops[] = {
8188     Op,
8189     DAG.getConstant(NumBits+NumBits-1, OpVT),
8190     DAG.getConstant(X86::COND_E, MVT::i8),
8191     Op.getValue(1)
8192   };
8193   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8194
8195   // Finally xor with NumBits-1.
8196   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8197
8198   if (VT == MVT::i8)
8199     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8200   return Op;
8201 }
8202
8203 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8204   EVT VT = Op.getValueType();
8205   EVT OpVT = VT;
8206   unsigned NumBits = VT.getSizeInBits();
8207   DebugLoc dl = Op.getDebugLoc();
8208
8209   Op = Op.getOperand(0);
8210   if (VT == MVT::i8) {
8211     OpVT = MVT::i32;
8212     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8213   }
8214
8215   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8216   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8217   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8218
8219   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8220   SDValue Ops[] = {
8221     Op,
8222     DAG.getConstant(NumBits, OpVT),
8223     DAG.getConstant(X86::COND_E, MVT::i8),
8224     Op.getValue(1)
8225   };
8226   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8227
8228   if (VT == MVT::i8)
8229     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8230   return Op;
8231 }
8232
8233 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8234   EVT VT = Op.getValueType();
8235   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8236   DebugLoc dl = Op.getDebugLoc();
8237
8238   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8239   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8240   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8241   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8242   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8243   //
8244   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8245   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8246   //  return AloBlo + AloBhi + AhiBlo;
8247
8248   SDValue A = Op.getOperand(0);
8249   SDValue B = Op.getOperand(1);
8250
8251   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8252                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8253                        A, DAG.getConstant(32, MVT::i32));
8254   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8255                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8256                        B, DAG.getConstant(32, MVT::i32));
8257   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8258                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8259                        A, B);
8260   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8261                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8262                        A, Bhi);
8263   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8264                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8265                        Ahi, B);
8266   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8267                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8268                        AloBhi, DAG.getConstant(32, MVT::i32));
8269   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8270                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8271                        AhiBlo, DAG.getConstant(32, MVT::i32));
8272   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8273   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8274   return Res;
8275 }
8276
8277 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8278   EVT VT = Op.getValueType();
8279   DebugLoc dl = Op.getDebugLoc();
8280   SDValue R = Op.getOperand(0);
8281
8282   LLVMContext *Context = DAG.getContext();
8283
8284   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8285
8286   if (VT == MVT::v4i32) {
8287     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8288                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8289                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8290
8291     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8292     
8293     std::vector<Constant*> CV(4, CI);
8294     Constant *C = ConstantVector::get(CV);
8295     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8296     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8297                                  PseudoSourceValue::getConstantPool(), 0,
8298                                  false, false, 16);
8299
8300     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8301     Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8302     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8303     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8304   }
8305   if (VT == MVT::v16i8) {
8306     // a = a << 5;
8307     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8308                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8309                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8310
8311     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8312     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8313
8314     std::vector<Constant*> CVM1(16, CM1);
8315     std::vector<Constant*> CVM2(16, CM2);
8316     Constant *C = ConstantVector::get(CVM1);
8317     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8318     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8319                             PseudoSourceValue::getConstantPool(), 0,
8320                             false, false, 16);
8321
8322     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8323     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8324     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8325                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8326                     DAG.getConstant(4, MVT::i32));
8327     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8328                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8329                     R, M, Op);
8330     // a += a
8331     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8332     
8333     C = ConstantVector::get(CVM2);
8334     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8335     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8336                     PseudoSourceValue::getConstantPool(), 0, false, false, 16);
8337     
8338     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8339     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8340     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8341                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8342                     DAG.getConstant(2, MVT::i32));
8343     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8344                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8345                     R, M, Op);
8346     // a += a
8347     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8348     
8349     // return pblendv(r, r+r, a);
8350     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8351                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8352                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8353     return R;
8354   }
8355   return SDValue();
8356 }
8357
8358 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8359   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8360   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8361   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8362   // has only one use.
8363   SDNode *N = Op.getNode();
8364   SDValue LHS = N->getOperand(0);
8365   SDValue RHS = N->getOperand(1);
8366   unsigned BaseOp = 0;
8367   unsigned Cond = 0;
8368   DebugLoc dl = Op.getDebugLoc();
8369
8370   switch (Op.getOpcode()) {
8371   default: llvm_unreachable("Unknown ovf instruction!");
8372   case ISD::SADDO:
8373     // A subtract of one will be selected as a INC. Note that INC doesn't
8374     // set CF, so we can't do this for UADDO.
8375     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8376       if (C->getAPIntValue() == 1) {
8377         BaseOp = X86ISD::INC;
8378         Cond = X86::COND_O;
8379         break;
8380       }
8381     BaseOp = X86ISD::ADD;
8382     Cond = X86::COND_O;
8383     break;
8384   case ISD::UADDO:
8385     BaseOp = X86ISD::ADD;
8386     Cond = X86::COND_B;
8387     break;
8388   case ISD::SSUBO:
8389     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8390     // set CF, so we can't do this for USUBO.
8391     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8392       if (C->getAPIntValue() == 1) {
8393         BaseOp = X86ISD::DEC;
8394         Cond = X86::COND_O;
8395         break;
8396       }
8397     BaseOp = X86ISD::SUB;
8398     Cond = X86::COND_O;
8399     break;
8400   case ISD::USUBO:
8401     BaseOp = X86ISD::SUB;
8402     Cond = X86::COND_B;
8403     break;
8404   case ISD::SMULO:
8405     BaseOp = X86ISD::SMUL;
8406     Cond = X86::COND_O;
8407     break;
8408   case ISD::UMULO:
8409     BaseOp = X86ISD::UMUL;
8410     Cond = X86::COND_B;
8411     break;
8412   }
8413
8414   // Also sets EFLAGS.
8415   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8416   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8417
8418   SDValue SetCC =
8419     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8420                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8421
8422   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8423   return Sum;
8424 }
8425
8426 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8427   DebugLoc dl = Op.getDebugLoc();
8428   
8429   if (!Subtarget->hasSSE2()) {
8430     SDValue Chain = Op.getOperand(0);
8431     SDValue Zero = DAG.getConstant(0, 
8432                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8433     SDValue Ops[] = {
8434       DAG.getRegister(X86::ESP, MVT::i32), // Base
8435       DAG.getTargetConstant(1, MVT::i8),   // Scale
8436       DAG.getRegister(0, MVT::i32),        // Index
8437       DAG.getTargetConstant(0, MVT::i32),  // Disp
8438       DAG.getRegister(0, MVT::i32),        // Segment.
8439       Zero,
8440       Chain
8441     };
8442     SDNode *Res = 
8443       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8444                           array_lengthof(Ops));
8445     return SDValue(Res, 0);
8446   }
8447   
8448   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8449   if (!isDev)
8450     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8451   
8452   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8453   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8454   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8455   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8456   
8457   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8458   if (!Op1 && !Op2 && !Op3 && Op4)
8459     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8460   
8461   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8462   if (Op1 && !Op2 && !Op3 && !Op4)
8463     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8464   
8465   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 
8466   //           (MFENCE)>;
8467   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8468 }
8469
8470 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8471   EVT T = Op.getValueType();
8472   DebugLoc dl = Op.getDebugLoc();
8473   unsigned Reg = 0;
8474   unsigned size = 0;
8475   switch(T.getSimpleVT().SimpleTy) {
8476   default:
8477     assert(false && "Invalid value type!");
8478   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8479   case MVT::i16: Reg = X86::AX;  size = 2; break;
8480   case MVT::i32: Reg = X86::EAX; size = 4; break;
8481   case MVT::i64:
8482     assert(Subtarget->is64Bit() && "Node not type legal!");
8483     Reg = X86::RAX; size = 8;
8484     break;
8485   }
8486   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
8487                                     Op.getOperand(2), SDValue());
8488   SDValue Ops[] = { cpIn.getValue(0),
8489                     Op.getOperand(1),
8490                     Op.getOperand(3),
8491                     DAG.getTargetConstant(size, MVT::i8),
8492                     cpIn.getValue(1) };
8493   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8494   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
8495   SDValue cpOut =
8496     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
8497   return cpOut;
8498 }
8499
8500 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8501                                                  SelectionDAG &DAG) const {
8502   assert(Subtarget->is64Bit() && "Result not type legalized?");
8503   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8504   SDValue TheChain = Op.getOperand(0);
8505   DebugLoc dl = Op.getDebugLoc();
8506   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8507   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8508   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8509                                    rax.getValue(2));
8510   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8511                             DAG.getConstant(32, MVT::i8));
8512   SDValue Ops[] = {
8513     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8514     rdx.getValue(1)
8515   };
8516   return DAG.getMergeValues(Ops, 2, dl);
8517 }
8518
8519 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8520                                             SelectionDAG &DAG) const {
8521   EVT SrcVT = Op.getOperand(0).getValueType();
8522   EVT DstVT = Op.getValueType();
8523   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
8524           Subtarget->hasMMX() && !DisableMMX) &&
8525          "Unexpected custom BIT_CONVERT");
8526   assert((DstVT == MVT::i64 || 
8527           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8528          "Unexpected custom BIT_CONVERT");
8529   // i64 <=> MMX conversions are Legal.
8530   if (SrcVT==MVT::i64 && DstVT.isVector())
8531     return Op;
8532   if (DstVT==MVT::i64 && SrcVT.isVector())
8533     return Op;
8534   // MMX <=> MMX conversions are Legal.
8535   if (SrcVT.isVector() && DstVT.isVector())
8536     return Op;
8537   // All other conversions need to be expanded.
8538   return SDValue();
8539 }
8540 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8541   SDNode *Node = Op.getNode();
8542   DebugLoc dl = Node->getDebugLoc();
8543   EVT T = Node->getValueType(0);
8544   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8545                               DAG.getConstant(0, T), Node->getOperand(2));
8546   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8547                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8548                        Node->getOperand(0),
8549                        Node->getOperand(1), negOp,
8550                        cast<AtomicSDNode>(Node)->getSrcValue(),
8551                        cast<AtomicSDNode>(Node)->getAlignment());
8552 }
8553
8554 /// LowerOperation - Provide custom lowering hooks for some operations.
8555 ///
8556 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8557   switch (Op.getOpcode()) {
8558   default: llvm_unreachable("Should not custom lower this!");
8559   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8560   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8561   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8562   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8563   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8564   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8565   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8566   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8567   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8568   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8569   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8570   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8571   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8572   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8573   case ISD::SHL_PARTS:
8574   case ISD::SRA_PARTS:
8575   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8576   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8577   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8578   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8579   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8580   case ISD::FABS:               return LowerFABS(Op, DAG);
8581   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8582   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8583   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8584   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8585   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8586   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8587   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8588   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8589   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8590   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8591   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8592   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8593   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8594   case ISD::FRAME_TO_ARGS_OFFSET:
8595                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8596   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8597   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8598   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8599   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8600   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8601   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8602   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8603   case ISD::SHL:                return LowerSHL(Op, DAG);
8604   case ISD::SADDO:
8605   case ISD::UADDO:
8606   case ISD::SSUBO:
8607   case ISD::USUBO:
8608   case ISD::SMULO:
8609   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8610   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8611   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
8612   }
8613 }
8614
8615 void X86TargetLowering::
8616 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8617                         SelectionDAG &DAG, unsigned NewOp) const {
8618   EVT T = Node->getValueType(0);
8619   DebugLoc dl = Node->getDebugLoc();
8620   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8621
8622   SDValue Chain = Node->getOperand(0);
8623   SDValue In1 = Node->getOperand(1);
8624   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8625                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8626   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8627                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8628   SDValue Ops[] = { Chain, In1, In2L, In2H };
8629   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8630   SDValue Result =
8631     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8632                             cast<MemSDNode>(Node)->getMemOperand());
8633   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8634   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8635   Results.push_back(Result.getValue(2));
8636 }
8637
8638 /// ReplaceNodeResults - Replace a node with an illegal result type
8639 /// with a new node built out of custom code.
8640 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8641                                            SmallVectorImpl<SDValue>&Results,
8642                                            SelectionDAG &DAG) const {
8643   DebugLoc dl = N->getDebugLoc();
8644   switch (N->getOpcode()) {
8645   default:
8646     assert(false && "Do not know how to custom type legalize this operation!");
8647     return;
8648   case ISD::FP_TO_SINT: {
8649     std::pair<SDValue,SDValue> Vals =
8650         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8651     SDValue FIST = Vals.first, StackSlot = Vals.second;
8652     if (FIST.getNode() != 0) {
8653       EVT VT = N->getValueType(0);
8654       // Return a load from the stack slot.
8655       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
8656                                     false, false, 0));
8657     }
8658     return;
8659   }
8660   case ISD::READCYCLECOUNTER: {
8661     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8662     SDValue TheChain = N->getOperand(0);
8663     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8664     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8665                                      rd.getValue(1));
8666     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8667                                      eax.getValue(2));
8668     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8669     SDValue Ops[] = { eax, edx };
8670     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8671     Results.push_back(edx.getValue(1));
8672     return;
8673   }
8674   case ISD::ATOMIC_CMP_SWAP: {
8675     EVT T = N->getValueType(0);
8676     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8677     SDValue cpInL, cpInH;
8678     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8679                         DAG.getConstant(0, MVT::i32));
8680     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8681                         DAG.getConstant(1, MVT::i32));
8682     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8683     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8684                              cpInL.getValue(1));
8685     SDValue swapInL, swapInH;
8686     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8687                           DAG.getConstant(0, MVT::i32));
8688     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8689                           DAG.getConstant(1, MVT::i32));
8690     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8691                                cpInH.getValue(1));
8692     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8693                                swapInL.getValue(1));
8694     SDValue Ops[] = { swapInH.getValue(0),
8695                       N->getOperand(1),
8696                       swapInH.getValue(1) };
8697     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8698     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8699     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8700                                         MVT::i32, Result.getValue(1));
8701     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8702                                         MVT::i32, cpOutL.getValue(2));
8703     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8704     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8705     Results.push_back(cpOutH.getValue(1));
8706     return;
8707   }
8708   case ISD::ATOMIC_LOAD_ADD:
8709     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8710     return;
8711   case ISD::ATOMIC_LOAD_AND:
8712     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8713     return;
8714   case ISD::ATOMIC_LOAD_NAND:
8715     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8716     return;
8717   case ISD::ATOMIC_LOAD_OR:
8718     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8719     return;
8720   case ISD::ATOMIC_LOAD_SUB:
8721     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8722     return;
8723   case ISD::ATOMIC_LOAD_XOR:
8724     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8725     return;
8726   case ISD::ATOMIC_SWAP:
8727     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8728     return;
8729   }
8730 }
8731
8732 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8733   switch (Opcode) {
8734   default: return NULL;
8735   case X86ISD::BSF:                return "X86ISD::BSF";
8736   case X86ISD::BSR:                return "X86ISD::BSR";
8737   case X86ISD::SHLD:               return "X86ISD::SHLD";
8738   case X86ISD::SHRD:               return "X86ISD::SHRD";
8739   case X86ISD::FAND:               return "X86ISD::FAND";
8740   case X86ISD::FOR:                return "X86ISD::FOR";
8741   case X86ISD::FXOR:               return "X86ISD::FXOR";
8742   case X86ISD::FSRL:               return "X86ISD::FSRL";
8743   case X86ISD::FILD:               return "X86ISD::FILD";
8744   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8745   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8746   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8747   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8748   case X86ISD::FLD:                return "X86ISD::FLD";
8749   case X86ISD::FST:                return "X86ISD::FST";
8750   case X86ISD::CALL:               return "X86ISD::CALL";
8751   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8752   case X86ISD::BT:                 return "X86ISD::BT";
8753   case X86ISD::CMP:                return "X86ISD::CMP";
8754   case X86ISD::COMI:               return "X86ISD::COMI";
8755   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8756   case X86ISD::SETCC:              return "X86ISD::SETCC";
8757   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8758   case X86ISD::CMOV:               return "X86ISD::CMOV";
8759   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8760   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8761   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8762   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8763   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8764   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8765   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8766   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8767   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8768   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8769   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8770   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8771   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
8772   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8773   case X86ISD::FMAX:               return "X86ISD::FMAX";
8774   case X86ISD::FMIN:               return "X86ISD::FMIN";
8775   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8776   case X86ISD::FRCP:               return "X86ISD::FRCP";
8777   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8778   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8779   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
8780   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8781   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8782   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8783   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8784   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8785   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8786   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8787   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8788   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8789   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8790   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8791   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8792   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8793   case X86ISD::VSHL:               return "X86ISD::VSHL";
8794   case X86ISD::VSRL:               return "X86ISD::VSRL";
8795   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8796   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8797   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8798   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8799   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8800   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8801   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8802   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8803   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8804   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8805   case X86ISD::ADD:                return "X86ISD::ADD";
8806   case X86ISD::SUB:                return "X86ISD::SUB";
8807   case X86ISD::SMUL:               return "X86ISD::SMUL";
8808   case X86ISD::UMUL:               return "X86ISD::UMUL";
8809   case X86ISD::INC:                return "X86ISD::INC";
8810   case X86ISD::DEC:                return "X86ISD::DEC";
8811   case X86ISD::OR:                 return "X86ISD::OR";
8812   case X86ISD::XOR:                return "X86ISD::XOR";
8813   case X86ISD::AND:                return "X86ISD::AND";
8814   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8815   case X86ISD::PTEST:              return "X86ISD::PTEST";
8816   case X86ISD::TESTP:              return "X86ISD::TESTP";
8817   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8818   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8819   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8820   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8821   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8822   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8823   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8824   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8825   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8826   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8827   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8828   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8829   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8830   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8831   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8832   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8833   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8834   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8835   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8836   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8837   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8838   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8839   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8840   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8841   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8842   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8843   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8844   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8845   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8846   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8847   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8848   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8849   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8850   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8851   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
8852   }
8853 }
8854
8855 // isLegalAddressingMode - Return true if the addressing mode represented
8856 // by AM is legal for this target, for a load/store of the specified type.
8857 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8858                                               const Type *Ty) const {
8859   // X86 supports extremely general addressing modes.
8860   CodeModel::Model M = getTargetMachine().getCodeModel();
8861   Reloc::Model R = getTargetMachine().getRelocationModel();
8862
8863   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8864   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8865     return false;
8866
8867   if (AM.BaseGV) {
8868     unsigned GVFlags =
8869       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8870
8871     // If a reference to this global requires an extra load, we can't fold it.
8872     if (isGlobalStubReference(GVFlags))
8873       return false;
8874
8875     // If BaseGV requires a register for the PIC base, we cannot also have a
8876     // BaseReg specified.
8877     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8878       return false;
8879
8880     // If lower 4G is not available, then we must use rip-relative addressing.
8881     if ((M != CodeModel::Small || R != Reloc::Static) &&
8882         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8883       return false;
8884   }
8885
8886   switch (AM.Scale) {
8887   case 0:
8888   case 1:
8889   case 2:
8890   case 4:
8891   case 8:
8892     // These scales always work.
8893     break;
8894   case 3:
8895   case 5:
8896   case 9:
8897     // These scales are formed with basereg+scalereg.  Only accept if there is
8898     // no basereg yet.
8899     if (AM.HasBaseReg)
8900       return false;
8901     break;
8902   default:  // Other stuff never works.
8903     return false;
8904   }
8905
8906   return true;
8907 }
8908
8909
8910 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8911   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8912     return false;
8913   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8914   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8915   if (NumBits1 <= NumBits2)
8916     return false;
8917   return true;
8918 }
8919
8920 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8921   if (!VT1.isInteger() || !VT2.isInteger())
8922     return false;
8923   unsigned NumBits1 = VT1.getSizeInBits();
8924   unsigned NumBits2 = VT2.getSizeInBits();
8925   if (NumBits1 <= NumBits2)
8926     return false;
8927   return true;
8928 }
8929
8930 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8931   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8932   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8933 }
8934
8935 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8936   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8937   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8938 }
8939
8940 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8941   // i16 instructions are longer (0x66 prefix) and potentially slower.
8942   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8943 }
8944
8945 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8946 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8947 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8948 /// are assumed to be legal.
8949 bool
8950 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8951                                       EVT VT) const {
8952   // Very little shuffling can be done for 64-bit vectors right now.
8953   if (VT.getSizeInBits() == 64)
8954     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8955
8956   // FIXME: pshufb, blends, shifts.
8957   return (VT.getVectorNumElements() == 2 ||
8958           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8959           isMOVLMask(M, VT) ||
8960           isSHUFPMask(M, VT) ||
8961           isPSHUFDMask(M, VT) ||
8962           isPSHUFHWMask(M, VT) ||
8963           isPSHUFLWMask(M, VT) ||
8964           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8965           isUNPCKLMask(M, VT) ||
8966           isUNPCKHMask(M, VT) ||
8967           isUNPCKL_v_undef_Mask(M, VT) ||
8968           isUNPCKH_v_undef_Mask(M, VT));
8969 }
8970
8971 bool
8972 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8973                                           EVT VT) const {
8974   unsigned NumElts = VT.getVectorNumElements();
8975   // FIXME: This collection of masks seems suspect.
8976   if (NumElts == 2)
8977     return true;
8978   if (NumElts == 4 && VT.getSizeInBits() == 128) {
8979     return (isMOVLMask(Mask, VT)  ||
8980             isCommutedMOVLMask(Mask, VT, true) ||
8981             isSHUFPMask(Mask, VT) ||
8982             isCommutedSHUFPMask(Mask, VT));
8983   }
8984   return false;
8985 }
8986
8987 //===----------------------------------------------------------------------===//
8988 //                           X86 Scheduler Hooks
8989 //===----------------------------------------------------------------------===//
8990
8991 // private utility function
8992 MachineBasicBlock *
8993 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8994                                                        MachineBasicBlock *MBB,
8995                                                        unsigned regOpc,
8996                                                        unsigned immOpc,
8997                                                        unsigned LoadOpc,
8998                                                        unsigned CXchgOpc,
8999                                                        unsigned notOpc,
9000                                                        unsigned EAXreg,
9001                                                        TargetRegisterClass *RC,
9002                                                        bool invSrc) const {
9003   // For the atomic bitwise operator, we generate
9004   //   thisMBB:
9005   //   newMBB:
9006   //     ld  t1 = [bitinstr.addr]
9007   //     op  t2 = t1, [bitinstr.val]
9008   //     mov EAX = t1
9009   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9010   //     bz  newMBB
9011   //     fallthrough -->nextMBB
9012   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9013   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9014   MachineFunction::iterator MBBIter = MBB;
9015   ++MBBIter;
9016
9017   /// First build the CFG
9018   MachineFunction *F = MBB->getParent();
9019   MachineBasicBlock *thisMBB = MBB;
9020   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9021   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9022   F->insert(MBBIter, newMBB);
9023   F->insert(MBBIter, nextMBB);
9024
9025   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9026   nextMBB->splice(nextMBB->begin(), thisMBB,
9027                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9028                   thisMBB->end());
9029   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9030
9031   // Update thisMBB to fall through to newMBB
9032   thisMBB->addSuccessor(newMBB);
9033
9034   // newMBB jumps to itself and fall through to nextMBB
9035   newMBB->addSuccessor(nextMBB);
9036   newMBB->addSuccessor(newMBB);
9037
9038   // Insert instructions into newMBB based on incoming instruction
9039   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9040          "unexpected number of operands");
9041   DebugLoc dl = bInstr->getDebugLoc();
9042   MachineOperand& destOper = bInstr->getOperand(0);
9043   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9044   int numArgs = bInstr->getNumOperands() - 1;
9045   for (int i=0; i < numArgs; ++i)
9046     argOpers[i] = &bInstr->getOperand(i+1);
9047
9048   // x86 address has 4 operands: base, index, scale, and displacement
9049   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9050   int valArgIndx = lastAddrIndx + 1;
9051
9052   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9053   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9054   for (int i=0; i <= lastAddrIndx; ++i)
9055     (*MIB).addOperand(*argOpers[i]);
9056
9057   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9058   if (invSrc) {
9059     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9060   }
9061   else
9062     tt = t1;
9063
9064   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9065   assert((argOpers[valArgIndx]->isReg() ||
9066           argOpers[valArgIndx]->isImm()) &&
9067          "invalid operand");
9068   if (argOpers[valArgIndx]->isReg())
9069     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9070   else
9071     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9072   MIB.addReg(tt);
9073   (*MIB).addOperand(*argOpers[valArgIndx]);
9074
9075   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9076   MIB.addReg(t1);
9077
9078   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9079   for (int i=0; i <= lastAddrIndx; ++i)
9080     (*MIB).addOperand(*argOpers[i]);
9081   MIB.addReg(t2);
9082   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9083   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9084                     bInstr->memoperands_end());
9085
9086   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9087   MIB.addReg(EAXreg);
9088
9089   // insert branch
9090   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9091
9092   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9093   return nextMBB;
9094 }
9095
9096 // private utility function:  64 bit atomics on 32 bit host.
9097 MachineBasicBlock *
9098 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9099                                                        MachineBasicBlock *MBB,
9100                                                        unsigned regOpcL,
9101                                                        unsigned regOpcH,
9102                                                        unsigned immOpcL,
9103                                                        unsigned immOpcH,
9104                                                        bool invSrc) const {
9105   // For the atomic bitwise operator, we generate
9106   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9107   //     ld t1,t2 = [bitinstr.addr]
9108   //   newMBB:
9109   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9110   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9111   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9112   //     mov ECX, EBX <- t5, t6
9113   //     mov EAX, EDX <- t1, t2
9114   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9115   //     mov t3, t4 <- EAX, EDX
9116   //     bz  newMBB
9117   //     result in out1, out2
9118   //     fallthrough -->nextMBB
9119
9120   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9121   const unsigned LoadOpc = X86::MOV32rm;
9122   const unsigned NotOpc = X86::NOT32r;
9123   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9124   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9125   MachineFunction::iterator MBBIter = MBB;
9126   ++MBBIter;
9127
9128   /// First build the CFG
9129   MachineFunction *F = MBB->getParent();
9130   MachineBasicBlock *thisMBB = MBB;
9131   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9132   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9133   F->insert(MBBIter, newMBB);
9134   F->insert(MBBIter, nextMBB);
9135
9136   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9137   nextMBB->splice(nextMBB->begin(), thisMBB,
9138                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9139                   thisMBB->end());
9140   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9141
9142   // Update thisMBB to fall through to newMBB
9143   thisMBB->addSuccessor(newMBB);
9144
9145   // newMBB jumps to itself and fall through to nextMBB
9146   newMBB->addSuccessor(nextMBB);
9147   newMBB->addSuccessor(newMBB);
9148
9149   DebugLoc dl = bInstr->getDebugLoc();
9150   // Insert instructions into newMBB based on incoming instruction
9151   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9152   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9153          "unexpected number of operands");
9154   MachineOperand& dest1Oper = bInstr->getOperand(0);
9155   MachineOperand& dest2Oper = bInstr->getOperand(1);
9156   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9157   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9158     argOpers[i] = &bInstr->getOperand(i+2);
9159
9160     // We use some of the operands multiple times, so conservatively just
9161     // clear any kill flags that might be present.
9162     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9163       argOpers[i]->setIsKill(false);
9164   }
9165
9166   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9167   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9168
9169   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9170   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9171   for (int i=0; i <= lastAddrIndx; ++i)
9172     (*MIB).addOperand(*argOpers[i]);
9173   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9174   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9175   // add 4 to displacement.
9176   for (int i=0; i <= lastAddrIndx-2; ++i)
9177     (*MIB).addOperand(*argOpers[i]);
9178   MachineOperand newOp3 = *(argOpers[3]);
9179   if (newOp3.isImm())
9180     newOp3.setImm(newOp3.getImm()+4);
9181   else
9182     newOp3.setOffset(newOp3.getOffset()+4);
9183   (*MIB).addOperand(newOp3);
9184   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9185
9186   // t3/4 are defined later, at the bottom of the loop
9187   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9188   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9189   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9190     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9191   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9192     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9193
9194   // The subsequent operations should be using the destination registers of
9195   //the PHI instructions.
9196   if (invSrc) {
9197     t1 = F->getRegInfo().createVirtualRegister(RC);
9198     t2 = F->getRegInfo().createVirtualRegister(RC);
9199     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9200     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9201   } else {
9202     t1 = dest1Oper.getReg();
9203     t2 = dest2Oper.getReg();
9204   }
9205
9206   int valArgIndx = lastAddrIndx + 1;
9207   assert((argOpers[valArgIndx]->isReg() ||
9208           argOpers[valArgIndx]->isImm()) &&
9209          "invalid operand");
9210   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9211   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9212   if (argOpers[valArgIndx]->isReg())
9213     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9214   else
9215     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9216   if (regOpcL != X86::MOV32rr)
9217     MIB.addReg(t1);
9218   (*MIB).addOperand(*argOpers[valArgIndx]);
9219   assert(argOpers[valArgIndx + 1]->isReg() ==
9220          argOpers[valArgIndx]->isReg());
9221   assert(argOpers[valArgIndx + 1]->isImm() ==
9222          argOpers[valArgIndx]->isImm());
9223   if (argOpers[valArgIndx + 1]->isReg())
9224     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9225   else
9226     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9227   if (regOpcH != X86::MOV32rr)
9228     MIB.addReg(t2);
9229   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9230
9231   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9232   MIB.addReg(t1);
9233   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9234   MIB.addReg(t2);
9235
9236   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9237   MIB.addReg(t5);
9238   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9239   MIB.addReg(t6);
9240
9241   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9242   for (int i=0; i <= lastAddrIndx; ++i)
9243     (*MIB).addOperand(*argOpers[i]);
9244
9245   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9246   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9247                     bInstr->memoperands_end());
9248
9249   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9250   MIB.addReg(X86::EAX);
9251   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9252   MIB.addReg(X86::EDX);
9253
9254   // insert branch
9255   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9256
9257   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9258   return nextMBB;
9259 }
9260
9261 // private utility function
9262 MachineBasicBlock *
9263 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9264                                                       MachineBasicBlock *MBB,
9265                                                       unsigned cmovOpc) const {
9266   // For the atomic min/max operator, we generate
9267   //   thisMBB:
9268   //   newMBB:
9269   //     ld t1 = [min/max.addr]
9270   //     mov t2 = [min/max.val]
9271   //     cmp  t1, t2
9272   //     cmov[cond] t2 = t1
9273   //     mov EAX = t1
9274   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9275   //     bz   newMBB
9276   //     fallthrough -->nextMBB
9277   //
9278   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9279   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9280   MachineFunction::iterator MBBIter = MBB;
9281   ++MBBIter;
9282
9283   /// First build the CFG
9284   MachineFunction *F = MBB->getParent();
9285   MachineBasicBlock *thisMBB = MBB;
9286   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9287   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9288   F->insert(MBBIter, newMBB);
9289   F->insert(MBBIter, nextMBB);
9290
9291   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9292   nextMBB->splice(nextMBB->begin(), thisMBB,
9293                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9294                   thisMBB->end());
9295   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9296
9297   // Update thisMBB to fall through to newMBB
9298   thisMBB->addSuccessor(newMBB);
9299
9300   // newMBB jumps to newMBB and fall through to nextMBB
9301   newMBB->addSuccessor(nextMBB);
9302   newMBB->addSuccessor(newMBB);
9303
9304   DebugLoc dl = mInstr->getDebugLoc();
9305   // Insert instructions into newMBB based on incoming instruction
9306   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9307          "unexpected number of operands");
9308   MachineOperand& destOper = mInstr->getOperand(0);
9309   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9310   int numArgs = mInstr->getNumOperands() - 1;
9311   for (int i=0; i < numArgs; ++i)
9312     argOpers[i] = &mInstr->getOperand(i+1);
9313
9314   // x86 address has 4 operands: base, index, scale, and displacement
9315   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9316   int valArgIndx = lastAddrIndx + 1;
9317
9318   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9319   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9320   for (int i=0; i <= lastAddrIndx; ++i)
9321     (*MIB).addOperand(*argOpers[i]);
9322
9323   // We only support register and immediate values
9324   assert((argOpers[valArgIndx]->isReg() ||
9325           argOpers[valArgIndx]->isImm()) &&
9326          "invalid operand");
9327
9328   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9329   if (argOpers[valArgIndx]->isReg())
9330     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9331   else
9332     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9333   (*MIB).addOperand(*argOpers[valArgIndx]);
9334
9335   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9336   MIB.addReg(t1);
9337
9338   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9339   MIB.addReg(t1);
9340   MIB.addReg(t2);
9341
9342   // Generate movc
9343   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9344   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9345   MIB.addReg(t2);
9346   MIB.addReg(t1);
9347
9348   // Cmp and exchange if none has modified the memory location
9349   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9350   for (int i=0; i <= lastAddrIndx; ++i)
9351     (*MIB).addOperand(*argOpers[i]);
9352   MIB.addReg(t3);
9353   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9354   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9355                     mInstr->memoperands_end());
9356
9357   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9358   MIB.addReg(X86::EAX);
9359
9360   // insert branch
9361   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9362
9363   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9364   return nextMBB;
9365 }
9366
9367 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9368 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9369 // in the .td file.
9370 MachineBasicBlock *
9371 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9372                             unsigned numArgs, bool memArg) const {
9373
9374   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9375          "Target must have SSE4.2 or AVX features enabled");
9376
9377   DebugLoc dl = MI->getDebugLoc();
9378   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9379
9380   unsigned Opc;
9381
9382   if (!Subtarget->hasAVX()) {
9383     if (memArg)
9384       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9385     else
9386       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9387   } else {
9388     if (memArg)
9389       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9390     else
9391       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9392   }
9393
9394   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9395
9396   for (unsigned i = 0; i < numArgs; ++i) {
9397     MachineOperand &Op = MI->getOperand(i+1);
9398
9399     if (!(Op.isReg() && Op.isImplicit()))
9400       MIB.addOperand(Op);
9401   }
9402
9403   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9404     .addReg(X86::XMM0);
9405
9406   MI->eraseFromParent();
9407
9408   return BB;
9409 }
9410
9411 MachineBasicBlock *
9412 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9413                                                  MachineInstr *MI,
9414                                                  MachineBasicBlock *MBB) const {
9415   // Emit code to save XMM registers to the stack. The ABI says that the
9416   // number of registers to save is given in %al, so it's theoretically
9417   // possible to do an indirect jump trick to avoid saving all of them,
9418   // however this code takes a simpler approach and just executes all
9419   // of the stores if %al is non-zero. It's less code, and it's probably
9420   // easier on the hardware branch predictor, and stores aren't all that
9421   // expensive anyway.
9422
9423   // Create the new basic blocks. One block contains all the XMM stores,
9424   // and one block is the final destination regardless of whether any
9425   // stores were performed.
9426   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9427   MachineFunction *F = MBB->getParent();
9428   MachineFunction::iterator MBBIter = MBB;
9429   ++MBBIter;
9430   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9431   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9432   F->insert(MBBIter, XMMSaveMBB);
9433   F->insert(MBBIter, EndMBB);
9434
9435   // Transfer the remainder of MBB and its successor edges to EndMBB.
9436   EndMBB->splice(EndMBB->begin(), MBB,
9437                  llvm::next(MachineBasicBlock::iterator(MI)),
9438                  MBB->end());
9439   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9440
9441   // The original block will now fall through to the XMM save block.
9442   MBB->addSuccessor(XMMSaveMBB);
9443   // The XMMSaveMBB will fall through to the end block.
9444   XMMSaveMBB->addSuccessor(EndMBB);
9445
9446   // Now add the instructions.
9447   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9448   DebugLoc DL = MI->getDebugLoc();
9449
9450   unsigned CountReg = MI->getOperand(0).getReg();
9451   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9452   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9453
9454   if (!Subtarget->isTargetWin64()) {
9455     // If %al is 0, branch around the XMM save block.
9456     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9457     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9458     MBB->addSuccessor(EndMBB);
9459   }
9460
9461   // In the XMM save block, save all the XMM argument registers.
9462   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9463     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9464     MachineMemOperand *MMO =
9465       F->getMachineMemOperand(
9466         MachinePointerInfo(PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
9467                            Offset),
9468         MachineMemOperand::MOStore,
9469         /*Size=*/16, /*Align=*/16);
9470     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9471       .addFrameIndex(RegSaveFrameIndex)
9472       .addImm(/*Scale=*/1)
9473       .addReg(/*IndexReg=*/0)
9474       .addImm(/*Disp=*/Offset)
9475       .addReg(/*Segment=*/0)
9476       .addReg(MI->getOperand(i).getReg())
9477       .addMemOperand(MMO);
9478   }
9479
9480   MI->eraseFromParent();   // The pseudo instruction is gone now.
9481
9482   return EndMBB;
9483 }
9484
9485 MachineBasicBlock *
9486 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9487                                      MachineBasicBlock *BB) const {
9488   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9489   DebugLoc DL = MI->getDebugLoc();
9490
9491   // To "insert" a SELECT_CC instruction, we actually have to insert the
9492   // diamond control-flow pattern.  The incoming instruction knows the
9493   // destination vreg to set, the condition code register to branch on, the
9494   // true/false values to select between, and a branch opcode to use.
9495   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9496   MachineFunction::iterator It = BB;
9497   ++It;
9498
9499   //  thisMBB:
9500   //  ...
9501   //   TrueVal = ...
9502   //   cmpTY ccX, r1, r2
9503   //   bCC copy1MBB
9504   //   fallthrough --> copy0MBB
9505   MachineBasicBlock *thisMBB = BB;
9506   MachineFunction *F = BB->getParent();
9507   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9508   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9509   F->insert(It, copy0MBB);
9510   F->insert(It, sinkMBB);
9511
9512   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9513   // live into the sink and copy blocks.
9514   const MachineFunction *MF = BB->getParent();
9515   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9516   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9517
9518   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9519     const MachineOperand &MO = MI->getOperand(I);
9520     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9521     unsigned Reg = MO.getReg();
9522     if (Reg != X86::EFLAGS) continue;
9523     copy0MBB->addLiveIn(Reg);
9524     sinkMBB->addLiveIn(Reg);
9525   }
9526
9527   // Transfer the remainder of BB and its successor edges to sinkMBB.
9528   sinkMBB->splice(sinkMBB->begin(), BB,
9529                   llvm::next(MachineBasicBlock::iterator(MI)),
9530                   BB->end());
9531   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9532
9533   // Add the true and fallthrough blocks as its successors.
9534   BB->addSuccessor(copy0MBB);
9535   BB->addSuccessor(sinkMBB);
9536
9537   // Create the conditional branch instruction.
9538   unsigned Opc =
9539     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9540   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9541
9542   //  copy0MBB:
9543   //   %FalseValue = ...
9544   //   # fallthrough to sinkMBB
9545   copy0MBB->addSuccessor(sinkMBB);
9546
9547   //  sinkMBB:
9548   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9549   //  ...
9550   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9551           TII->get(X86::PHI), MI->getOperand(0).getReg())
9552     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9553     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9554
9555   MI->eraseFromParent();   // The pseudo instruction is gone now.
9556   return sinkMBB;
9557 }
9558
9559 MachineBasicBlock *
9560 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9561                                           MachineBasicBlock *BB) const {
9562   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9563   DebugLoc DL = MI->getDebugLoc();
9564
9565   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9566   // non-trivial part is impdef of ESP.
9567   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9568   // mingw-w64.
9569
9570   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9571     .addExternalSymbol("_alloca")
9572     .addReg(X86::EAX, RegState::Implicit)
9573     .addReg(X86::ESP, RegState::Implicit)
9574     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9575     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9576     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9577
9578   MI->eraseFromParent();   // The pseudo instruction is gone now.
9579   return BB;
9580 }
9581
9582 MachineBasicBlock *
9583 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9584                                       MachineBasicBlock *BB) const {
9585   // This is pretty easy.  We're taking the value that we received from
9586   // our load from the relocation, sticking it in either RDI (x86-64)
9587   // or EAX and doing an indirect call.  The return value will then
9588   // be in the normal return register.
9589   const X86InstrInfo *TII 
9590     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9591   DebugLoc DL = MI->getDebugLoc();
9592   MachineFunction *F = BB->getParent();
9593   bool IsWin64 = Subtarget->isTargetWin64();
9594   
9595   assert(MI->getOperand(3).isGlobal() && "This should be a global");
9596   
9597   if (Subtarget->is64Bit()) {
9598     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9599                                       TII->get(X86::MOV64rm), X86::RDI)
9600     .addReg(X86::RIP)
9601     .addImm(0).addReg(0)
9602     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9603                       MI->getOperand(3).getTargetFlags())
9604     .addReg(0);
9605     MIB = BuildMI(*BB, MI, DL, TII->get(IsWin64 ? X86::WINCALL64m : X86::CALL64m));
9606     addDirectMem(MIB, X86::RDI);
9607   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9608     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9609                                       TII->get(X86::MOV32rm), X86::EAX)
9610     .addReg(0)
9611     .addImm(0).addReg(0)
9612     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9613                       MI->getOperand(3).getTargetFlags())
9614     .addReg(0);
9615     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9616     addDirectMem(MIB, X86::EAX);
9617   } else {
9618     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9619                                       TII->get(X86::MOV32rm), X86::EAX)
9620     .addReg(TII->getGlobalBaseReg(F))
9621     .addImm(0).addReg(0)
9622     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9623                       MI->getOperand(3).getTargetFlags())
9624     .addReg(0);
9625     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9626     addDirectMem(MIB, X86::EAX);
9627   }
9628   
9629   MI->eraseFromParent(); // The pseudo instruction is gone now.
9630   return BB;
9631 }
9632
9633 MachineBasicBlock *
9634 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9635                                                MachineBasicBlock *BB) const {
9636   switch (MI->getOpcode()) {
9637   default: assert(false && "Unexpected instr type to insert");
9638   case X86::MINGW_ALLOCA:
9639     return EmitLoweredMingwAlloca(MI, BB);
9640   case X86::TLSCall_32:
9641   case X86::TLSCall_64:
9642     return EmitLoweredTLSCall(MI, BB);
9643   case X86::CMOV_GR8:
9644   case X86::CMOV_V1I64:
9645   case X86::CMOV_FR32:
9646   case X86::CMOV_FR64:
9647   case X86::CMOV_V4F32:
9648   case X86::CMOV_V2F64:
9649   case X86::CMOV_V2I64:
9650   case X86::CMOV_GR16:
9651   case X86::CMOV_GR32:
9652   case X86::CMOV_RFP32:
9653   case X86::CMOV_RFP64:
9654   case X86::CMOV_RFP80:
9655     return EmitLoweredSelect(MI, BB);
9656
9657   case X86::FP32_TO_INT16_IN_MEM:
9658   case X86::FP32_TO_INT32_IN_MEM:
9659   case X86::FP32_TO_INT64_IN_MEM:
9660   case X86::FP64_TO_INT16_IN_MEM:
9661   case X86::FP64_TO_INT32_IN_MEM:
9662   case X86::FP64_TO_INT64_IN_MEM:
9663   case X86::FP80_TO_INT16_IN_MEM:
9664   case X86::FP80_TO_INT32_IN_MEM:
9665   case X86::FP80_TO_INT64_IN_MEM: {
9666     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9667     DebugLoc DL = MI->getDebugLoc();
9668
9669     // Change the floating point control register to use "round towards zero"
9670     // mode when truncating to an integer value.
9671     MachineFunction *F = BB->getParent();
9672     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9673     addFrameReference(BuildMI(*BB, MI, DL,
9674                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
9675
9676     // Load the old value of the high byte of the control word...
9677     unsigned OldCW =
9678       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9679     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9680                       CWFrameIdx);
9681
9682     // Set the high part to be round to zero...
9683     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9684       .addImm(0xC7F);
9685
9686     // Reload the modified control word now...
9687     addFrameReference(BuildMI(*BB, MI, DL,
9688                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9689
9690     // Restore the memory image of control word to original value
9691     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9692       .addReg(OldCW);
9693
9694     // Get the X86 opcode to use.
9695     unsigned Opc;
9696     switch (MI->getOpcode()) {
9697     default: llvm_unreachable("illegal opcode!");
9698     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9699     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9700     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9701     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9702     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9703     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9704     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9705     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9706     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9707     }
9708
9709     X86AddressMode AM;
9710     MachineOperand &Op = MI->getOperand(0);
9711     if (Op.isReg()) {
9712       AM.BaseType = X86AddressMode::RegBase;
9713       AM.Base.Reg = Op.getReg();
9714     } else {
9715       AM.BaseType = X86AddressMode::FrameIndexBase;
9716       AM.Base.FrameIndex = Op.getIndex();
9717     }
9718     Op = MI->getOperand(1);
9719     if (Op.isImm())
9720       AM.Scale = Op.getImm();
9721     Op = MI->getOperand(2);
9722     if (Op.isImm())
9723       AM.IndexReg = Op.getImm();
9724     Op = MI->getOperand(3);
9725     if (Op.isGlobal()) {
9726       AM.GV = Op.getGlobal();
9727     } else {
9728       AM.Disp = Op.getImm();
9729     }
9730     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9731                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9732
9733     // Reload the original control word now.
9734     addFrameReference(BuildMI(*BB, MI, DL,
9735                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9736
9737     MI->eraseFromParent();   // The pseudo instruction is gone now.
9738     return BB;
9739   }
9740     // String/text processing lowering.
9741   case X86::PCMPISTRM128REG:
9742   case X86::VPCMPISTRM128REG:
9743     return EmitPCMP(MI, BB, 3, false /* in-mem */);
9744   case X86::PCMPISTRM128MEM:
9745   case X86::VPCMPISTRM128MEM:
9746     return EmitPCMP(MI, BB, 3, true /* in-mem */);
9747   case X86::PCMPESTRM128REG:
9748   case X86::VPCMPESTRM128REG:
9749     return EmitPCMP(MI, BB, 5, false /* in mem */);
9750   case X86::PCMPESTRM128MEM:
9751   case X86::VPCMPESTRM128MEM:
9752     return EmitPCMP(MI, BB, 5, true /* in mem */);
9753
9754     // Atomic Lowering.
9755   case X86::ATOMAND32:
9756     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9757                                                X86::AND32ri, X86::MOV32rm,
9758                                                X86::LCMPXCHG32,
9759                                                X86::NOT32r, X86::EAX,
9760                                                X86::GR32RegisterClass);
9761   case X86::ATOMOR32:
9762     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9763                                                X86::OR32ri, X86::MOV32rm,
9764                                                X86::LCMPXCHG32,
9765                                                X86::NOT32r, X86::EAX,
9766                                                X86::GR32RegisterClass);
9767   case X86::ATOMXOR32:
9768     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9769                                                X86::XOR32ri, X86::MOV32rm,
9770                                                X86::LCMPXCHG32,
9771                                                X86::NOT32r, X86::EAX,
9772                                                X86::GR32RegisterClass);
9773   case X86::ATOMNAND32:
9774     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9775                                                X86::AND32ri, X86::MOV32rm,
9776                                                X86::LCMPXCHG32,
9777                                                X86::NOT32r, X86::EAX,
9778                                                X86::GR32RegisterClass, true);
9779   case X86::ATOMMIN32:
9780     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9781   case X86::ATOMMAX32:
9782     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9783   case X86::ATOMUMIN32:
9784     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9785   case X86::ATOMUMAX32:
9786     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9787
9788   case X86::ATOMAND16:
9789     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9790                                                X86::AND16ri, X86::MOV16rm,
9791                                                X86::LCMPXCHG16,
9792                                                X86::NOT16r, X86::AX,
9793                                                X86::GR16RegisterClass);
9794   case X86::ATOMOR16:
9795     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9796                                                X86::OR16ri, X86::MOV16rm,
9797                                                X86::LCMPXCHG16,
9798                                                X86::NOT16r, X86::AX,
9799                                                X86::GR16RegisterClass);
9800   case X86::ATOMXOR16:
9801     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9802                                                X86::XOR16ri, X86::MOV16rm,
9803                                                X86::LCMPXCHG16,
9804                                                X86::NOT16r, X86::AX,
9805                                                X86::GR16RegisterClass);
9806   case X86::ATOMNAND16:
9807     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9808                                                X86::AND16ri, X86::MOV16rm,
9809                                                X86::LCMPXCHG16,
9810                                                X86::NOT16r, X86::AX,
9811                                                X86::GR16RegisterClass, true);
9812   case X86::ATOMMIN16:
9813     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9814   case X86::ATOMMAX16:
9815     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9816   case X86::ATOMUMIN16:
9817     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9818   case X86::ATOMUMAX16:
9819     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9820
9821   case X86::ATOMAND8:
9822     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9823                                                X86::AND8ri, X86::MOV8rm,
9824                                                X86::LCMPXCHG8,
9825                                                X86::NOT8r, X86::AL,
9826                                                X86::GR8RegisterClass);
9827   case X86::ATOMOR8:
9828     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9829                                                X86::OR8ri, X86::MOV8rm,
9830                                                X86::LCMPXCHG8,
9831                                                X86::NOT8r, X86::AL,
9832                                                X86::GR8RegisterClass);
9833   case X86::ATOMXOR8:
9834     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9835                                                X86::XOR8ri, X86::MOV8rm,
9836                                                X86::LCMPXCHG8,
9837                                                X86::NOT8r, X86::AL,
9838                                                X86::GR8RegisterClass);
9839   case X86::ATOMNAND8:
9840     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9841                                                X86::AND8ri, X86::MOV8rm,
9842                                                X86::LCMPXCHG8,
9843                                                X86::NOT8r, X86::AL,
9844                                                X86::GR8RegisterClass, true);
9845   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9846   // This group is for 64-bit host.
9847   case X86::ATOMAND64:
9848     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9849                                                X86::AND64ri32, X86::MOV64rm,
9850                                                X86::LCMPXCHG64,
9851                                                X86::NOT64r, X86::RAX,
9852                                                X86::GR64RegisterClass);
9853   case X86::ATOMOR64:
9854     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9855                                                X86::OR64ri32, X86::MOV64rm,
9856                                                X86::LCMPXCHG64,
9857                                                X86::NOT64r, X86::RAX,
9858                                                X86::GR64RegisterClass);
9859   case X86::ATOMXOR64:
9860     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9861                                                X86::XOR64ri32, X86::MOV64rm,
9862                                                X86::LCMPXCHG64,
9863                                                X86::NOT64r, X86::RAX,
9864                                                X86::GR64RegisterClass);
9865   case X86::ATOMNAND64:
9866     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9867                                                X86::AND64ri32, X86::MOV64rm,
9868                                                X86::LCMPXCHG64,
9869                                                X86::NOT64r, X86::RAX,
9870                                                X86::GR64RegisterClass, true);
9871   case X86::ATOMMIN64:
9872     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9873   case X86::ATOMMAX64:
9874     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9875   case X86::ATOMUMIN64:
9876     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9877   case X86::ATOMUMAX64:
9878     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9879
9880   // This group does 64-bit operations on a 32-bit host.
9881   case X86::ATOMAND6432:
9882     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9883                                                X86::AND32rr, X86::AND32rr,
9884                                                X86::AND32ri, X86::AND32ri,
9885                                                false);
9886   case X86::ATOMOR6432:
9887     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9888                                                X86::OR32rr, X86::OR32rr,
9889                                                X86::OR32ri, X86::OR32ri,
9890                                                false);
9891   case X86::ATOMXOR6432:
9892     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9893                                                X86::XOR32rr, X86::XOR32rr,
9894                                                X86::XOR32ri, X86::XOR32ri,
9895                                                false);
9896   case X86::ATOMNAND6432:
9897     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9898                                                X86::AND32rr, X86::AND32rr,
9899                                                X86::AND32ri, X86::AND32ri,
9900                                                true);
9901   case X86::ATOMADD6432:
9902     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9903                                                X86::ADD32rr, X86::ADC32rr,
9904                                                X86::ADD32ri, X86::ADC32ri,
9905                                                false);
9906   case X86::ATOMSUB6432:
9907     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9908                                                X86::SUB32rr, X86::SBB32rr,
9909                                                X86::SUB32ri, X86::SBB32ri,
9910                                                false);
9911   case X86::ATOMSWAP6432:
9912     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9913                                                X86::MOV32rr, X86::MOV32rr,
9914                                                X86::MOV32ri, X86::MOV32ri,
9915                                                false);
9916   case X86::VASTART_SAVE_XMM_REGS:
9917     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9918   }
9919 }
9920
9921 //===----------------------------------------------------------------------===//
9922 //                           X86 Optimization Hooks
9923 //===----------------------------------------------------------------------===//
9924
9925 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9926                                                        const APInt &Mask,
9927                                                        APInt &KnownZero,
9928                                                        APInt &KnownOne,
9929                                                        const SelectionDAG &DAG,
9930                                                        unsigned Depth) const {
9931   unsigned Opc = Op.getOpcode();
9932   assert((Opc >= ISD::BUILTIN_OP_END ||
9933           Opc == ISD::INTRINSIC_WO_CHAIN ||
9934           Opc == ISD::INTRINSIC_W_CHAIN ||
9935           Opc == ISD::INTRINSIC_VOID) &&
9936          "Should use MaskedValueIsZero if you don't know whether Op"
9937          " is a target node!");
9938
9939   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
9940   switch (Opc) {
9941   default: break;
9942   case X86ISD::ADD:
9943   case X86ISD::SUB:
9944   case X86ISD::SMUL:
9945   case X86ISD::UMUL:
9946   case X86ISD::INC:
9947   case X86ISD::DEC:
9948   case X86ISD::OR:
9949   case X86ISD::XOR:
9950   case X86ISD::AND:
9951     // These nodes' second result is a boolean.
9952     if (Op.getResNo() == 0)
9953       break;
9954     // Fallthrough
9955   case X86ISD::SETCC:
9956     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9957                                        Mask.getBitWidth() - 1);
9958     break;
9959   }
9960 }
9961
9962 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9963 /// node is a GlobalAddress + offset.
9964 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9965                                        const GlobalValue* &GA,
9966                                        int64_t &Offset) const {
9967   if (N->getOpcode() == X86ISD::Wrapper) {
9968     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9969       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9970       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9971       return true;
9972     }
9973   }
9974   return TargetLowering::isGAPlusOffset(N, GA, Offset);
9975 }
9976
9977 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9978 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9979 /// if the load addresses are consecutive, non-overlapping, and in the right
9980 /// order.
9981 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9982                                      const TargetLowering &TLI) {
9983   DebugLoc dl = N->getDebugLoc();
9984   EVT VT = N->getValueType(0);
9985
9986   if (VT.getSizeInBits() != 128)
9987     return SDValue();
9988
9989   SmallVector<SDValue, 16> Elts;
9990   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9991     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
9992
9993   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9994 }
9995
9996 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
9997 /// generation and convert it from being a bunch of shuffles and extracts
9998 /// to a simple store and scalar loads to extract the elements.
9999 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10000                                                 const TargetLowering &TLI) {
10001   SDValue InputVector = N->getOperand(0);
10002
10003   // Only operate on vectors of 4 elements, where the alternative shuffling
10004   // gets to be more expensive.
10005   if (InputVector.getValueType() != MVT::v4i32)
10006     return SDValue();
10007
10008   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10009   // single use which is a sign-extend or zero-extend, and all elements are
10010   // used.
10011   SmallVector<SDNode *, 4> Uses;
10012   unsigned ExtractedElements = 0;
10013   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10014        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10015     if (UI.getUse().getResNo() != InputVector.getResNo())
10016       return SDValue();
10017
10018     SDNode *Extract = *UI;
10019     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10020       return SDValue();
10021
10022     if (Extract->getValueType(0) != MVT::i32)
10023       return SDValue();
10024     if (!Extract->hasOneUse())
10025       return SDValue();
10026     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10027         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10028       return SDValue();
10029     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10030       return SDValue();
10031
10032     // Record which element was extracted.
10033     ExtractedElements |=
10034       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10035
10036     Uses.push_back(Extract);
10037   }
10038
10039   // If not all the elements were used, this may not be worthwhile.
10040   if (ExtractedElements != 15)
10041     return SDValue();
10042
10043   // Ok, we've now decided to do the transformation.
10044   DebugLoc dl = InputVector.getDebugLoc();
10045
10046   // Store the value to a temporary stack slot.
10047   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10048   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL,
10049                             0, false, false, 0);
10050
10051   // Replace each use (extract) with a load of the appropriate element.
10052   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10053        UE = Uses.end(); UI != UE; ++UI) {
10054     SDNode *Extract = *UI;
10055
10056     // Compute the element's address.
10057     SDValue Idx = Extract->getOperand(1);
10058     unsigned EltSize =
10059         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10060     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10061     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10062
10063     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10064                                      OffsetVal, StackPtr);
10065
10066     // Load the scalar.
10067     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10068                                      ScalarAddr, NULL, 0, false, false, 0);
10069
10070     // Replace the exact with the load.
10071     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10072   }
10073
10074   // The replacement was made in place; don't return anything.
10075   return SDValue();
10076 }
10077
10078 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10079 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10080                                     const X86Subtarget *Subtarget) {
10081   DebugLoc DL = N->getDebugLoc();
10082   SDValue Cond = N->getOperand(0);
10083   // Get the LHS/RHS of the select.
10084   SDValue LHS = N->getOperand(1);
10085   SDValue RHS = N->getOperand(2);
10086
10087   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10088   // instructions match the semantics of the common C idiom x<y?x:y but not
10089   // x<=y?x:y, because of how they handle negative zero (which can be
10090   // ignored in unsafe-math mode).
10091   if (Subtarget->hasSSE2() &&
10092       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10093       Cond.getOpcode() == ISD::SETCC) {
10094     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10095
10096     unsigned Opcode = 0;
10097     // Check for x CC y ? x : y.
10098     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10099         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10100       switch (CC) {
10101       default: break;
10102       case ISD::SETULT:
10103         // Converting this to a min would handle NaNs incorrectly, and swapping
10104         // the operands would cause it to handle comparisons between positive
10105         // and negative zero incorrectly.
10106         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10107           if (!UnsafeFPMath &&
10108               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10109             break;
10110           std::swap(LHS, RHS);
10111         }
10112         Opcode = X86ISD::FMIN;
10113         break;
10114       case ISD::SETOLE:
10115         // Converting this to a min would handle comparisons between positive
10116         // and negative zero incorrectly.
10117         if (!UnsafeFPMath &&
10118             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10119           break;
10120         Opcode = X86ISD::FMIN;
10121         break;
10122       case ISD::SETULE:
10123         // Converting this to a min would handle both negative zeros and NaNs
10124         // incorrectly, but we can swap the operands to fix both.
10125         std::swap(LHS, RHS);
10126       case ISD::SETOLT:
10127       case ISD::SETLT:
10128       case ISD::SETLE:
10129         Opcode = X86ISD::FMIN;
10130         break;
10131
10132       case ISD::SETOGE:
10133         // Converting this to a max would handle comparisons between positive
10134         // and negative zero incorrectly.
10135         if (!UnsafeFPMath &&
10136             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10137           break;
10138         Opcode = X86ISD::FMAX;
10139         break;
10140       case ISD::SETUGT:
10141         // Converting this to a max would handle NaNs incorrectly, and swapping
10142         // the operands would cause it to handle comparisons between positive
10143         // and negative zero incorrectly.
10144         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10145           if (!UnsafeFPMath &&
10146               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10147             break;
10148           std::swap(LHS, RHS);
10149         }
10150         Opcode = X86ISD::FMAX;
10151         break;
10152       case ISD::SETUGE:
10153         // Converting this to a max would handle both negative zeros and NaNs
10154         // incorrectly, but we can swap the operands to fix both.
10155         std::swap(LHS, RHS);
10156       case ISD::SETOGT:
10157       case ISD::SETGT:
10158       case ISD::SETGE:
10159         Opcode = X86ISD::FMAX;
10160         break;
10161       }
10162     // Check for x CC y ? y : x -- a min/max with reversed arms.
10163     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10164                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10165       switch (CC) {
10166       default: break;
10167       case ISD::SETOGE:
10168         // Converting this to a min would handle comparisons between positive
10169         // and negative zero incorrectly, and swapping the operands would
10170         // cause it to handle NaNs incorrectly.
10171         if (!UnsafeFPMath &&
10172             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10173           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10174             break;
10175           std::swap(LHS, RHS);
10176         }
10177         Opcode = X86ISD::FMIN;
10178         break;
10179       case ISD::SETUGT:
10180         // Converting this to a min would handle NaNs incorrectly.
10181         if (!UnsafeFPMath &&
10182             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10183           break;
10184         Opcode = X86ISD::FMIN;
10185         break;
10186       case ISD::SETUGE:
10187         // Converting this to a min would handle both negative zeros and NaNs
10188         // incorrectly, but we can swap the operands to fix both.
10189         std::swap(LHS, RHS);
10190       case ISD::SETOGT:
10191       case ISD::SETGT:
10192       case ISD::SETGE:
10193         Opcode = X86ISD::FMIN;
10194         break;
10195
10196       case ISD::SETULT:
10197         // Converting this to a max would handle NaNs incorrectly.
10198         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10199           break;
10200         Opcode = X86ISD::FMAX;
10201         break;
10202       case ISD::SETOLE:
10203         // Converting this to a max would handle comparisons between positive
10204         // and negative zero incorrectly, and swapping the operands would
10205         // cause it to handle NaNs incorrectly.
10206         if (!UnsafeFPMath &&
10207             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10208           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10209             break;
10210           std::swap(LHS, RHS);
10211         }
10212         Opcode = X86ISD::FMAX;
10213         break;
10214       case ISD::SETULE:
10215         // Converting this to a max would handle both negative zeros and NaNs
10216         // incorrectly, but we can swap the operands to fix both.
10217         std::swap(LHS, RHS);
10218       case ISD::SETOLT:
10219       case ISD::SETLT:
10220       case ISD::SETLE:
10221         Opcode = X86ISD::FMAX;
10222         break;
10223       }
10224     }
10225
10226     if (Opcode)
10227       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10228   }
10229
10230   // If this is a select between two integer constants, try to do some
10231   // optimizations.
10232   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10233     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10234       // Don't do this for crazy integer types.
10235       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10236         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10237         // so that TrueC (the true value) is larger than FalseC.
10238         bool NeedsCondInvert = false;
10239
10240         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10241             // Efficiently invertible.
10242             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10243              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10244               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10245           NeedsCondInvert = true;
10246           std::swap(TrueC, FalseC);
10247         }
10248
10249         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10250         if (FalseC->getAPIntValue() == 0 &&
10251             TrueC->getAPIntValue().isPowerOf2()) {
10252           if (NeedsCondInvert) // Invert the condition if needed.
10253             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10254                                DAG.getConstant(1, Cond.getValueType()));
10255
10256           // Zero extend the condition if needed.
10257           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10258
10259           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10260           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10261                              DAG.getConstant(ShAmt, MVT::i8));
10262         }
10263
10264         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10265         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10266           if (NeedsCondInvert) // Invert the condition if needed.
10267             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10268                                DAG.getConstant(1, Cond.getValueType()));
10269
10270           // Zero extend the condition if needed.
10271           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10272                              FalseC->getValueType(0), Cond);
10273           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10274                              SDValue(FalseC, 0));
10275         }
10276
10277         // Optimize cases that will turn into an LEA instruction.  This requires
10278         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10279         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10280           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10281           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10282
10283           bool isFastMultiplier = false;
10284           if (Diff < 10) {
10285             switch ((unsigned char)Diff) {
10286               default: break;
10287               case 1:  // result = add base, cond
10288               case 2:  // result = lea base(    , cond*2)
10289               case 3:  // result = lea base(cond, cond*2)
10290               case 4:  // result = lea base(    , cond*4)
10291               case 5:  // result = lea base(cond, cond*4)
10292               case 8:  // result = lea base(    , cond*8)
10293               case 9:  // result = lea base(cond, cond*8)
10294                 isFastMultiplier = true;
10295                 break;
10296             }
10297           }
10298
10299           if (isFastMultiplier) {
10300             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10301             if (NeedsCondInvert) // Invert the condition if needed.
10302               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10303                                  DAG.getConstant(1, Cond.getValueType()));
10304
10305             // Zero extend the condition if needed.
10306             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10307                                Cond);
10308             // Scale the condition by the difference.
10309             if (Diff != 1)
10310               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10311                                  DAG.getConstant(Diff, Cond.getValueType()));
10312
10313             // Add the base if non-zero.
10314             if (FalseC->getAPIntValue() != 0)
10315               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10316                                  SDValue(FalseC, 0));
10317             return Cond;
10318           }
10319         }
10320       }
10321   }
10322
10323   return SDValue();
10324 }
10325
10326 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10327 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10328                                   TargetLowering::DAGCombinerInfo &DCI) {
10329   DebugLoc DL = N->getDebugLoc();
10330
10331   // If the flag operand isn't dead, don't touch this CMOV.
10332   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10333     return SDValue();
10334
10335   // If this is a select between two integer constants, try to do some
10336   // optimizations.  Note that the operands are ordered the opposite of SELECT
10337   // operands.
10338   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10339     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10340       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10341       // larger than FalseC (the false value).
10342       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10343
10344       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10345         CC = X86::GetOppositeBranchCondition(CC);
10346         std::swap(TrueC, FalseC);
10347       }
10348
10349       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10350       // This is efficient for any integer data type (including i8/i16) and
10351       // shift amount.
10352       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10353         SDValue Cond = N->getOperand(3);
10354         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10355                            DAG.getConstant(CC, MVT::i8), Cond);
10356
10357         // Zero extend the condition if needed.
10358         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10359
10360         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10361         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10362                            DAG.getConstant(ShAmt, MVT::i8));
10363         if (N->getNumValues() == 2)  // Dead flag value?
10364           return DCI.CombineTo(N, Cond, SDValue());
10365         return Cond;
10366       }
10367
10368       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10369       // for any integer data type, including i8/i16.
10370       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10371         SDValue Cond = N->getOperand(3);
10372         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10373                            DAG.getConstant(CC, MVT::i8), Cond);
10374
10375         // Zero extend the condition if needed.
10376         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10377                            FalseC->getValueType(0), Cond);
10378         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10379                            SDValue(FalseC, 0));
10380
10381         if (N->getNumValues() == 2)  // Dead flag value?
10382           return DCI.CombineTo(N, Cond, SDValue());
10383         return Cond;
10384       }
10385
10386       // Optimize cases that will turn into an LEA instruction.  This requires
10387       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10388       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10389         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10390         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10391
10392         bool isFastMultiplier = false;
10393         if (Diff < 10) {
10394           switch ((unsigned char)Diff) {
10395           default: break;
10396           case 1:  // result = add base, cond
10397           case 2:  // result = lea base(    , cond*2)
10398           case 3:  // result = lea base(cond, cond*2)
10399           case 4:  // result = lea base(    , cond*4)
10400           case 5:  // result = lea base(cond, cond*4)
10401           case 8:  // result = lea base(    , cond*8)
10402           case 9:  // result = lea base(cond, cond*8)
10403             isFastMultiplier = true;
10404             break;
10405           }
10406         }
10407
10408         if (isFastMultiplier) {
10409           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10410           SDValue Cond = N->getOperand(3);
10411           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10412                              DAG.getConstant(CC, MVT::i8), Cond);
10413           // Zero extend the condition if needed.
10414           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10415                              Cond);
10416           // Scale the condition by the difference.
10417           if (Diff != 1)
10418             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10419                                DAG.getConstant(Diff, Cond.getValueType()));
10420
10421           // Add the base if non-zero.
10422           if (FalseC->getAPIntValue() != 0)
10423             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10424                                SDValue(FalseC, 0));
10425           if (N->getNumValues() == 2)  // Dead flag value?
10426             return DCI.CombineTo(N, Cond, SDValue());
10427           return Cond;
10428         }
10429       }
10430     }
10431   }
10432   return SDValue();
10433 }
10434
10435
10436 /// PerformMulCombine - Optimize a single multiply with constant into two
10437 /// in order to implement it with two cheaper instructions, e.g.
10438 /// LEA + SHL, LEA + LEA.
10439 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10440                                  TargetLowering::DAGCombinerInfo &DCI) {
10441   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10442     return SDValue();
10443
10444   EVT VT = N->getValueType(0);
10445   if (VT != MVT::i64)
10446     return SDValue();
10447
10448   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10449   if (!C)
10450     return SDValue();
10451   uint64_t MulAmt = C->getZExtValue();
10452   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10453     return SDValue();
10454
10455   uint64_t MulAmt1 = 0;
10456   uint64_t MulAmt2 = 0;
10457   if ((MulAmt % 9) == 0) {
10458     MulAmt1 = 9;
10459     MulAmt2 = MulAmt / 9;
10460   } else if ((MulAmt % 5) == 0) {
10461     MulAmt1 = 5;
10462     MulAmt2 = MulAmt / 5;
10463   } else if ((MulAmt % 3) == 0) {
10464     MulAmt1 = 3;
10465     MulAmt2 = MulAmt / 3;
10466   }
10467   if (MulAmt2 &&
10468       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10469     DebugLoc DL = N->getDebugLoc();
10470
10471     if (isPowerOf2_64(MulAmt2) &&
10472         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10473       // If second multiplifer is pow2, issue it first. We want the multiply by
10474       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10475       // is an add.
10476       std::swap(MulAmt1, MulAmt2);
10477
10478     SDValue NewMul;
10479     if (isPowerOf2_64(MulAmt1))
10480       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10481                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10482     else
10483       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10484                            DAG.getConstant(MulAmt1, VT));
10485
10486     if (isPowerOf2_64(MulAmt2))
10487       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10488                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10489     else
10490       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10491                            DAG.getConstant(MulAmt2, VT));
10492
10493     // Do not add new nodes to DAG combiner worklist.
10494     DCI.CombineTo(N, NewMul, false);
10495   }
10496   return SDValue();
10497 }
10498
10499 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10500   SDValue N0 = N->getOperand(0);
10501   SDValue N1 = N->getOperand(1);
10502   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10503   EVT VT = N0.getValueType();
10504
10505   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10506   // since the result of setcc_c is all zero's or all ones.
10507   if (N1C && N0.getOpcode() == ISD::AND &&
10508       N0.getOperand(1).getOpcode() == ISD::Constant) {
10509     SDValue N00 = N0.getOperand(0);
10510     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10511         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10512           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10513          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10514       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10515       APInt ShAmt = N1C->getAPIntValue();
10516       Mask = Mask.shl(ShAmt);
10517       if (Mask != 0)
10518         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10519                            N00, DAG.getConstant(Mask, VT));
10520     }
10521   }
10522
10523   return SDValue();
10524 }
10525
10526 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10527 ///                       when possible.
10528 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10529                                    const X86Subtarget *Subtarget) {
10530   EVT VT = N->getValueType(0);
10531   if (!VT.isVector() && VT.isInteger() &&
10532       N->getOpcode() == ISD::SHL)
10533     return PerformSHLCombine(N, DAG);
10534
10535   // On X86 with SSE2 support, we can transform this to a vector shift if
10536   // all elements are shifted by the same amount.  We can't do this in legalize
10537   // because the a constant vector is typically transformed to a constant pool
10538   // so we have no knowledge of the shift amount.
10539   if (!Subtarget->hasSSE2())
10540     return SDValue();
10541
10542   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10543     return SDValue();
10544
10545   SDValue ShAmtOp = N->getOperand(1);
10546   EVT EltVT = VT.getVectorElementType();
10547   DebugLoc DL = N->getDebugLoc();
10548   SDValue BaseShAmt = SDValue();
10549   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10550     unsigned NumElts = VT.getVectorNumElements();
10551     unsigned i = 0;
10552     for (; i != NumElts; ++i) {
10553       SDValue Arg = ShAmtOp.getOperand(i);
10554       if (Arg.getOpcode() == ISD::UNDEF) continue;
10555       BaseShAmt = Arg;
10556       break;
10557     }
10558     for (; i != NumElts; ++i) {
10559       SDValue Arg = ShAmtOp.getOperand(i);
10560       if (Arg.getOpcode() == ISD::UNDEF) continue;
10561       if (Arg != BaseShAmt) {
10562         return SDValue();
10563       }
10564     }
10565   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10566              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10567     SDValue InVec = ShAmtOp.getOperand(0);
10568     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10569       unsigned NumElts = InVec.getValueType().getVectorNumElements();
10570       unsigned i = 0;
10571       for (; i != NumElts; ++i) {
10572         SDValue Arg = InVec.getOperand(i);
10573         if (Arg.getOpcode() == ISD::UNDEF) continue;
10574         BaseShAmt = Arg;
10575         break;
10576       }
10577     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10578        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10579          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10580          if (C->getZExtValue() == SplatIdx)
10581            BaseShAmt = InVec.getOperand(1);
10582        }
10583     }
10584     if (BaseShAmt.getNode() == 0)
10585       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10586                               DAG.getIntPtrConstant(0));
10587   } else
10588     return SDValue();
10589
10590   // The shift amount is an i32.
10591   if (EltVT.bitsGT(MVT::i32))
10592     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10593   else if (EltVT.bitsLT(MVT::i32))
10594     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10595
10596   // The shift amount is identical so we can do a vector shift.
10597   SDValue  ValOp = N->getOperand(0);
10598   switch (N->getOpcode()) {
10599   default:
10600     llvm_unreachable("Unknown shift opcode!");
10601     break;
10602   case ISD::SHL:
10603     if (VT == MVT::v2i64)
10604       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10605                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10606                          ValOp, BaseShAmt);
10607     if (VT == MVT::v4i32)
10608       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10609                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10610                          ValOp, BaseShAmt);
10611     if (VT == MVT::v8i16)
10612       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10613                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10614                          ValOp, BaseShAmt);
10615     break;
10616   case ISD::SRA:
10617     if (VT == MVT::v4i32)
10618       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10619                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10620                          ValOp, BaseShAmt);
10621     if (VT == MVT::v8i16)
10622       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10623                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10624                          ValOp, BaseShAmt);
10625     break;
10626   case ISD::SRL:
10627     if (VT == MVT::v2i64)
10628       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10629                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10630                          ValOp, BaseShAmt);
10631     if (VT == MVT::v4i32)
10632       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10633                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10634                          ValOp, BaseShAmt);
10635     if (VT ==  MVT::v8i16)
10636       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10637                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10638                          ValOp, BaseShAmt);
10639     break;
10640   }
10641   return SDValue();
10642 }
10643
10644 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10645                                 TargetLowering::DAGCombinerInfo &DCI,
10646                                 const X86Subtarget *Subtarget) {
10647   if (DCI.isBeforeLegalizeOps())
10648     return SDValue();
10649
10650   EVT VT = N->getValueType(0);
10651   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10652     return SDValue();
10653
10654   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10655   SDValue N0 = N->getOperand(0);
10656   SDValue N1 = N->getOperand(1);
10657   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10658     std::swap(N0, N1);
10659   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10660     return SDValue();
10661   if (!N0.hasOneUse() || !N1.hasOneUse())
10662     return SDValue();
10663
10664   SDValue ShAmt0 = N0.getOperand(1);
10665   if (ShAmt0.getValueType() != MVT::i8)
10666     return SDValue();
10667   SDValue ShAmt1 = N1.getOperand(1);
10668   if (ShAmt1.getValueType() != MVT::i8)
10669     return SDValue();
10670   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10671     ShAmt0 = ShAmt0.getOperand(0);
10672   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10673     ShAmt1 = ShAmt1.getOperand(0);
10674
10675   DebugLoc DL = N->getDebugLoc();
10676   unsigned Opc = X86ISD::SHLD;
10677   SDValue Op0 = N0.getOperand(0);
10678   SDValue Op1 = N1.getOperand(0);
10679   if (ShAmt0.getOpcode() == ISD::SUB) {
10680     Opc = X86ISD::SHRD;
10681     std::swap(Op0, Op1);
10682     std::swap(ShAmt0, ShAmt1);
10683   }
10684
10685   unsigned Bits = VT.getSizeInBits();
10686   if (ShAmt1.getOpcode() == ISD::SUB) {
10687     SDValue Sum = ShAmt1.getOperand(0);
10688     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10689       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10690       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10691         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10692       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10693         return DAG.getNode(Opc, DL, VT,
10694                            Op0, Op1,
10695                            DAG.getNode(ISD::TRUNCATE, DL,
10696                                        MVT::i8, ShAmt0));
10697     }
10698   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10699     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10700     if (ShAmt0C &&
10701         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10702       return DAG.getNode(Opc, DL, VT,
10703                          N0.getOperand(0), N1.getOperand(0),
10704                          DAG.getNode(ISD::TRUNCATE, DL,
10705                                        MVT::i8, ShAmt0));
10706   }
10707
10708   return SDValue();
10709 }
10710
10711 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10712 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10713                                    const X86Subtarget *Subtarget) {
10714   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
10715   // the FP state in cases where an emms may be missing.
10716   // A preferable solution to the general problem is to figure out the right
10717   // places to insert EMMS.  This qualifies as a quick hack.
10718
10719   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10720   StoreSDNode *St = cast<StoreSDNode>(N);
10721   EVT VT = St->getValue().getValueType();
10722   if (VT.getSizeInBits() != 64)
10723     return SDValue();
10724
10725   const Function *F = DAG.getMachineFunction().getFunction();
10726   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10727   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10728     && Subtarget->hasSSE2();
10729   if ((VT.isVector() ||
10730        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10731       isa<LoadSDNode>(St->getValue()) &&
10732       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10733       St->getChain().hasOneUse() && !St->isVolatile()) {
10734     SDNode* LdVal = St->getValue().getNode();
10735     LoadSDNode *Ld = 0;
10736     int TokenFactorIndex = -1;
10737     SmallVector<SDValue, 8> Ops;
10738     SDNode* ChainVal = St->getChain().getNode();
10739     // Must be a store of a load.  We currently handle two cases:  the load
10740     // is a direct child, and it's under an intervening TokenFactor.  It is
10741     // possible to dig deeper under nested TokenFactors.
10742     if (ChainVal == LdVal)
10743       Ld = cast<LoadSDNode>(St->getChain());
10744     else if (St->getValue().hasOneUse() &&
10745              ChainVal->getOpcode() == ISD::TokenFactor) {
10746       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10747         if (ChainVal->getOperand(i).getNode() == LdVal) {
10748           TokenFactorIndex = i;
10749           Ld = cast<LoadSDNode>(St->getValue());
10750         } else
10751           Ops.push_back(ChainVal->getOperand(i));
10752       }
10753     }
10754
10755     if (!Ld || !ISD::isNormalLoad(Ld))
10756       return SDValue();
10757
10758     // If this is not the MMX case, i.e. we are just turning i64 load/store
10759     // into f64 load/store, avoid the transformation if there are multiple
10760     // uses of the loaded value.
10761     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10762       return SDValue();
10763
10764     DebugLoc LdDL = Ld->getDebugLoc();
10765     DebugLoc StDL = N->getDebugLoc();
10766     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10767     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10768     // pair instead.
10769     if (Subtarget->is64Bit() || F64IsLegal) {
10770       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10771       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
10772                                   Ld->getBasePtr(), Ld->getSrcValue(),
10773                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
10774                                   Ld->isNonTemporal(), Ld->getAlignment());
10775       SDValue NewChain = NewLd.getValue(1);
10776       if (TokenFactorIndex != -1) {
10777         Ops.push_back(NewChain);
10778         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10779                                Ops.size());
10780       }
10781       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10782                           St->getSrcValue(), St->getSrcValueOffset(),
10783                           St->isVolatile(), St->isNonTemporal(),
10784                           St->getAlignment());
10785     }
10786
10787     // Otherwise, lower to two pairs of 32-bit loads / stores.
10788     SDValue LoAddr = Ld->getBasePtr();
10789     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10790                                  DAG.getConstant(4, MVT::i32));
10791
10792     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10793                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
10794                                Ld->isVolatile(), Ld->isNonTemporal(),
10795                                Ld->getAlignment());
10796     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10797                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
10798                                Ld->isVolatile(), Ld->isNonTemporal(),
10799                                MinAlign(Ld->getAlignment(), 4));
10800
10801     SDValue NewChain = LoLd.getValue(1);
10802     if (TokenFactorIndex != -1) {
10803       Ops.push_back(LoLd);
10804       Ops.push_back(HiLd);
10805       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10806                              Ops.size());
10807     }
10808
10809     LoAddr = St->getBasePtr();
10810     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10811                          DAG.getConstant(4, MVT::i32));
10812
10813     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10814                                 St->getSrcValue(), St->getSrcValueOffset(),
10815                                 St->isVolatile(), St->isNonTemporal(),
10816                                 St->getAlignment());
10817     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10818                                 St->getSrcValue(),
10819                                 St->getSrcValueOffset() + 4,
10820                                 St->isVolatile(),
10821                                 St->isNonTemporal(),
10822                                 MinAlign(St->getAlignment(), 4));
10823     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10824   }
10825   return SDValue();
10826 }
10827
10828 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10829 /// X86ISD::FXOR nodes.
10830 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10831   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10832   // F[X]OR(0.0, x) -> x
10833   // F[X]OR(x, 0.0) -> x
10834   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10835     if (C->getValueAPF().isPosZero())
10836       return N->getOperand(1);
10837   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10838     if (C->getValueAPF().isPosZero())
10839       return N->getOperand(0);
10840   return SDValue();
10841 }
10842
10843 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10844 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10845   // FAND(0.0, x) -> 0.0
10846   // FAND(x, 0.0) -> 0.0
10847   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10848     if (C->getValueAPF().isPosZero())
10849       return N->getOperand(0);
10850   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10851     if (C->getValueAPF().isPosZero())
10852       return N->getOperand(1);
10853   return SDValue();
10854 }
10855
10856 static SDValue PerformBTCombine(SDNode *N,
10857                                 SelectionDAG &DAG,
10858                                 TargetLowering::DAGCombinerInfo &DCI) {
10859   // BT ignores high bits in the bit index operand.
10860   SDValue Op1 = N->getOperand(1);
10861   if (Op1.hasOneUse()) {
10862     unsigned BitWidth = Op1.getValueSizeInBits();
10863     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10864     APInt KnownZero, KnownOne;
10865     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10866                                           !DCI.isBeforeLegalizeOps());
10867     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10868     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10869         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10870       DCI.CommitTargetLoweringOpt(TLO);
10871   }
10872   return SDValue();
10873 }
10874
10875 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10876   SDValue Op = N->getOperand(0);
10877   if (Op.getOpcode() == ISD::BIT_CONVERT)
10878     Op = Op.getOperand(0);
10879   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10880   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10881       VT.getVectorElementType().getSizeInBits() ==
10882       OpVT.getVectorElementType().getSizeInBits()) {
10883     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10884   }
10885   return SDValue();
10886 }
10887
10888 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10889   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
10890   //           (and (i32 x86isd::setcc_carry), 1)
10891   // This eliminates the zext. This transformation is necessary because
10892   // ISD::SETCC is always legalized to i8.
10893   DebugLoc dl = N->getDebugLoc();
10894   SDValue N0 = N->getOperand(0);
10895   EVT VT = N->getValueType(0);
10896   if (N0.getOpcode() == ISD::AND &&
10897       N0.hasOneUse() &&
10898       N0.getOperand(0).hasOneUse()) {
10899     SDValue N00 = N0.getOperand(0);
10900     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10901       return SDValue();
10902     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10903     if (!C || C->getZExtValue() != 1)
10904       return SDValue();
10905     return DAG.getNode(ISD::AND, dl, VT,
10906                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10907                                    N00.getOperand(0), N00.getOperand(1)),
10908                        DAG.getConstant(1, VT));
10909   }
10910
10911   return SDValue();
10912 }
10913
10914 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10915                                              DAGCombinerInfo &DCI) const {
10916   SelectionDAG &DAG = DCI.DAG;
10917   switch (N->getOpcode()) {
10918   default: break;
10919   case ISD::EXTRACT_VECTOR_ELT:
10920                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10921   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
10922   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
10923   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
10924   case ISD::SHL:
10925   case ISD::SRA:
10926   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
10927   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
10928   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
10929   case X86ISD::FXOR:
10930   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
10931   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
10932   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
10933   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
10934   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
10935   case X86ISD::SHUFPS:      // Handle all target specific shuffles
10936   case X86ISD::SHUFPD:
10937   case X86ISD::PALIGN:
10938   case X86ISD::PUNPCKHBW:
10939   case X86ISD::PUNPCKHWD:
10940   case X86ISD::PUNPCKHDQ:
10941   case X86ISD::PUNPCKHQDQ:
10942   case X86ISD::UNPCKHPS:
10943   case X86ISD::UNPCKHPD:
10944   case X86ISD::PUNPCKLBW:
10945   case X86ISD::PUNPCKLWD:
10946   case X86ISD::PUNPCKLDQ:
10947   case X86ISD::PUNPCKLQDQ:
10948   case X86ISD::UNPCKLPS:
10949   case X86ISD::UNPCKLPD:
10950   case X86ISD::MOVHLPS:
10951   case X86ISD::MOVLHPS:
10952   case X86ISD::PSHUFD:
10953   case X86ISD::PSHUFHW:
10954   case X86ISD::PSHUFLW:
10955   case X86ISD::MOVSS:
10956   case X86ISD::MOVSD:
10957   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10958   }
10959
10960   return SDValue();
10961 }
10962
10963 /// isTypeDesirableForOp - Return true if the target has native support for
10964 /// the specified value type and it is 'desirable' to use the type for the
10965 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10966 /// instruction encodings are longer and some i16 instructions are slow.
10967 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10968   if (!isTypeLegal(VT))
10969     return false;
10970   if (VT != MVT::i16)
10971     return true;
10972
10973   switch (Opc) {
10974   default:
10975     return true;
10976   case ISD::LOAD:
10977   case ISD::SIGN_EXTEND:
10978   case ISD::ZERO_EXTEND:
10979   case ISD::ANY_EXTEND:
10980   case ISD::SHL:
10981   case ISD::SRL:
10982   case ISD::SUB:
10983   case ISD::ADD:
10984   case ISD::MUL:
10985   case ISD::AND:
10986   case ISD::OR:
10987   case ISD::XOR:
10988     return false;
10989   }
10990 }
10991
10992 /// IsDesirableToPromoteOp - This method query the target whether it is
10993 /// beneficial for dag combiner to promote the specified node. If true, it
10994 /// should return the desired promotion type by reference.
10995 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10996   EVT VT = Op.getValueType();
10997   if (VT != MVT::i16)
10998     return false;
10999
11000   bool Promote = false;
11001   bool Commute = false;
11002   switch (Op.getOpcode()) {
11003   default: break;
11004   case ISD::LOAD: {
11005     LoadSDNode *LD = cast<LoadSDNode>(Op);
11006     // If the non-extending load has a single use and it's not live out, then it
11007     // might be folded.
11008     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11009                                                      Op.hasOneUse()*/) {
11010       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11011              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11012         // The only case where we'd want to promote LOAD (rather then it being
11013         // promoted as an operand is when it's only use is liveout.
11014         if (UI->getOpcode() != ISD::CopyToReg)
11015           return false;
11016       }
11017     }
11018     Promote = true;
11019     break;
11020   }
11021   case ISD::SIGN_EXTEND:
11022   case ISD::ZERO_EXTEND:
11023   case ISD::ANY_EXTEND:
11024     Promote = true;
11025     break;
11026   case ISD::SHL:
11027   case ISD::SRL: {
11028     SDValue N0 = Op.getOperand(0);
11029     // Look out for (store (shl (load), x)).
11030     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11031       return false;
11032     Promote = true;
11033     break;
11034   }
11035   case ISD::ADD:
11036   case ISD::MUL:
11037   case ISD::AND:
11038   case ISD::OR:
11039   case ISD::XOR:
11040     Commute = true;
11041     // fallthrough
11042   case ISD::SUB: {
11043     SDValue N0 = Op.getOperand(0);
11044     SDValue N1 = Op.getOperand(1);
11045     if (!Commute && MayFoldLoad(N1))
11046       return false;
11047     // Avoid disabling potential load folding opportunities.
11048     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11049       return false;
11050     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11051       return false;
11052     Promote = true;
11053   }
11054   }
11055
11056   PVT = MVT::i32;
11057   return Promote;
11058 }
11059
11060 //===----------------------------------------------------------------------===//
11061 //                           X86 Inline Assembly Support
11062 //===----------------------------------------------------------------------===//
11063
11064 static bool LowerToBSwap(CallInst *CI) {
11065   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11066   // we will turn this bswap into something that will be lowered to logical ops
11067   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11068   // so don't worry about this.
11069
11070   // Verify this is a simple bswap.
11071   if (CI->getNumArgOperands() != 1 ||
11072       CI->getType() != CI->getArgOperand(0)->getType() ||
11073       !CI->getType()->isIntegerTy())
11074     return false;
11075
11076   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11077   if (!Ty || Ty->getBitWidth() % 16 != 0)
11078     return false;
11079
11080   // Okay, we can do this xform, do so now.
11081   const Type *Tys[] = { Ty };
11082   Module *M = CI->getParent()->getParent()->getParent();
11083   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11084
11085   Value *Op = CI->getArgOperand(0);
11086   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11087
11088   CI->replaceAllUsesWith(Op);
11089   CI->eraseFromParent();
11090   return true;
11091 }
11092
11093 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11094   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11095   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11096
11097   std::string AsmStr = IA->getAsmString();
11098
11099   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11100   SmallVector<StringRef, 4> AsmPieces;
11101   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
11102
11103   switch (AsmPieces.size()) {
11104   default: return false;
11105   case 1:
11106     AsmStr = AsmPieces[0];
11107     AsmPieces.clear();
11108     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11109
11110     // bswap $0
11111     if (AsmPieces.size() == 2 &&
11112         (AsmPieces[0] == "bswap" ||
11113          AsmPieces[0] == "bswapq" ||
11114          AsmPieces[0] == "bswapl") &&
11115         (AsmPieces[1] == "$0" ||
11116          AsmPieces[1] == "${0:q}")) {
11117       // No need to check constraints, nothing other than the equivalent of
11118       // "=r,0" would be valid here.
11119       return LowerToBSwap(CI);
11120     }
11121     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11122     if (CI->getType()->isIntegerTy(16) &&
11123         AsmPieces.size() == 3 &&
11124         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11125         AsmPieces[1] == "$$8," &&
11126         AsmPieces[2] == "${0:w}" &&
11127         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11128       AsmPieces.clear();
11129       const std::string &Constraints = IA->getConstraintString();
11130       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11131       std::sort(AsmPieces.begin(), AsmPieces.end());
11132       if (AsmPieces.size() == 4 &&
11133           AsmPieces[0] == "~{cc}" &&
11134           AsmPieces[1] == "~{dirflag}" &&
11135           AsmPieces[2] == "~{flags}" &&
11136           AsmPieces[3] == "~{fpsr}") {
11137         return LowerToBSwap(CI);
11138       }
11139     }
11140     break;
11141   case 3:
11142     if (CI->getType()->isIntegerTy(64) &&
11143         Constraints.size() >= 2 &&
11144         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11145         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11146       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11147       SmallVector<StringRef, 4> Words;
11148       SplitString(AsmPieces[0], Words, " \t");
11149       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11150         Words.clear();
11151         SplitString(AsmPieces[1], Words, " \t");
11152         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11153           Words.clear();
11154           SplitString(AsmPieces[2], Words, " \t,");
11155           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11156               Words[2] == "%edx") {
11157             return LowerToBSwap(CI);
11158           }
11159         }
11160       }
11161     }
11162     break;
11163   }
11164   return false;
11165 }
11166
11167
11168
11169 /// getConstraintType - Given a constraint letter, return the type of
11170 /// constraint it is for this target.
11171 X86TargetLowering::ConstraintType
11172 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11173   if (Constraint.size() == 1) {
11174     switch (Constraint[0]) {
11175     case 'A':
11176       return C_Register;
11177     case 'f':
11178     case 'r':
11179     case 'R':
11180     case 'l':
11181     case 'q':
11182     case 'Q':
11183     case 'x':
11184     case 'y':
11185     case 'Y':
11186       return C_RegisterClass;
11187     case 'e':
11188     case 'Z':
11189       return C_Other;
11190     default:
11191       break;
11192     }
11193   }
11194   return TargetLowering::getConstraintType(Constraint);
11195 }
11196
11197 /// Examine constraint type and operand type and determine a weight value,
11198 /// where: -1 = invalid match, and 0 = so-so match to 3 = good match.
11199 /// This object must already have been set up with the operand type
11200 /// and the current alternative constraint selected.
11201 int X86TargetLowering::getSingleConstraintMatchWeight(
11202     AsmOperandInfo &info, const char *constraint) const {
11203   int weight = -1;
11204   Value *CallOperandVal = info.CallOperandVal;
11205     // If we don't have a value, we can't do a match,
11206     // but allow it at the lowest weight.
11207   if (CallOperandVal == NULL)
11208     return 0;
11209   // Look at the constraint type.
11210   switch (*constraint) {
11211   default:
11212     return TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11213     break;
11214   case 'I':
11215     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11216       if (C->getZExtValue() <= 31)
11217         weight = 3;
11218     }
11219     break;
11220   // etc.
11221   }
11222   return weight;
11223 }
11224
11225 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11226 /// with another that has more specific requirements based on the type of the
11227 /// corresponding operand.
11228 const char *X86TargetLowering::
11229 LowerXConstraint(EVT ConstraintVT) const {
11230   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11231   // 'f' like normal targets.
11232   if (ConstraintVT.isFloatingPoint()) {
11233     if (Subtarget->hasSSE2())
11234       return "Y";
11235     if (Subtarget->hasSSE1())
11236       return "x";
11237   }
11238
11239   return TargetLowering::LowerXConstraint(ConstraintVT);
11240 }
11241
11242 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11243 /// vector.  If it is invalid, don't add anything to Ops.
11244 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11245                                                      char Constraint,
11246                                                      std::vector<SDValue>&Ops,
11247                                                      SelectionDAG &DAG) const {
11248   SDValue Result(0, 0);
11249
11250   switch (Constraint) {
11251   default: break;
11252   case 'I':
11253     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11254       if (C->getZExtValue() <= 31) {
11255         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11256         break;
11257       }
11258     }
11259     return;
11260   case 'J':
11261     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11262       if (C->getZExtValue() <= 63) {
11263         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11264         break;
11265       }
11266     }
11267     return;
11268   case 'K':
11269     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11270       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11271         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11272         break;
11273       }
11274     }
11275     return;
11276   case 'N':
11277     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11278       if (C->getZExtValue() <= 255) {
11279         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11280         break;
11281       }
11282     }
11283     return;
11284   case 'e': {
11285     // 32-bit signed value
11286     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11287       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11288                                            C->getSExtValue())) {
11289         // Widen to 64 bits here to get it sign extended.
11290         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11291         break;
11292       }
11293     // FIXME gcc accepts some relocatable values here too, but only in certain
11294     // memory models; it's complicated.
11295     }
11296     return;
11297   }
11298   case 'Z': {
11299     // 32-bit unsigned value
11300     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11301       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11302                                            C->getZExtValue())) {
11303         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11304         break;
11305       }
11306     }
11307     // FIXME gcc accepts some relocatable values here too, but only in certain
11308     // memory models; it's complicated.
11309     return;
11310   }
11311   case 'i': {
11312     // Literal immediates are always ok.
11313     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11314       // Widen to 64 bits here to get it sign extended.
11315       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11316       break;
11317     }
11318
11319     // In any sort of PIC mode addresses need to be computed at runtime by
11320     // adding in a register or some sort of table lookup.  These can't
11321     // be used as immediates.
11322     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11323       return;
11324
11325     // If we are in non-pic codegen mode, we allow the address of a global (with
11326     // an optional displacement) to be used with 'i'.
11327     GlobalAddressSDNode *GA = 0;
11328     int64_t Offset = 0;
11329
11330     // Match either (GA), (GA+C), (GA+C1+C2), etc.
11331     while (1) {
11332       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11333         Offset += GA->getOffset();
11334         break;
11335       } else if (Op.getOpcode() == ISD::ADD) {
11336         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11337           Offset += C->getZExtValue();
11338           Op = Op.getOperand(0);
11339           continue;
11340         }
11341       } else if (Op.getOpcode() == ISD::SUB) {
11342         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11343           Offset += -C->getZExtValue();
11344           Op = Op.getOperand(0);
11345           continue;
11346         }
11347       }
11348
11349       // Otherwise, this isn't something we can handle, reject it.
11350       return;
11351     }
11352
11353     const GlobalValue *GV = GA->getGlobal();
11354     // If we require an extra load to get this address, as in PIC mode, we
11355     // can't accept it.
11356     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11357                                                         getTargetMachine())))
11358       return;
11359
11360     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11361                                         GA->getValueType(0), Offset);
11362     break;
11363   }
11364   }
11365
11366   if (Result.getNode()) {
11367     Ops.push_back(Result);
11368     return;
11369   }
11370   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11371 }
11372
11373 std::vector<unsigned> X86TargetLowering::
11374 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11375                                   EVT VT) const {
11376   if (Constraint.size() == 1) {
11377     // FIXME: not handling fp-stack yet!
11378     switch (Constraint[0]) {      // GCC X86 Constraint Letters
11379     default: break;  // Unknown constraint letter
11380     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11381       if (Subtarget->is64Bit()) {
11382         if (VT == MVT::i32)
11383           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11384                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11385                                        X86::R10D,X86::R11D,X86::R12D,
11386                                        X86::R13D,X86::R14D,X86::R15D,
11387                                        X86::EBP, X86::ESP, 0);
11388         else if (VT == MVT::i16)
11389           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
11390                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
11391                                        X86::R10W,X86::R11W,X86::R12W,
11392                                        X86::R13W,X86::R14W,X86::R15W,
11393                                        X86::BP,  X86::SP, 0);
11394         else if (VT == MVT::i8)
11395           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
11396                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11397                                        X86::R10B,X86::R11B,X86::R12B,
11398                                        X86::R13B,X86::R14B,X86::R15B,
11399                                        X86::BPL, X86::SPL, 0);
11400
11401         else if (VT == MVT::i64)
11402           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11403                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
11404                                        X86::R10, X86::R11, X86::R12,
11405                                        X86::R13, X86::R14, X86::R15,
11406                                        X86::RBP, X86::RSP, 0);
11407
11408         break;
11409       }
11410       // 32-bit fallthrough
11411     case 'Q':   // Q_REGS
11412       if (VT == MVT::i32)
11413         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11414       else if (VT == MVT::i16)
11415         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11416       else if (VT == MVT::i8)
11417         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11418       else if (VT == MVT::i64)
11419         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11420       break;
11421     }
11422   }
11423
11424   return std::vector<unsigned>();
11425 }
11426
11427 std::pair<unsigned, const TargetRegisterClass*>
11428 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11429                                                 EVT VT) const {
11430   // First, see if this is a constraint that directly corresponds to an LLVM
11431   // register class.
11432   if (Constraint.size() == 1) {
11433     // GCC Constraint Letters
11434     switch (Constraint[0]) {
11435     default: break;
11436     case 'r':   // GENERAL_REGS
11437     case 'l':   // INDEX_REGS
11438       if (VT == MVT::i8)
11439         return std::make_pair(0U, X86::GR8RegisterClass);
11440       if (VT == MVT::i16)
11441         return std::make_pair(0U, X86::GR16RegisterClass);
11442       if (VT == MVT::i32 || !Subtarget->is64Bit())
11443         return std::make_pair(0U, X86::GR32RegisterClass);
11444       return std::make_pair(0U, X86::GR64RegisterClass);
11445     case 'R':   // LEGACY_REGS
11446       if (VT == MVT::i8)
11447         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11448       if (VT == MVT::i16)
11449         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11450       if (VT == MVT::i32 || !Subtarget->is64Bit())
11451         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11452       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11453     case 'f':  // FP Stack registers.
11454       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11455       // value to the correct fpstack register class.
11456       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11457         return std::make_pair(0U, X86::RFP32RegisterClass);
11458       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11459         return std::make_pair(0U, X86::RFP64RegisterClass);
11460       return std::make_pair(0U, X86::RFP80RegisterClass);
11461     case 'y':   // MMX_REGS if MMX allowed.
11462       if (!Subtarget->hasMMX()) break;
11463       return std::make_pair(0U, X86::VR64RegisterClass);
11464     case 'Y':   // SSE_REGS if SSE2 allowed
11465       if (!Subtarget->hasSSE2()) break;
11466       // FALL THROUGH.
11467     case 'x':   // SSE_REGS if SSE1 allowed
11468       if (!Subtarget->hasSSE1()) break;
11469
11470       switch (VT.getSimpleVT().SimpleTy) {
11471       default: break;
11472       // Scalar SSE types.
11473       case MVT::f32:
11474       case MVT::i32:
11475         return std::make_pair(0U, X86::FR32RegisterClass);
11476       case MVT::f64:
11477       case MVT::i64:
11478         return std::make_pair(0U, X86::FR64RegisterClass);
11479       // Vector types.
11480       case MVT::v16i8:
11481       case MVT::v8i16:
11482       case MVT::v4i32:
11483       case MVT::v2i64:
11484       case MVT::v4f32:
11485       case MVT::v2f64:
11486         return std::make_pair(0U, X86::VR128RegisterClass);
11487       }
11488       break;
11489     }
11490   }
11491
11492   // Use the default implementation in TargetLowering to convert the register
11493   // constraint into a member of a register class.
11494   std::pair<unsigned, const TargetRegisterClass*> Res;
11495   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11496
11497   // Not found as a standard register?
11498   if (Res.second == 0) {
11499     // Map st(0) -> st(7) -> ST0
11500     if (Constraint.size() == 7 && Constraint[0] == '{' &&
11501         tolower(Constraint[1]) == 's' &&
11502         tolower(Constraint[2]) == 't' &&
11503         Constraint[3] == '(' &&
11504         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11505         Constraint[5] == ')' &&
11506         Constraint[6] == '}') {
11507
11508       Res.first = X86::ST0+Constraint[4]-'0';
11509       Res.second = X86::RFP80RegisterClass;
11510       return Res;
11511     }
11512
11513     // GCC allows "st(0)" to be called just plain "st".
11514     if (StringRef("{st}").equals_lower(Constraint)) {
11515       Res.first = X86::ST0;
11516       Res.second = X86::RFP80RegisterClass;
11517       return Res;
11518     }
11519
11520     // flags -> EFLAGS
11521     if (StringRef("{flags}").equals_lower(Constraint)) {
11522       Res.first = X86::EFLAGS;
11523       Res.second = X86::CCRRegisterClass;
11524       return Res;
11525     }
11526
11527     // 'A' means EAX + EDX.
11528     if (Constraint == "A") {
11529       Res.first = X86::EAX;
11530       Res.second = X86::GR32_ADRegisterClass;
11531       return Res;
11532     }
11533     return Res;
11534   }
11535
11536   // Otherwise, check to see if this is a register class of the wrong value
11537   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11538   // turn into {ax},{dx}.
11539   if (Res.second->hasType(VT))
11540     return Res;   // Correct type already, nothing to do.
11541
11542   // All of the single-register GCC register classes map their values onto
11543   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
11544   // really want an 8-bit or 32-bit register, map to the appropriate register
11545   // class and return the appropriate register.
11546   if (Res.second == X86::GR16RegisterClass) {
11547     if (VT == MVT::i8) {
11548       unsigned DestReg = 0;
11549       switch (Res.first) {
11550       default: break;
11551       case X86::AX: DestReg = X86::AL; break;
11552       case X86::DX: DestReg = X86::DL; break;
11553       case X86::CX: DestReg = X86::CL; break;
11554       case X86::BX: DestReg = X86::BL; break;
11555       }
11556       if (DestReg) {
11557         Res.first = DestReg;
11558         Res.second = X86::GR8RegisterClass;
11559       }
11560     } else if (VT == MVT::i32) {
11561       unsigned DestReg = 0;
11562       switch (Res.first) {
11563       default: break;
11564       case X86::AX: DestReg = X86::EAX; break;
11565       case X86::DX: DestReg = X86::EDX; break;
11566       case X86::CX: DestReg = X86::ECX; break;
11567       case X86::BX: DestReg = X86::EBX; break;
11568       case X86::SI: DestReg = X86::ESI; break;
11569       case X86::DI: DestReg = X86::EDI; break;
11570       case X86::BP: DestReg = X86::EBP; break;
11571       case X86::SP: DestReg = X86::ESP; break;
11572       }
11573       if (DestReg) {
11574         Res.first = DestReg;
11575         Res.second = X86::GR32RegisterClass;
11576       }
11577     } else if (VT == MVT::i64) {
11578       unsigned DestReg = 0;
11579       switch (Res.first) {
11580       default: break;
11581       case X86::AX: DestReg = X86::RAX; break;
11582       case X86::DX: DestReg = X86::RDX; break;
11583       case X86::CX: DestReg = X86::RCX; break;
11584       case X86::BX: DestReg = X86::RBX; break;
11585       case X86::SI: DestReg = X86::RSI; break;
11586       case X86::DI: DestReg = X86::RDI; break;
11587       case X86::BP: DestReg = X86::RBP; break;
11588       case X86::SP: DestReg = X86::RSP; break;
11589       }
11590       if (DestReg) {
11591         Res.first = DestReg;
11592         Res.second = X86::GR64RegisterClass;
11593       }
11594     }
11595   } else if (Res.second == X86::FR32RegisterClass ||
11596              Res.second == X86::FR64RegisterClass ||
11597              Res.second == X86::VR128RegisterClass) {
11598     // Handle references to XMM physical registers that got mapped into the
11599     // wrong class.  This can happen with constraints like {xmm0} where the
11600     // target independent register mapper will just pick the first match it can
11601     // find, ignoring the required type.
11602     if (VT == MVT::f32)
11603       Res.second = X86::FR32RegisterClass;
11604     else if (VT == MVT::f64)
11605       Res.second = X86::FR64RegisterClass;
11606     else if (X86::VR128RegisterClass->hasType(VT))
11607       Res.second = X86::VR128RegisterClass;
11608   }
11609
11610   return Res;
11611 }