28bc10a9b6b8d74eddeaa3a0eb087652cdc39c6e
[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     // or SSE or MMX vectors.
1320     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1321          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1322           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1323       report_fatal_error("SSE register return with SSE disabled");
1324     }
1325     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1326     // llvm-gcc has never done it right and no one has noticed, so this
1327     // should be OK for now.
1328     if (ValVT == MVT::f64 &&
1329         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1330       report_fatal_error("SSE2 register return with SSE2 disabled");
1331
1332     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1333     // the RET instruction and handled by the FP Stackifier.
1334     if (VA.getLocReg() == X86::ST0 ||
1335         VA.getLocReg() == X86::ST1) {
1336       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1337       // change the value to the FP stack register class.
1338       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1339         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1340       RetOps.push_back(ValToCopy);
1341       // Don't emit a copytoreg.
1342       continue;
1343     }
1344
1345     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1346     // which is returned in RAX / RDX.
1347     if (Subtarget->is64Bit()) {
1348       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1349         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1350         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1351           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1352                                   ValToCopy);
1353           
1354           // If we don't have SSE2 available, convert to v4f32 so the generated
1355           // register is legal.
1356           if (!Subtarget->hasSSE2())
1357             ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32,ValToCopy);
1358         }
1359       }
1360     }
1361     
1362     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1363     Flag = Chain.getValue(1);
1364   }
1365
1366   // The x86-64 ABI for returning structs by value requires that we copy
1367   // the sret argument into %rax for the return. We saved the argument into
1368   // a virtual register in the entry block, so now we copy the value out
1369   // and into %rax.
1370   if (Subtarget->is64Bit() &&
1371       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1372     MachineFunction &MF = DAG.getMachineFunction();
1373     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1374     unsigned Reg = FuncInfo->getSRetReturnReg();
1375     assert(Reg && 
1376            "SRetReturnReg should have been set in LowerFormalArguments().");
1377     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1378
1379     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1380     Flag = Chain.getValue(1);
1381
1382     // RAX now acts like a return value.
1383     MRI.addLiveOut(X86::RAX);
1384   }
1385
1386   RetOps[0] = Chain;  // Update chain.
1387
1388   // Add the flag if we have it.
1389   if (Flag.getNode())
1390     RetOps.push_back(Flag);
1391
1392   return DAG.getNode(X86ISD::RET_FLAG, dl,
1393                      MVT::Other, &RetOps[0], RetOps.size());
1394 }
1395
1396 /// LowerCallResult - Lower the result values of a call into the
1397 /// appropriate copies out of appropriate physical registers.
1398 ///
1399 SDValue
1400 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1401                                    CallingConv::ID CallConv, bool isVarArg,
1402                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1403                                    DebugLoc dl, SelectionDAG &DAG,
1404                                    SmallVectorImpl<SDValue> &InVals) const {
1405
1406   // Assign locations to each value returned by this call.
1407   SmallVector<CCValAssign, 16> RVLocs;
1408   bool Is64Bit = Subtarget->is64Bit();
1409   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1410                  RVLocs, *DAG.getContext());
1411   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1412
1413   // Copy all of the result registers out of their specified physreg.
1414   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1415     CCValAssign &VA = RVLocs[i];
1416     EVT CopyVT = VA.getValVT();
1417
1418     // If this is x86-64, and we disabled SSE, we can't return FP values
1419     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1420         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1421       report_fatal_error("SSE register return with SSE disabled");
1422     }
1423
1424     SDValue Val;
1425
1426     // If this is a call to a function that returns an fp value on the floating
1427     // point stack, we must guarantee the the value is popped from the stack, so
1428     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1429     // if the return value is not used. We use the FpGET_ST0 instructions
1430     // instead.
1431     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1432       // If we prefer to use the value in xmm registers, copy it out as f80 and
1433       // use a truncate to move it from fp stack reg to xmm reg.
1434       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1435       bool isST0 = VA.getLocReg() == X86::ST0;
1436       unsigned Opc = 0;
1437       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1438       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1439       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1440       SDValue Ops[] = { Chain, InFlag };
1441       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1442                                          Ops, 2), 1);
1443       Val = Chain.getValue(0);
1444
1445       // Round the f80 to the right size, which also moves it to the appropriate
1446       // xmm register.
1447       if (CopyVT != VA.getValVT())
1448         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1449                           // This truncation won't change the value.
1450                           DAG.getIntPtrConstant(1));
1451     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1452       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1453       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1454         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1455                                    MVT::v2i64, InFlag).getValue(1);
1456         Val = Chain.getValue(0);
1457         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1458                           Val, DAG.getConstant(0, MVT::i64));
1459       } else {
1460         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1461                                    MVT::i64, InFlag).getValue(1);
1462         Val = Chain.getValue(0);
1463       }
1464       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1465     } else {
1466       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1467                                  CopyVT, InFlag).getValue(1);
1468       Val = Chain.getValue(0);
1469     }
1470     InFlag = Chain.getValue(2);
1471     InVals.push_back(Val);
1472   }
1473
1474   return Chain;
1475 }
1476
1477
1478 //===----------------------------------------------------------------------===//
1479 //                C & StdCall & Fast Calling Convention implementation
1480 //===----------------------------------------------------------------------===//
1481 //  StdCall calling convention seems to be standard for many Windows' API
1482 //  routines and around. It differs from C calling convention just a little:
1483 //  callee should clean up the stack, not caller. Symbols should be also
1484 //  decorated in some fancy way :) It doesn't support any vector arguments.
1485 //  For info on fast calling convention see Fast Calling Convention (tail call)
1486 //  implementation LowerX86_32FastCCCallTo.
1487
1488 /// CallIsStructReturn - Determines whether a call uses struct return
1489 /// semantics.
1490 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1491   if (Outs.empty())
1492     return false;
1493
1494   return Outs[0].Flags.isSRet();
1495 }
1496
1497 /// ArgsAreStructReturn - Determines whether a function uses struct
1498 /// return semantics.
1499 static bool
1500 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1501   if (Ins.empty())
1502     return false;
1503
1504   return Ins[0].Flags.isSRet();
1505 }
1506
1507 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1508 /// given CallingConvention value.
1509 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1510   if (Subtarget->is64Bit()) {
1511     if (CC == CallingConv::GHC)
1512       return CC_X86_64_GHC;
1513     else if (Subtarget->isTargetWin64())
1514       return CC_X86_Win64_C;
1515     else
1516       return CC_X86_64_C;
1517   }
1518
1519   if (CC == CallingConv::X86_FastCall)
1520     return CC_X86_32_FastCall;
1521   else if (CC == CallingConv::X86_ThisCall)
1522     return CC_X86_32_ThisCall;
1523   else if (CC == CallingConv::Fast)
1524     return CC_X86_32_FastCC;
1525   else if (CC == CallingConv::GHC)
1526     return CC_X86_32_GHC;
1527   else
1528     return CC_X86_32_C;
1529 }
1530
1531 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1532 /// by "Src" to address "Dst" with size and alignment information specified by
1533 /// the specific parameter attribute. The copy will be passed as a byval
1534 /// function parameter.
1535 static SDValue
1536 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1537                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1538                           DebugLoc dl) {
1539   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1540   
1541   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1542                        /*isVolatile*/false, /*AlwaysInline=*/true,
1543                        MachinePointerInfo(), MachinePointerInfo());
1544 }
1545
1546 /// IsTailCallConvention - Return true if the calling convention is one that
1547 /// supports tail call optimization.
1548 static bool IsTailCallConvention(CallingConv::ID CC) {
1549   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1550 }
1551
1552 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1553 /// a tailcall target by changing its ABI.
1554 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1555   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1556 }
1557
1558 SDValue
1559 X86TargetLowering::LowerMemArgument(SDValue Chain,
1560                                     CallingConv::ID CallConv,
1561                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1562                                     DebugLoc dl, SelectionDAG &DAG,
1563                                     const CCValAssign &VA,
1564                                     MachineFrameInfo *MFI,
1565                                     unsigned i) const {
1566   // Create the nodes corresponding to a load from this parameter slot.
1567   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1568   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1569   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1570   EVT ValVT;
1571
1572   // If value is passed by pointer we have address passed instead of the value
1573   // itself.
1574   if (VA.getLocInfo() == CCValAssign::Indirect)
1575     ValVT = VA.getLocVT();
1576   else
1577     ValVT = VA.getValVT();
1578
1579   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1580   // changed with more analysis.
1581   // In case of tail call optimization mark all arguments mutable. Since they
1582   // could be overwritten by lowering of arguments in case of a tail call.
1583   if (Flags.isByVal()) {
1584     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1585                                     VA.getLocMemOffset(), isImmutable);
1586     return DAG.getFrameIndex(FI, getPointerTy());
1587   } else {
1588     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1589                                     VA.getLocMemOffset(), isImmutable);
1590     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1591     return DAG.getLoad(ValVT, dl, Chain, FIN,
1592                        MachinePointerInfo::getFixedStack(FI),
1593                        false, false, 0);
1594   }
1595 }
1596
1597 SDValue
1598 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1599                                         CallingConv::ID CallConv,
1600                                         bool isVarArg,
1601                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1602                                         DebugLoc dl,
1603                                         SelectionDAG &DAG,
1604                                         SmallVectorImpl<SDValue> &InVals)
1605                                           const {
1606   MachineFunction &MF = DAG.getMachineFunction();
1607   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1608
1609   const Function* Fn = MF.getFunction();
1610   if (Fn->hasExternalLinkage() &&
1611       Subtarget->isTargetCygMing() &&
1612       Fn->getName() == "main")
1613     FuncInfo->setForceFramePointer(true);
1614
1615   MachineFrameInfo *MFI = MF.getFrameInfo();
1616   bool Is64Bit = Subtarget->is64Bit();
1617   bool IsWin64 = Subtarget->isTargetWin64();
1618
1619   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1620          "Var args not supported with calling convention fastcc or ghc");
1621
1622   // Assign locations to all of the incoming arguments.
1623   SmallVector<CCValAssign, 16> ArgLocs;
1624   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1625                  ArgLocs, *DAG.getContext());
1626   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1627
1628   unsigned LastVal = ~0U;
1629   SDValue ArgValue;
1630   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1631     CCValAssign &VA = ArgLocs[i];
1632     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1633     // places.
1634     assert(VA.getValNo() != LastVal &&
1635            "Don't support value assigned to multiple locs yet");
1636     LastVal = VA.getValNo();
1637
1638     if (VA.isRegLoc()) {
1639       EVT RegVT = VA.getLocVT();
1640       TargetRegisterClass *RC = NULL;
1641       if (RegVT == MVT::i32)
1642         RC = X86::GR32RegisterClass;
1643       else if (Is64Bit && RegVT == MVT::i64)
1644         RC = X86::GR64RegisterClass;
1645       else if (RegVT == MVT::f32)
1646         RC = X86::FR32RegisterClass;
1647       else if (RegVT == MVT::f64)
1648         RC = X86::FR64RegisterClass;
1649       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1650         RC = X86::VR256RegisterClass;
1651       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1652         RC = X86::VR128RegisterClass;
1653       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1654         RC = X86::VR64RegisterClass;
1655       else
1656         llvm_unreachable("Unknown argument type!");
1657
1658       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1659       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1660
1661       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1662       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1663       // right size.
1664       if (VA.getLocInfo() == CCValAssign::SExt)
1665         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1666                                DAG.getValueType(VA.getValVT()));
1667       else if (VA.getLocInfo() == CCValAssign::ZExt)
1668         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1669                                DAG.getValueType(VA.getValVT()));
1670       else if (VA.getLocInfo() == CCValAssign::BCvt)
1671         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1672
1673       if (VA.isExtInLoc()) {
1674         // Handle MMX values passed in XMM regs.
1675         if (RegVT.isVector()) {
1676           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1677                                  ArgValue, DAG.getConstant(0, MVT::i64));
1678           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1679         } else
1680           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1681       }
1682     } else {
1683       assert(VA.isMemLoc());
1684       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1685     }
1686
1687     // If value is passed via pointer - do a load.
1688     if (VA.getLocInfo() == CCValAssign::Indirect)
1689       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1690                              MachinePointerInfo(), false, false, 0);
1691
1692     InVals.push_back(ArgValue);
1693   }
1694
1695   // The x86-64 ABI for returning structs by value requires that we copy
1696   // the sret argument into %rax for the return. Save the argument into
1697   // a virtual register so that we can access it from the return points.
1698   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1699     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1700     unsigned Reg = FuncInfo->getSRetReturnReg();
1701     if (!Reg) {
1702       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1703       FuncInfo->setSRetReturnReg(Reg);
1704     }
1705     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1706     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1707   }
1708
1709   unsigned StackSize = CCInfo.getNextStackOffset();
1710   // Align stack specially for tail calls.
1711   if (FuncIsMadeTailCallSafe(CallConv))
1712     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1713
1714   // If the function takes variable number of arguments, make a frame index for
1715   // the start of the first vararg value... for expansion of llvm.va_start.
1716   if (isVarArg) {
1717     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1718                     CallConv != CallingConv::X86_ThisCall)) {
1719       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1720     }
1721     if (Is64Bit) {
1722       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1723
1724       // FIXME: We should really autogenerate these arrays
1725       static const unsigned GPR64ArgRegsWin64[] = {
1726         X86::RCX, X86::RDX, X86::R8,  X86::R9
1727       };
1728       static const unsigned XMMArgRegsWin64[] = {
1729         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1730       };
1731       static const unsigned GPR64ArgRegs64Bit[] = {
1732         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1733       };
1734       static const unsigned XMMArgRegs64Bit[] = {
1735         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1736         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1737       };
1738       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1739
1740       if (IsWin64) {
1741         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1742         GPR64ArgRegs = GPR64ArgRegsWin64;
1743         XMMArgRegs = XMMArgRegsWin64;
1744       } else {
1745         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1746         GPR64ArgRegs = GPR64ArgRegs64Bit;
1747         XMMArgRegs = XMMArgRegs64Bit;
1748       }
1749       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1750                                                        TotalNumIntRegs);
1751       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1752                                                        TotalNumXMMRegs);
1753
1754       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1755       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1756              "SSE register cannot be used when SSE is disabled!");
1757       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1758              "SSE register cannot be used when SSE is disabled!");
1759       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1760         // Kernel mode asks for SSE to be disabled, so don't push them
1761         // on the stack.
1762         TotalNumXMMRegs = 0;
1763
1764       // For X86-64, if there are vararg parameters that are passed via
1765       // registers, then we must store them to their spots on the stack so they
1766       // may be loaded by deferencing the result of va_next.
1767       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1768       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1769       FuncInfo->setRegSaveFrameIndex(
1770         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1771                                false));
1772
1773       // Store the integer parameter registers.
1774       SmallVector<SDValue, 8> MemOps;
1775       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1776                                         getPointerTy());
1777       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1778       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1779         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1780                                   DAG.getIntPtrConstant(Offset));
1781         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1782                                      X86::GR64RegisterClass);
1783         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1784         SDValue Store =
1785           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1786                        MachinePointerInfo::getFixedStack(
1787                          FuncInfo->getRegSaveFrameIndex(), Offset),
1788                        false, false, 0);
1789         MemOps.push_back(Store);
1790         Offset += 8;
1791       }
1792
1793       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1794         // Now store the XMM (fp + vector) parameter registers.
1795         SmallVector<SDValue, 11> SaveXMMOps;
1796         SaveXMMOps.push_back(Chain);
1797
1798         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1799         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1800         SaveXMMOps.push_back(ALVal);
1801
1802         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1803                                FuncInfo->getRegSaveFrameIndex()));
1804         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1805                                FuncInfo->getVarArgsFPOffset()));
1806
1807         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1808           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1809                                        X86::VR128RegisterClass);
1810           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1811           SaveXMMOps.push_back(Val);
1812         }
1813         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1814                                      MVT::Other,
1815                                      &SaveXMMOps[0], SaveXMMOps.size()));
1816       }
1817
1818       if (!MemOps.empty())
1819         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1820                             &MemOps[0], MemOps.size());
1821     }
1822   }
1823
1824   // Some CCs need callee pop.
1825   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1826     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1827   } else {
1828     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1829     // If this is an sret function, the return should pop the hidden pointer.
1830     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1831       FuncInfo->setBytesToPopOnReturn(4);
1832   }
1833
1834   if (!Is64Bit) {
1835     // RegSaveFrameIndex is X86-64 only.
1836     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1837     if (CallConv == CallingConv::X86_FastCall ||
1838         CallConv == CallingConv::X86_ThisCall)
1839       // fastcc functions can't have varargs.
1840       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1841   }
1842
1843   return Chain;
1844 }
1845
1846 SDValue
1847 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1848                                     SDValue StackPtr, SDValue Arg,
1849                                     DebugLoc dl, SelectionDAG &DAG,
1850                                     const CCValAssign &VA,
1851                                     ISD::ArgFlagsTy Flags) const {
1852   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1853   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1854   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1855   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1856   if (Flags.isByVal())
1857     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1858
1859   return DAG.getStore(Chain, dl, Arg, PtrOff,
1860                       MachinePointerInfo::getStack(LocMemOffset),
1861                       false, false, 0);
1862 }
1863
1864 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1865 /// optimization is performed and it is required.
1866 SDValue
1867 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1868                                            SDValue &OutRetAddr, SDValue Chain,
1869                                            bool IsTailCall, bool Is64Bit,
1870                                            int FPDiff, DebugLoc dl) const {
1871   // Adjust the Return address stack slot.
1872   EVT VT = getPointerTy();
1873   OutRetAddr = getReturnAddressFrameIndex(DAG);
1874
1875   // Load the "old" Return address.
1876   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1877                            false, false, 0);
1878   return SDValue(OutRetAddr.getNode(), 1);
1879 }
1880
1881 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1882 /// optimization is performed and it is required (FPDiff!=0).
1883 static SDValue
1884 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1885                          SDValue Chain, SDValue RetAddrFrIdx,
1886                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1887   // Store the return address to the appropriate stack slot.
1888   if (!FPDiff) return Chain;
1889   // Calculate the new stack slot for the return address.
1890   int SlotSize = Is64Bit ? 8 : 4;
1891   int NewReturnAddrFI =
1892     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1893   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1894   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1895   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1896                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1897                        false, false, 0);
1898   return Chain;
1899 }
1900
1901 SDValue
1902 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1903                              CallingConv::ID CallConv, bool isVarArg,
1904                              bool &isTailCall,
1905                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1906                              const SmallVectorImpl<SDValue> &OutVals,
1907                              const SmallVectorImpl<ISD::InputArg> &Ins,
1908                              DebugLoc dl, SelectionDAG &DAG,
1909                              SmallVectorImpl<SDValue> &InVals) const {
1910   MachineFunction &MF = DAG.getMachineFunction();
1911   bool Is64Bit        = Subtarget->is64Bit();
1912   bool IsStructRet    = CallIsStructReturn(Outs);
1913   bool IsSibcall      = false;
1914
1915   if (isTailCall) {
1916     // Check if it's really possible to do a tail call.
1917     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1918                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1919                                                    Outs, OutVals, Ins, DAG);
1920
1921     // Sibcalls are automatically detected tailcalls which do not require
1922     // ABI changes.
1923     if (!GuaranteedTailCallOpt && isTailCall)
1924       IsSibcall = true;
1925
1926     if (isTailCall)
1927       ++NumTailCalls;
1928   }
1929
1930   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1931          "Var args not supported with calling convention fastcc or ghc");
1932
1933   // Analyze operands of the call, assigning locations to each operand.
1934   SmallVector<CCValAssign, 16> ArgLocs;
1935   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1936                  ArgLocs, *DAG.getContext());
1937   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1938
1939   // Get a count of how many bytes are to be pushed on the stack.
1940   unsigned NumBytes = CCInfo.getNextStackOffset();
1941   if (IsSibcall)
1942     // This is a sibcall. The memory operands are available in caller's
1943     // own caller's stack.
1944     NumBytes = 0;
1945   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1946     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1947
1948   int FPDiff = 0;
1949   if (isTailCall && !IsSibcall) {
1950     // Lower arguments at fp - stackoffset + fpdiff.
1951     unsigned NumBytesCallerPushed =
1952       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1953     FPDiff = NumBytesCallerPushed - NumBytes;
1954
1955     // Set the delta of movement of the returnaddr stackslot.
1956     // But only set if delta is greater than previous delta.
1957     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1958       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1959   }
1960
1961   if (!IsSibcall)
1962     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1963
1964   SDValue RetAddrFrIdx;
1965   // Load return adress for tail calls.
1966   if (isTailCall && FPDiff)
1967     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1968                                     Is64Bit, FPDiff, dl);
1969
1970   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1971   SmallVector<SDValue, 8> MemOpChains;
1972   SDValue StackPtr;
1973
1974   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1975   // of tail call optimization arguments are handle later.
1976   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1977     CCValAssign &VA = ArgLocs[i];
1978     EVT RegVT = VA.getLocVT();
1979     SDValue Arg = OutVals[i];
1980     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1981     bool isByVal = Flags.isByVal();
1982
1983     // Promote the value if needed.
1984     switch (VA.getLocInfo()) {
1985     default: llvm_unreachable("Unknown loc info!");
1986     case CCValAssign::Full: break;
1987     case CCValAssign::SExt:
1988       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1989       break;
1990     case CCValAssign::ZExt:
1991       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1992       break;
1993     case CCValAssign::AExt:
1994       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1995         // Special case: passing MMX values in XMM registers.
1996         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1997         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1998         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1999       } else
2000         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2001       break;
2002     case CCValAssign::BCvt:
2003       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
2004       break;
2005     case CCValAssign::Indirect: {
2006       // Store the argument.
2007       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2008       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2009       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2010                            MachinePointerInfo::getFixedStack(FI),
2011                            false, false, 0);
2012       Arg = SpillSlot;
2013       break;
2014     }
2015     }
2016
2017     if (VA.isRegLoc()) {
2018       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2019       if (isVarArg && Subtarget->isTargetWin64()) {
2020         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2021         // shadow reg if callee is a varargs function.
2022         unsigned ShadowReg = 0;
2023         switch (VA.getLocReg()) {
2024         case X86::XMM0: ShadowReg = X86::RCX; break;
2025         case X86::XMM1: ShadowReg = X86::RDX; break;
2026         case X86::XMM2: ShadowReg = X86::R8; break;
2027         case X86::XMM3: ShadowReg = X86::R9; break;
2028         }
2029         if (ShadowReg)
2030           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2031       }
2032     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2033       assert(VA.isMemLoc());
2034       if (StackPtr.getNode() == 0)
2035         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2036       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2037                                              dl, DAG, VA, Flags));
2038     }
2039   }
2040
2041   if (!MemOpChains.empty())
2042     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2043                         &MemOpChains[0], MemOpChains.size());
2044
2045   // Build a sequence of copy-to-reg nodes chained together with token chain
2046   // and flag operands which copy the outgoing args into registers.
2047   SDValue InFlag;
2048   // Tail call byval lowering might overwrite argument registers so in case of
2049   // tail call optimization the copies to registers are lowered later.
2050   if (!isTailCall)
2051     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2052       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2053                                RegsToPass[i].second, InFlag);
2054       InFlag = Chain.getValue(1);
2055     }
2056
2057   if (Subtarget->isPICStyleGOT()) {
2058     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2059     // GOT pointer.
2060     if (!isTailCall) {
2061       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2062                                DAG.getNode(X86ISD::GlobalBaseReg,
2063                                            DebugLoc(), getPointerTy()),
2064                                InFlag);
2065       InFlag = Chain.getValue(1);
2066     } else {
2067       // If we are tail calling and generating PIC/GOT style code load the
2068       // address of the callee into ECX. The value in ecx is used as target of
2069       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2070       // for tail calls on PIC/GOT architectures. Normally we would just put the
2071       // address of GOT into ebx and then call target@PLT. But for tail calls
2072       // ebx would be restored (since ebx is callee saved) before jumping to the
2073       // target@PLT.
2074
2075       // Note: The actual moving to ECX is done further down.
2076       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2077       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2078           !G->getGlobal()->hasProtectedVisibility())
2079         Callee = LowerGlobalAddress(Callee, DAG);
2080       else if (isa<ExternalSymbolSDNode>(Callee))
2081         Callee = LowerExternalSymbol(Callee, DAG);
2082     }
2083   }
2084
2085   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2086     // From AMD64 ABI document:
2087     // For calls that may call functions that use varargs or stdargs
2088     // (prototype-less calls or calls to functions containing ellipsis (...) in
2089     // the declaration) %al is used as hidden argument to specify the number
2090     // of SSE registers used. The contents of %al do not need to match exactly
2091     // the number of registers, but must be an ubound on the number of SSE
2092     // registers used and is in the range 0 - 8 inclusive.
2093
2094     // Count the number of XMM registers allocated.
2095     static const unsigned XMMArgRegs[] = {
2096       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2097       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2098     };
2099     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2100     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2101            && "SSE registers cannot be used when SSE is disabled");
2102
2103     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2104                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2105     InFlag = Chain.getValue(1);
2106   }
2107
2108
2109   // For tail calls lower the arguments to the 'real' stack slot.
2110   if (isTailCall) {
2111     // Force all the incoming stack arguments to be loaded from the stack
2112     // before any new outgoing arguments are stored to the stack, because the
2113     // outgoing stack slots may alias the incoming argument stack slots, and
2114     // the alias isn't otherwise explicit. This is slightly more conservative
2115     // than necessary, because it means that each store effectively depends
2116     // on every argument instead of just those arguments it would clobber.
2117     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2118
2119     SmallVector<SDValue, 8> MemOpChains2;
2120     SDValue FIN;
2121     int FI = 0;
2122     // Do not flag preceeding copytoreg stuff together with the following stuff.
2123     InFlag = SDValue();
2124     if (GuaranteedTailCallOpt) {
2125       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2126         CCValAssign &VA = ArgLocs[i];
2127         if (VA.isRegLoc())
2128           continue;
2129         assert(VA.isMemLoc());
2130         SDValue Arg = OutVals[i];
2131         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2132         // Create frame index.
2133         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2134         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2135         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2136         FIN = DAG.getFrameIndex(FI, getPointerTy());
2137
2138         if (Flags.isByVal()) {
2139           // Copy relative to framepointer.
2140           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2141           if (StackPtr.getNode() == 0)
2142             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2143                                           getPointerTy());
2144           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2145
2146           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2147                                                            ArgChain,
2148                                                            Flags, DAG, dl));
2149         } else {
2150           // Store relative to framepointer.
2151           MemOpChains2.push_back(
2152             DAG.getStore(ArgChain, dl, Arg, FIN,
2153                          MachinePointerInfo::getFixedStack(FI),
2154                          false, false, 0));
2155         }
2156       }
2157     }
2158
2159     if (!MemOpChains2.empty())
2160       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2161                           &MemOpChains2[0], MemOpChains2.size());
2162
2163     // Copy arguments to their registers.
2164     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2165       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2166                                RegsToPass[i].second, InFlag);
2167       InFlag = Chain.getValue(1);
2168     }
2169     InFlag =SDValue();
2170
2171     // Store the return address to the appropriate stack slot.
2172     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2173                                      FPDiff, dl);
2174   }
2175
2176   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2177     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2178     // In the 64-bit large code model, we have to make all calls
2179     // through a register, since the call instruction's 32-bit
2180     // pc-relative offset may not be large enough to hold the whole
2181     // address.
2182   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2183     // If the callee is a GlobalAddress node (quite common, every direct call
2184     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2185     // it.
2186
2187     // We should use extra load for direct calls to dllimported functions in
2188     // non-JIT mode.
2189     const GlobalValue *GV = G->getGlobal();
2190     if (!GV->hasDLLImportLinkage()) {
2191       unsigned char OpFlags = 0;
2192
2193       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2194       // external symbols most go through the PLT in PIC mode.  If the symbol
2195       // has hidden or protected visibility, or if it is static or local, then
2196       // we don't need to use the PLT - we can directly call it.
2197       if (Subtarget->isTargetELF() &&
2198           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2199           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2200         OpFlags = X86II::MO_PLT;
2201       } else if (Subtarget->isPICStyleStubAny() &&
2202                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2203                Subtarget->getDarwinVers() < 9) {
2204         // PC-relative references to external symbols should go through $stub,
2205         // unless we're building with the leopard linker or later, which
2206         // automatically synthesizes these stubs.
2207         OpFlags = X86II::MO_DARWIN_STUB;
2208       }
2209
2210       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2211                                           G->getOffset(), OpFlags);
2212     }
2213   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2214     unsigned char OpFlags = 0;
2215
2216     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2217     // symbols should go through the PLT.
2218     if (Subtarget->isTargetELF() &&
2219         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2220       OpFlags = X86II::MO_PLT;
2221     } else if (Subtarget->isPICStyleStubAny() &&
2222              Subtarget->getDarwinVers() < 9) {
2223       // PC-relative references to external symbols should go through $stub,
2224       // unless we're building with the leopard linker or later, which
2225       // automatically synthesizes these stubs.
2226       OpFlags = X86II::MO_DARWIN_STUB;
2227     }
2228
2229     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2230                                          OpFlags);
2231   }
2232
2233   // Returns a chain & a flag for retval copy to use.
2234   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2235   SmallVector<SDValue, 8> Ops;
2236
2237   if (!IsSibcall && isTailCall) {
2238     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2239                            DAG.getIntPtrConstant(0, true), InFlag);
2240     InFlag = Chain.getValue(1);
2241   }
2242
2243   Ops.push_back(Chain);
2244   Ops.push_back(Callee);
2245
2246   if (isTailCall)
2247     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2248
2249   // Add argument registers to the end of the list so that they are known live
2250   // into the call.
2251   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2252     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2253                                   RegsToPass[i].second.getValueType()));
2254
2255   // Add an implicit use GOT pointer in EBX.
2256   if (!isTailCall && Subtarget->isPICStyleGOT())
2257     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2258
2259   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2260   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2261     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2262
2263   if (InFlag.getNode())
2264     Ops.push_back(InFlag);
2265
2266   if (isTailCall) {
2267     // We used to do:
2268     //// If this is the first return lowered for this function, add the regs
2269     //// to the liveout set for the function.
2270     // This isn't right, although it's probably harmless on x86; liveouts
2271     // should be computed from returns not tail calls.  Consider a void
2272     // function making a tail call to a function returning int.
2273     return DAG.getNode(X86ISD::TC_RETURN, dl,
2274                        NodeTys, &Ops[0], Ops.size());
2275   }
2276
2277   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2278   InFlag = Chain.getValue(1);
2279
2280   // Create the CALLSEQ_END node.
2281   unsigned NumBytesForCalleeToPush;
2282   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2283     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2284   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2285     // If this is a call to a struct-return function, the callee
2286     // pops the hidden struct pointer, so we have to push it back.
2287     // This is common for Darwin/X86, Linux & Mingw32 targets.
2288     NumBytesForCalleeToPush = 4;
2289   else
2290     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2291
2292   // Returns a flag for retval copy to use.
2293   if (!IsSibcall) {
2294     Chain = DAG.getCALLSEQ_END(Chain,
2295                                DAG.getIntPtrConstant(NumBytes, true),
2296                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2297                                                      true),
2298                                InFlag);
2299     InFlag = Chain.getValue(1);
2300   }
2301
2302   // Handle result values, copying them out of physregs into vregs that we
2303   // return.
2304   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2305                          Ins, dl, DAG, InVals);
2306 }
2307
2308
2309 //===----------------------------------------------------------------------===//
2310 //                Fast Calling Convention (tail call) implementation
2311 //===----------------------------------------------------------------------===//
2312
2313 //  Like std call, callee cleans arguments, convention except that ECX is
2314 //  reserved for storing the tail called function address. Only 2 registers are
2315 //  free for argument passing (inreg). Tail call optimization is performed
2316 //  provided:
2317 //                * tailcallopt is enabled
2318 //                * caller/callee are fastcc
2319 //  On X86_64 architecture with GOT-style position independent code only local
2320 //  (within module) calls are supported at the moment.
2321 //  To keep the stack aligned according to platform abi the function
2322 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2323 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2324 //  If a tail called function callee has more arguments than the caller the
2325 //  caller needs to make sure that there is room to move the RETADDR to. This is
2326 //  achieved by reserving an area the size of the argument delta right after the
2327 //  original REtADDR, but before the saved framepointer or the spilled registers
2328 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2329 //  stack layout:
2330 //    arg1
2331 //    arg2
2332 //    RETADDR
2333 //    [ new RETADDR
2334 //      move area ]
2335 //    (possible EBP)
2336 //    ESI
2337 //    EDI
2338 //    local1 ..
2339
2340 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2341 /// for a 16 byte align requirement.
2342 unsigned
2343 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2344                                                SelectionDAG& DAG) const {
2345   MachineFunction &MF = DAG.getMachineFunction();
2346   const TargetMachine &TM = MF.getTarget();
2347   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2348   unsigned StackAlignment = TFI.getStackAlignment();
2349   uint64_t AlignMask = StackAlignment - 1;
2350   int64_t Offset = StackSize;
2351   uint64_t SlotSize = TD->getPointerSize();
2352   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2353     // Number smaller than 12 so just add the difference.
2354     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2355   } else {
2356     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2357     Offset = ((~AlignMask) & Offset) + StackAlignment +
2358       (StackAlignment-SlotSize);
2359   }
2360   return Offset;
2361 }
2362
2363 /// MatchingStackOffset - Return true if the given stack call argument is
2364 /// already available in the same position (relatively) of the caller's
2365 /// incoming argument stack.
2366 static
2367 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2368                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2369                          const X86InstrInfo *TII) {
2370   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2371   int FI = INT_MAX;
2372   if (Arg.getOpcode() == ISD::CopyFromReg) {
2373     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2374     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2375       return false;
2376     MachineInstr *Def = MRI->getVRegDef(VR);
2377     if (!Def)
2378       return false;
2379     if (!Flags.isByVal()) {
2380       if (!TII->isLoadFromStackSlot(Def, FI))
2381         return false;
2382     } else {
2383       unsigned Opcode = Def->getOpcode();
2384       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2385           Def->getOperand(1).isFI()) {
2386         FI = Def->getOperand(1).getIndex();
2387         Bytes = Flags.getByValSize();
2388       } else
2389         return false;
2390     }
2391   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2392     if (Flags.isByVal())
2393       // ByVal argument is passed in as a pointer but it's now being
2394       // dereferenced. e.g.
2395       // define @foo(%struct.X* %A) {
2396       //   tail call @bar(%struct.X* byval %A)
2397       // }
2398       return false;
2399     SDValue Ptr = Ld->getBasePtr();
2400     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2401     if (!FINode)
2402       return false;
2403     FI = FINode->getIndex();
2404   } else
2405     return false;
2406
2407   assert(FI != INT_MAX);
2408   if (!MFI->isFixedObjectIndex(FI))
2409     return false;
2410   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2411 }
2412
2413 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2414 /// for tail call optimization. Targets which want to do tail call
2415 /// optimization should implement this function.
2416 bool
2417 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2418                                                      CallingConv::ID CalleeCC,
2419                                                      bool isVarArg,
2420                                                      bool isCalleeStructRet,
2421                                                      bool isCallerStructRet,
2422                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2423                                     const SmallVectorImpl<SDValue> &OutVals,
2424                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2425                                                      SelectionDAG& DAG) const {
2426   if (!IsTailCallConvention(CalleeCC) &&
2427       CalleeCC != CallingConv::C)
2428     return false;
2429
2430   // If -tailcallopt is specified, make fastcc functions tail-callable.
2431   const MachineFunction &MF = DAG.getMachineFunction();
2432   const Function *CallerF = DAG.getMachineFunction().getFunction();
2433   CallingConv::ID CallerCC = CallerF->getCallingConv();
2434   bool CCMatch = CallerCC == CalleeCC;
2435
2436   if (GuaranteedTailCallOpt) {
2437     if (IsTailCallConvention(CalleeCC) && CCMatch)
2438       return true;
2439     return false;
2440   }
2441
2442   // Look for obvious safe cases to perform tail call optimization that do not
2443   // require ABI changes. This is what gcc calls sibcall.
2444
2445   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2446   // emit a special epilogue.
2447   if (RegInfo->needsStackRealignment(MF))
2448     return false;
2449
2450   // Do not sibcall optimize vararg calls unless the call site is not passing
2451   // any arguments.
2452   if (isVarArg && !Outs.empty())
2453     return false;
2454
2455   // Also avoid sibcall optimization if either caller or callee uses struct
2456   // return semantics.
2457   if (isCalleeStructRet || isCallerStructRet)
2458     return false;
2459
2460   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2461   // Therefore if it's not used by the call it is not safe to optimize this into
2462   // a sibcall.
2463   bool Unused = false;
2464   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2465     if (!Ins[i].Used) {
2466       Unused = true;
2467       break;
2468     }
2469   }
2470   if (Unused) {
2471     SmallVector<CCValAssign, 16> RVLocs;
2472     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2473                    RVLocs, *DAG.getContext());
2474     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2475     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2476       CCValAssign &VA = RVLocs[i];
2477       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2478         return false;
2479     }
2480   }
2481
2482   // If the calling conventions do not match, then we'd better make sure the
2483   // results are returned in the same way as what the caller expects.
2484   if (!CCMatch) {
2485     SmallVector<CCValAssign, 16> RVLocs1;
2486     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2487                     RVLocs1, *DAG.getContext());
2488     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2489
2490     SmallVector<CCValAssign, 16> RVLocs2;
2491     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2492                     RVLocs2, *DAG.getContext());
2493     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2494
2495     if (RVLocs1.size() != RVLocs2.size())
2496       return false;
2497     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2498       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2499         return false;
2500       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2501         return false;
2502       if (RVLocs1[i].isRegLoc()) {
2503         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2504           return false;
2505       } else {
2506         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2507           return false;
2508       }
2509     }
2510   }
2511
2512   // If the callee takes no arguments then go on to check the results of the
2513   // call.
2514   if (!Outs.empty()) {
2515     // Check if stack adjustment is needed. For now, do not do this if any
2516     // argument is passed on the stack.
2517     SmallVector<CCValAssign, 16> ArgLocs;
2518     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2519                    ArgLocs, *DAG.getContext());
2520     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2521     if (CCInfo.getNextStackOffset()) {
2522       MachineFunction &MF = DAG.getMachineFunction();
2523       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2524         return false;
2525       if (Subtarget->isTargetWin64())
2526         // Win64 ABI has additional complications.
2527         return false;
2528
2529       // Check if the arguments are already laid out in the right way as
2530       // the caller's fixed stack objects.
2531       MachineFrameInfo *MFI = MF.getFrameInfo();
2532       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2533       const X86InstrInfo *TII =
2534         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2535       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2536         CCValAssign &VA = ArgLocs[i];
2537         SDValue Arg = OutVals[i];
2538         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2539         if (VA.getLocInfo() == CCValAssign::Indirect)
2540           return false;
2541         if (!VA.isRegLoc()) {
2542           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2543                                    MFI, MRI, TII))
2544             return false;
2545         }
2546       }
2547     }
2548
2549     // If the tailcall address may be in a register, then make sure it's
2550     // possible to register allocate for it. In 32-bit, the call address can
2551     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2552     // callee-saved registers are restored. These happen to be the same
2553     // registers used to pass 'inreg' arguments so watch out for those.
2554     if (!Subtarget->is64Bit() &&
2555         !isa<GlobalAddressSDNode>(Callee) &&
2556         !isa<ExternalSymbolSDNode>(Callee)) {
2557       unsigned NumInRegs = 0;
2558       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2559         CCValAssign &VA = ArgLocs[i];
2560         if (!VA.isRegLoc())
2561           continue;
2562         unsigned Reg = VA.getLocReg();
2563         switch (Reg) {
2564         default: break;
2565         case X86::EAX: case X86::EDX: case X86::ECX:
2566           if (++NumInRegs == 3)
2567             return false;
2568           break;
2569         }
2570       }
2571     }
2572   }
2573
2574   return true;
2575 }
2576
2577 FastISel *
2578 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2579   return X86::createFastISel(funcInfo);
2580 }
2581
2582
2583 //===----------------------------------------------------------------------===//
2584 //                           Other Lowering Hooks
2585 //===----------------------------------------------------------------------===//
2586
2587 static bool MayFoldLoad(SDValue Op) {
2588   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2589 }
2590
2591 static bool MayFoldIntoStore(SDValue Op) {
2592   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2593 }
2594
2595 static bool isTargetShuffle(unsigned Opcode) {
2596   switch(Opcode) {
2597   default: return false;
2598   case X86ISD::PSHUFD:
2599   case X86ISD::PSHUFHW:
2600   case X86ISD::PSHUFLW:
2601   case X86ISD::SHUFPD:
2602   case X86ISD::PALIGN:
2603   case X86ISD::SHUFPS:
2604   case X86ISD::MOVLHPS:
2605   case X86ISD::MOVLHPD:
2606   case X86ISD::MOVHLPS:
2607   case X86ISD::MOVLPS:
2608   case X86ISD::MOVLPD:
2609   case X86ISD::MOVSHDUP:
2610   case X86ISD::MOVSLDUP:
2611   case X86ISD::MOVDDUP:
2612   case X86ISD::MOVSS:
2613   case X86ISD::MOVSD:
2614   case X86ISD::UNPCKLPS:
2615   case X86ISD::UNPCKLPD:
2616   case X86ISD::PUNPCKLWD:
2617   case X86ISD::PUNPCKLBW:
2618   case X86ISD::PUNPCKLDQ:
2619   case X86ISD::PUNPCKLQDQ:
2620   case X86ISD::UNPCKHPS:
2621   case X86ISD::UNPCKHPD:
2622   case X86ISD::PUNPCKHWD:
2623   case X86ISD::PUNPCKHBW:
2624   case X86ISD::PUNPCKHDQ:
2625   case X86ISD::PUNPCKHQDQ:
2626     return true;
2627   }
2628   return false;
2629 }
2630
2631 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2632                                                SDValue V1, SelectionDAG &DAG) {
2633   switch(Opc) {
2634   default: llvm_unreachable("Unknown x86 shuffle node");
2635   case X86ISD::MOVSHDUP:
2636   case X86ISD::MOVSLDUP:
2637   case X86ISD::MOVDDUP:
2638     return DAG.getNode(Opc, dl, VT, V1);
2639   }
2640
2641   return SDValue();
2642 }
2643
2644 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2645                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2646   switch(Opc) {
2647   default: llvm_unreachable("Unknown x86 shuffle node");
2648   case X86ISD::PSHUFD:
2649   case X86ISD::PSHUFHW:
2650   case X86ISD::PSHUFLW:
2651     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2652   }
2653
2654   return SDValue();
2655 }
2656
2657 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2658                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2659   switch(Opc) {
2660   default: llvm_unreachable("Unknown x86 shuffle node");
2661   case X86ISD::PALIGN:
2662   case X86ISD::SHUFPD:
2663   case X86ISD::SHUFPS:
2664     return DAG.getNode(Opc, dl, VT, V1, V2,
2665                        DAG.getConstant(TargetMask, MVT::i8));
2666   }
2667   return SDValue();
2668 }
2669
2670 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2671                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2672   switch(Opc) {
2673   default: llvm_unreachable("Unknown x86 shuffle node");
2674   case X86ISD::MOVLHPS:
2675   case X86ISD::MOVLHPD:
2676   case X86ISD::MOVHLPS:
2677   case X86ISD::MOVLPS:
2678   case X86ISD::MOVLPD:
2679   case X86ISD::MOVSS:
2680   case X86ISD::MOVSD:
2681   case X86ISD::UNPCKLPS:
2682   case X86ISD::UNPCKLPD:
2683   case X86ISD::PUNPCKLWD:
2684   case X86ISD::PUNPCKLBW:
2685   case X86ISD::PUNPCKLDQ:
2686   case X86ISD::PUNPCKLQDQ:
2687   case X86ISD::UNPCKHPS:
2688   case X86ISD::UNPCKHPD:
2689   case X86ISD::PUNPCKHWD:
2690   case X86ISD::PUNPCKHBW:
2691   case X86ISD::PUNPCKHDQ:
2692   case X86ISD::PUNPCKHQDQ:
2693     return DAG.getNode(Opc, dl, VT, V1, V2);
2694   }
2695   return SDValue();
2696 }
2697
2698 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2699   MachineFunction &MF = DAG.getMachineFunction();
2700   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2701   int ReturnAddrIndex = FuncInfo->getRAIndex();
2702
2703   if (ReturnAddrIndex == 0) {
2704     // Set up a frame object for the return address.
2705     uint64_t SlotSize = TD->getPointerSize();
2706     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2707                                                            false);
2708     FuncInfo->setRAIndex(ReturnAddrIndex);
2709   }
2710
2711   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2712 }
2713
2714
2715 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2716                                        bool hasSymbolicDisplacement) {
2717   // Offset should fit into 32 bit immediate field.
2718   if (!isInt<32>(Offset))
2719     return false;
2720
2721   // If we don't have a symbolic displacement - we don't have any extra
2722   // restrictions.
2723   if (!hasSymbolicDisplacement)
2724     return true;
2725
2726   // FIXME: Some tweaks might be needed for medium code model.
2727   if (M != CodeModel::Small && M != CodeModel::Kernel)
2728     return false;
2729
2730   // For small code model we assume that latest object is 16MB before end of 31
2731   // bits boundary. We may also accept pretty large negative constants knowing
2732   // that all objects are in the positive half of address space.
2733   if (M == CodeModel::Small && Offset < 16*1024*1024)
2734     return true;
2735
2736   // For kernel code model we know that all object resist in the negative half
2737   // of 32bits address space. We may not accept negative offsets, since they may
2738   // be just off and we may accept pretty large positive ones.
2739   if (M == CodeModel::Kernel && Offset > 0)
2740     return true;
2741
2742   return false;
2743 }
2744
2745 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2746 /// specific condition code, returning the condition code and the LHS/RHS of the
2747 /// comparison to make.
2748 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2749                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2750   if (!isFP) {
2751     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2752       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2753         // X > -1   -> X == 0, jump !sign.
2754         RHS = DAG.getConstant(0, RHS.getValueType());
2755         return X86::COND_NS;
2756       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2757         // X < 0   -> X == 0, jump on sign.
2758         return X86::COND_S;
2759       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2760         // X < 1   -> X <= 0
2761         RHS = DAG.getConstant(0, RHS.getValueType());
2762         return X86::COND_LE;
2763       }
2764     }
2765
2766     switch (SetCCOpcode) {
2767     default: llvm_unreachable("Invalid integer condition!");
2768     case ISD::SETEQ:  return X86::COND_E;
2769     case ISD::SETGT:  return X86::COND_G;
2770     case ISD::SETGE:  return X86::COND_GE;
2771     case ISD::SETLT:  return X86::COND_L;
2772     case ISD::SETLE:  return X86::COND_LE;
2773     case ISD::SETNE:  return X86::COND_NE;
2774     case ISD::SETULT: return X86::COND_B;
2775     case ISD::SETUGT: return X86::COND_A;
2776     case ISD::SETULE: return X86::COND_BE;
2777     case ISD::SETUGE: return X86::COND_AE;
2778     }
2779   }
2780
2781   // First determine if it is required or is profitable to flip the operands.
2782
2783   // If LHS is a foldable load, but RHS is not, flip the condition.
2784   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2785       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2786     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2787     std::swap(LHS, RHS);
2788   }
2789
2790   switch (SetCCOpcode) {
2791   default: break;
2792   case ISD::SETOLT:
2793   case ISD::SETOLE:
2794   case ISD::SETUGT:
2795   case ISD::SETUGE:
2796     std::swap(LHS, RHS);
2797     break;
2798   }
2799
2800   // On a floating point condition, the flags are set as follows:
2801   // ZF  PF  CF   op
2802   //  0 | 0 | 0 | X > Y
2803   //  0 | 0 | 1 | X < Y
2804   //  1 | 0 | 0 | X == Y
2805   //  1 | 1 | 1 | unordered
2806   switch (SetCCOpcode) {
2807   default: llvm_unreachable("Condcode should be pre-legalized away");
2808   case ISD::SETUEQ:
2809   case ISD::SETEQ:   return X86::COND_E;
2810   case ISD::SETOLT:              // flipped
2811   case ISD::SETOGT:
2812   case ISD::SETGT:   return X86::COND_A;
2813   case ISD::SETOLE:              // flipped
2814   case ISD::SETOGE:
2815   case ISD::SETGE:   return X86::COND_AE;
2816   case ISD::SETUGT:              // flipped
2817   case ISD::SETULT:
2818   case ISD::SETLT:   return X86::COND_B;
2819   case ISD::SETUGE:              // flipped
2820   case ISD::SETULE:
2821   case ISD::SETLE:   return X86::COND_BE;
2822   case ISD::SETONE:
2823   case ISD::SETNE:   return X86::COND_NE;
2824   case ISD::SETUO:   return X86::COND_P;
2825   case ISD::SETO:    return X86::COND_NP;
2826   case ISD::SETOEQ:
2827   case ISD::SETUNE:  return X86::COND_INVALID;
2828   }
2829 }
2830
2831 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2832 /// code. Current x86 isa includes the following FP cmov instructions:
2833 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2834 static bool hasFPCMov(unsigned X86CC) {
2835   switch (X86CC) {
2836   default:
2837     return false;
2838   case X86::COND_B:
2839   case X86::COND_BE:
2840   case X86::COND_E:
2841   case X86::COND_P:
2842   case X86::COND_A:
2843   case X86::COND_AE:
2844   case X86::COND_NE:
2845   case X86::COND_NP:
2846     return true;
2847   }
2848 }
2849
2850 /// isFPImmLegal - Returns true if the target can instruction select the
2851 /// specified FP immediate natively. If false, the legalizer will
2852 /// materialize the FP immediate as a load from a constant pool.
2853 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2854   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2855     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2856       return true;
2857   }
2858   return false;
2859 }
2860
2861 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2862 /// the specified range (L, H].
2863 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2864   return (Val < 0) || (Val >= Low && Val < Hi);
2865 }
2866
2867 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2868 /// specified value.
2869 static bool isUndefOrEqual(int Val, int CmpVal) {
2870   if (Val < 0 || Val == CmpVal)
2871     return true;
2872   return false;
2873 }
2874
2875 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2876 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2877 /// the second operand.
2878 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2879   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2880     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2881   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2882     return (Mask[0] < 2 && Mask[1] < 2);
2883   return false;
2884 }
2885
2886 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2887   SmallVector<int, 8> M;
2888   N->getMask(M);
2889   return ::isPSHUFDMask(M, N->getValueType(0));
2890 }
2891
2892 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2893 /// is suitable for input to PSHUFHW.
2894 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2895   if (VT != MVT::v8i16)
2896     return false;
2897
2898   // Lower quadword copied in order or undef.
2899   for (int i = 0; i != 4; ++i)
2900     if (Mask[i] >= 0 && Mask[i] != i)
2901       return false;
2902
2903   // Upper quadword shuffled.
2904   for (int i = 4; i != 8; ++i)
2905     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2906       return false;
2907
2908   return true;
2909 }
2910
2911 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2912   SmallVector<int, 8> M;
2913   N->getMask(M);
2914   return ::isPSHUFHWMask(M, N->getValueType(0));
2915 }
2916
2917 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2918 /// is suitable for input to PSHUFLW.
2919 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2920   if (VT != MVT::v8i16)
2921     return false;
2922
2923   // Upper quadword copied in order.
2924   for (int i = 4; i != 8; ++i)
2925     if (Mask[i] >= 0 && Mask[i] != i)
2926       return false;
2927
2928   // Lower quadword shuffled.
2929   for (int i = 0; i != 4; ++i)
2930     if (Mask[i] >= 4)
2931       return false;
2932
2933   return true;
2934 }
2935
2936 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2937   SmallVector<int, 8> M;
2938   N->getMask(M);
2939   return ::isPSHUFLWMask(M, N->getValueType(0));
2940 }
2941
2942 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2943 /// is suitable for input to PALIGNR.
2944 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2945                           bool hasSSSE3) {
2946   int i, e = VT.getVectorNumElements();
2947   
2948   // Do not handle v2i64 / v2f64 shuffles with palignr.
2949   if (e < 4 || !hasSSSE3)
2950     return false;
2951   
2952   for (i = 0; i != e; ++i)
2953     if (Mask[i] >= 0)
2954       break;
2955   
2956   // All undef, not a palignr.
2957   if (i == e)
2958     return false;
2959
2960   // Determine if it's ok to perform a palignr with only the LHS, since we
2961   // don't have access to the actual shuffle elements to see if RHS is undef.
2962   bool Unary = Mask[i] < (int)e;
2963   bool NeedsUnary = false;
2964
2965   int s = Mask[i] - i;
2966   
2967   // Check the rest of the elements to see if they are consecutive.
2968   for (++i; i != e; ++i) {
2969     int m = Mask[i];
2970     if (m < 0) 
2971       continue;
2972     
2973     Unary = Unary && (m < (int)e);
2974     NeedsUnary = NeedsUnary || (m < s);
2975
2976     if (NeedsUnary && !Unary)
2977       return false;
2978     if (Unary && m != ((s+i) & (e-1)))
2979       return false;
2980     if (!Unary && m != (s+i))
2981       return false;
2982   }
2983   return true;
2984 }
2985
2986 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2987   SmallVector<int, 8> M;
2988   N->getMask(M);
2989   return ::isPALIGNRMask(M, N->getValueType(0), true);
2990 }
2991
2992 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2993 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2994 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2995   int NumElems = VT.getVectorNumElements();
2996   if (NumElems != 2 && NumElems != 4)
2997     return false;
2998
2999   int Half = NumElems / 2;
3000   for (int i = 0; i < Half; ++i)
3001     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3002       return false;
3003   for (int i = Half; i < NumElems; ++i)
3004     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3005       return false;
3006
3007   return true;
3008 }
3009
3010 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3011   SmallVector<int, 8> M;
3012   N->getMask(M);
3013   return ::isSHUFPMask(M, N->getValueType(0));
3014 }
3015
3016 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3017 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3018 /// half elements to come from vector 1 (which would equal the dest.) and
3019 /// the upper half to come from vector 2.
3020 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3021   int NumElems = VT.getVectorNumElements();
3022
3023   if (NumElems != 2 && NumElems != 4)
3024     return false;
3025
3026   int Half = NumElems / 2;
3027   for (int i = 0; i < Half; ++i)
3028     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3029       return false;
3030   for (int i = Half; i < NumElems; ++i)
3031     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3032       return false;
3033   return true;
3034 }
3035
3036 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3037   SmallVector<int, 8> M;
3038   N->getMask(M);
3039   return isCommutedSHUFPMask(M, N->getValueType(0));
3040 }
3041
3042 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3043 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3044 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3045   if (N->getValueType(0).getVectorNumElements() != 4)
3046     return false;
3047
3048   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3049   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3050          isUndefOrEqual(N->getMaskElt(1), 7) &&
3051          isUndefOrEqual(N->getMaskElt(2), 2) &&
3052          isUndefOrEqual(N->getMaskElt(3), 3);
3053 }
3054
3055 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3056 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3057 /// <2, 3, 2, 3>
3058 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3059   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3060   
3061   if (NumElems != 4)
3062     return false;
3063   
3064   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3065   isUndefOrEqual(N->getMaskElt(1), 3) &&
3066   isUndefOrEqual(N->getMaskElt(2), 2) &&
3067   isUndefOrEqual(N->getMaskElt(3), 3);
3068 }
3069
3070 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3071 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3072 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3073   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3074
3075   if (NumElems != 2 && NumElems != 4)
3076     return false;
3077
3078   for (unsigned i = 0; i < NumElems/2; ++i)
3079     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3080       return false;
3081
3082   for (unsigned i = NumElems/2; i < NumElems; ++i)
3083     if (!isUndefOrEqual(N->getMaskElt(i), i))
3084       return false;
3085
3086   return true;
3087 }
3088
3089 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3090 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3091 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3092   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3093
3094   if (NumElems != 2 && NumElems != 4)
3095     return false;
3096
3097   for (unsigned i = 0; i < NumElems/2; ++i)
3098     if (!isUndefOrEqual(N->getMaskElt(i), i))
3099       return false;
3100
3101   for (unsigned i = 0; i < NumElems/2; ++i)
3102     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3103       return false;
3104
3105   return true;
3106 }
3107
3108 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3109 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3110 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3111                          bool V2IsSplat = false) {
3112   int NumElts = VT.getVectorNumElements();
3113   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3114     return false;
3115
3116   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3117     int BitI  = Mask[i];
3118     int BitI1 = Mask[i+1];
3119     if (!isUndefOrEqual(BitI, j))
3120       return false;
3121     if (V2IsSplat) {
3122       if (!isUndefOrEqual(BitI1, NumElts))
3123         return false;
3124     } else {
3125       if (!isUndefOrEqual(BitI1, j + NumElts))
3126         return false;
3127     }
3128   }
3129   return true;
3130 }
3131
3132 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3133   SmallVector<int, 8> M;
3134   N->getMask(M);
3135   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3136 }
3137
3138 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3139 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3140 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3141                          bool V2IsSplat = false) {
3142   int NumElts = VT.getVectorNumElements();
3143   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3144     return false;
3145
3146   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3147     int BitI  = Mask[i];
3148     int BitI1 = Mask[i+1];
3149     if (!isUndefOrEqual(BitI, j + NumElts/2))
3150       return false;
3151     if (V2IsSplat) {
3152       if (isUndefOrEqual(BitI1, NumElts))
3153         return false;
3154     } else {
3155       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3156         return false;
3157     }
3158   }
3159   return true;
3160 }
3161
3162 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3163   SmallVector<int, 8> M;
3164   N->getMask(M);
3165   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3166 }
3167
3168 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3169 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3170 /// <0, 0, 1, 1>
3171 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3172   int NumElems = VT.getVectorNumElements();
3173   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3174     return false;
3175
3176   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3177     int BitI  = Mask[i];
3178     int BitI1 = Mask[i+1];
3179     if (!isUndefOrEqual(BitI, j))
3180       return false;
3181     if (!isUndefOrEqual(BitI1, j))
3182       return false;
3183   }
3184   return true;
3185 }
3186
3187 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3188   SmallVector<int, 8> M;
3189   N->getMask(M);
3190   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3191 }
3192
3193 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3194 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3195 /// <2, 2, 3, 3>
3196 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3197   int NumElems = VT.getVectorNumElements();
3198   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3199     return false;
3200
3201   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3202     int BitI  = Mask[i];
3203     int BitI1 = Mask[i+1];
3204     if (!isUndefOrEqual(BitI, j))
3205       return false;
3206     if (!isUndefOrEqual(BitI1, j))
3207       return false;
3208   }
3209   return true;
3210 }
3211
3212 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3213   SmallVector<int, 8> M;
3214   N->getMask(M);
3215   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3216 }
3217
3218 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3219 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3220 /// MOVSD, and MOVD, i.e. setting the lowest element.
3221 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3222   if (VT.getVectorElementType().getSizeInBits() < 32)
3223     return false;
3224
3225   int NumElts = VT.getVectorNumElements();
3226
3227   if (!isUndefOrEqual(Mask[0], NumElts))
3228     return false;
3229
3230   for (int i = 1; i < NumElts; ++i)
3231     if (!isUndefOrEqual(Mask[i], i))
3232       return false;
3233
3234   return true;
3235 }
3236
3237 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3238   SmallVector<int, 8> M;
3239   N->getMask(M);
3240   return ::isMOVLMask(M, N->getValueType(0));
3241 }
3242
3243 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3244 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3245 /// element of vector 2 and the other elements to come from vector 1 in order.
3246 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3247                                bool V2IsSplat = false, bool V2IsUndef = false) {
3248   int NumOps = VT.getVectorNumElements();
3249   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3250     return false;
3251
3252   if (!isUndefOrEqual(Mask[0], 0))
3253     return false;
3254
3255   for (int i = 1; i < NumOps; ++i)
3256     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3257           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3258           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3259       return false;
3260
3261   return true;
3262 }
3263
3264 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3265                            bool V2IsUndef = false) {
3266   SmallVector<int, 8> M;
3267   N->getMask(M);
3268   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3269 }
3270
3271 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3272 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3273 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3274   if (N->getValueType(0).getVectorNumElements() != 4)
3275     return false;
3276
3277   // Expect 1, 1, 3, 3
3278   for (unsigned i = 0; i < 2; ++i) {
3279     int Elt = N->getMaskElt(i);
3280     if (Elt >= 0 && Elt != 1)
3281       return false;
3282   }
3283
3284   bool HasHi = false;
3285   for (unsigned i = 2; i < 4; ++i) {
3286     int Elt = N->getMaskElt(i);
3287     if (Elt >= 0 && Elt != 3)
3288       return false;
3289     if (Elt == 3)
3290       HasHi = true;
3291   }
3292   // Don't use movshdup if it can be done with a shufps.
3293   // FIXME: verify that matching u, u, 3, 3 is what we want.
3294   return HasHi;
3295 }
3296
3297 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3298 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3299 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3300   if (N->getValueType(0).getVectorNumElements() != 4)
3301     return false;
3302
3303   // Expect 0, 0, 2, 2
3304   for (unsigned i = 0; i < 2; ++i)
3305     if (N->getMaskElt(i) > 0)
3306       return false;
3307
3308   bool HasHi = false;
3309   for (unsigned i = 2; i < 4; ++i) {
3310     int Elt = N->getMaskElt(i);
3311     if (Elt >= 0 && Elt != 2)
3312       return false;
3313     if (Elt == 2)
3314       HasHi = true;
3315   }
3316   // Don't use movsldup if it can be done with a shufps.
3317   return HasHi;
3318 }
3319
3320 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3321 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3322 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3323   int e = N->getValueType(0).getVectorNumElements() / 2;
3324
3325   for (int i = 0; i < e; ++i)
3326     if (!isUndefOrEqual(N->getMaskElt(i), i))
3327       return false;
3328   for (int i = 0; i < e; ++i)
3329     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3330       return false;
3331   return true;
3332 }
3333
3334 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3335 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3336 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3337   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3338   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3339
3340   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3341   unsigned Mask = 0;
3342   for (int i = 0; i < NumOperands; ++i) {
3343     int Val = SVOp->getMaskElt(NumOperands-i-1);
3344     if (Val < 0) Val = 0;
3345     if (Val >= NumOperands) Val -= NumOperands;
3346     Mask |= Val;
3347     if (i != NumOperands - 1)
3348       Mask <<= Shift;
3349   }
3350   return Mask;
3351 }
3352
3353 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3354 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3355 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3356   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3357   unsigned Mask = 0;
3358   // 8 nodes, but we only care about the last 4.
3359   for (unsigned i = 7; i >= 4; --i) {
3360     int Val = SVOp->getMaskElt(i);
3361     if (Val >= 0)
3362       Mask |= (Val - 4);
3363     if (i != 4)
3364       Mask <<= 2;
3365   }
3366   return Mask;
3367 }
3368
3369 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3370 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3371 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3372   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3373   unsigned Mask = 0;
3374   // 8 nodes, but we only care about the first 4.
3375   for (int i = 3; i >= 0; --i) {
3376     int Val = SVOp->getMaskElt(i);
3377     if (Val >= 0)
3378       Mask |= Val;
3379     if (i != 0)
3380       Mask <<= 2;
3381   }
3382   return Mask;
3383 }
3384
3385 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3386 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3387 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3389   EVT VVT = N->getValueType(0);
3390   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3391   int Val = 0;
3392
3393   unsigned i, e;
3394   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3395     Val = SVOp->getMaskElt(i);
3396     if (Val >= 0)
3397       break;
3398   }
3399   return (Val - i) * EltSize;
3400 }
3401
3402 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3403 /// constant +0.0.
3404 bool X86::isZeroNode(SDValue Elt) {
3405   return ((isa<ConstantSDNode>(Elt) &&
3406            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3407           (isa<ConstantFPSDNode>(Elt) &&
3408            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3409 }
3410
3411 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3412 /// their permute mask.
3413 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3414                                     SelectionDAG &DAG) {
3415   EVT VT = SVOp->getValueType(0);
3416   unsigned NumElems = VT.getVectorNumElements();
3417   SmallVector<int, 8> MaskVec;
3418
3419   for (unsigned i = 0; i != NumElems; ++i) {
3420     int idx = SVOp->getMaskElt(i);
3421     if (idx < 0)
3422       MaskVec.push_back(idx);
3423     else if (idx < (int)NumElems)
3424       MaskVec.push_back(idx + NumElems);
3425     else
3426       MaskVec.push_back(idx - NumElems);
3427   }
3428   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3429                               SVOp->getOperand(0), &MaskVec[0]);
3430 }
3431
3432 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3433 /// the two vector operands have swapped position.
3434 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3435   unsigned NumElems = VT.getVectorNumElements();
3436   for (unsigned i = 0; i != NumElems; ++i) {
3437     int idx = Mask[i];
3438     if (idx < 0)
3439       continue;
3440     else if (idx < (int)NumElems)
3441       Mask[i] = idx + NumElems;
3442     else
3443       Mask[i] = idx - NumElems;
3444   }
3445 }
3446
3447 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3448 /// match movhlps. The lower half elements should come from upper half of
3449 /// V1 (and in order), and the upper half elements should come from the upper
3450 /// half of V2 (and in order).
3451 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3452   if (Op->getValueType(0).getVectorNumElements() != 4)
3453     return false;
3454   for (unsigned i = 0, e = 2; i != e; ++i)
3455     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3456       return false;
3457   for (unsigned i = 2; i != 4; ++i)
3458     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3459       return false;
3460   return true;
3461 }
3462
3463 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3464 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3465 /// required.
3466 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3467   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3468     return false;
3469   N = N->getOperand(0).getNode();
3470   if (!ISD::isNON_EXTLoad(N))
3471     return false;
3472   if (LD)
3473     *LD = cast<LoadSDNode>(N);
3474   return true;
3475 }
3476
3477 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3478 /// match movlp{s|d}. The lower half elements should come from lower half of
3479 /// V1 (and in order), and the upper half elements should come from the upper
3480 /// half of V2 (and in order). And since V1 will become the source of the
3481 /// MOVLP, it must be either a vector load or a scalar load to vector.
3482 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3483                                ShuffleVectorSDNode *Op) {
3484   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3485     return false;
3486   // Is V2 is a vector load, don't do this transformation. We will try to use
3487   // load folding shufps op.
3488   if (ISD::isNON_EXTLoad(V2))
3489     return false;
3490
3491   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3492
3493   if (NumElems != 2 && NumElems != 4)
3494     return false;
3495   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3496     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3497       return false;
3498   for (unsigned i = NumElems/2; i != NumElems; ++i)
3499     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3500       return false;
3501   return true;
3502 }
3503
3504 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3505 /// all the same.
3506 static bool isSplatVector(SDNode *N) {
3507   if (N->getOpcode() != ISD::BUILD_VECTOR)
3508     return false;
3509
3510   SDValue SplatValue = N->getOperand(0);
3511   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3512     if (N->getOperand(i) != SplatValue)
3513       return false;
3514   return true;
3515 }
3516
3517 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3518 /// to an zero vector.
3519 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3520 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3521   SDValue V1 = N->getOperand(0);
3522   SDValue V2 = N->getOperand(1);
3523   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3524   for (unsigned i = 0; i != NumElems; ++i) {
3525     int Idx = N->getMaskElt(i);
3526     if (Idx >= (int)NumElems) {
3527       unsigned Opc = V2.getOpcode();
3528       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3529         continue;
3530       if (Opc != ISD::BUILD_VECTOR ||
3531           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3532         return false;
3533     } else if (Idx >= 0) {
3534       unsigned Opc = V1.getOpcode();
3535       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3536         continue;
3537       if (Opc != ISD::BUILD_VECTOR ||
3538           !X86::isZeroNode(V1.getOperand(Idx)))
3539         return false;
3540     }
3541   }
3542   return true;
3543 }
3544
3545 /// getZeroVector - Returns a vector of specified type with all zero elements.
3546 ///
3547 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3548                              DebugLoc dl) {
3549   assert(VT.isVector() && "Expected a vector type");
3550
3551   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted
3552   // to their dest type. This ensures they get CSE'd.
3553   SDValue Vec;
3554   if (VT.getSizeInBits() == 64) { // MMX
3555     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3556     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3557   } else if (VT.getSizeInBits() == 128) {
3558     if (HasSSE2) {  // SSE2
3559       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3560       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3561     } else { // SSE1
3562       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3563       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3564     }
3565   } else if (VT.getSizeInBits() == 256) { // AVX
3566     // 256-bit logic and arithmetic instructions in AVX are
3567     // all floating-point, no support for integer ops. Default
3568     // to emitting fp zeroed vectors then.
3569     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3570     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3571     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3572   }
3573   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3574 }
3575
3576 /// getOnesVector - Returns a vector of specified type with all bits set.
3577 ///
3578 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3579   assert(VT.isVector() && "Expected a vector type");
3580
3581   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3582   // type.  This ensures they get CSE'd.
3583   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3584   SDValue Vec;
3585   if (VT.getSizeInBits() == 64) // MMX
3586     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3587   else // SSE
3588     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3589   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3590 }
3591
3592
3593 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3594 /// that point to V2 points to its first element.
3595 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3596   EVT VT = SVOp->getValueType(0);
3597   unsigned NumElems = VT.getVectorNumElements();
3598
3599   bool Changed = false;
3600   SmallVector<int, 8> MaskVec;
3601   SVOp->getMask(MaskVec);
3602
3603   for (unsigned i = 0; i != NumElems; ++i) {
3604     if (MaskVec[i] > (int)NumElems) {
3605       MaskVec[i] = NumElems;
3606       Changed = true;
3607     }
3608   }
3609   if (Changed)
3610     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3611                                 SVOp->getOperand(1), &MaskVec[0]);
3612   return SDValue(SVOp, 0);
3613 }
3614
3615 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3616 /// operation of specified width.
3617 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3618                        SDValue V2) {
3619   unsigned NumElems = VT.getVectorNumElements();
3620   SmallVector<int, 8> Mask;
3621   Mask.push_back(NumElems);
3622   for (unsigned i = 1; i != NumElems; ++i)
3623     Mask.push_back(i);
3624   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3625 }
3626
3627 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3628 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3629                           SDValue V2) {
3630   unsigned NumElems = VT.getVectorNumElements();
3631   SmallVector<int, 8> Mask;
3632   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3633     Mask.push_back(i);
3634     Mask.push_back(i + NumElems);
3635   }
3636   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3637 }
3638
3639 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3640 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3641                           SDValue V2) {
3642   unsigned NumElems = VT.getVectorNumElements();
3643   unsigned Half = NumElems/2;
3644   SmallVector<int, 8> Mask;
3645   for (unsigned i = 0; i != Half; ++i) {
3646     Mask.push_back(i + Half);
3647     Mask.push_back(i + NumElems + Half);
3648   }
3649   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3650 }
3651
3652 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3653 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3654   EVT PVT = MVT::v4f32;
3655   EVT VT = SV->getValueType(0);
3656   DebugLoc dl = SV->getDebugLoc();
3657   SDValue V1 = SV->getOperand(0);
3658   int NumElems = VT.getVectorNumElements();
3659   int EltNo = SV->getSplatIndex();
3660
3661   // unpack elements to the correct location
3662   while (NumElems > 4) {
3663     if (EltNo < NumElems/2) {
3664       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3665     } else {
3666       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3667       EltNo -= NumElems/2;
3668     }
3669     NumElems >>= 1;
3670   }
3671
3672   // Perform the splat.
3673   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3674   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3675   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3676   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3677 }
3678
3679 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3680 /// vector of zero or undef vector.  This produces a shuffle where the low
3681 /// element of V2 is swizzled into the zero/undef vector, landing at element
3682 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3683 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3684                                              bool isZero, bool HasSSE2,
3685                                              SelectionDAG &DAG) {
3686   EVT VT = V2.getValueType();
3687   SDValue V1 = isZero
3688     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3689   unsigned NumElems = VT.getVectorNumElements();
3690   SmallVector<int, 16> MaskVec;
3691   for (unsigned i = 0; i != NumElems; ++i)
3692     // If this is the insertion idx, put the low elt of V2 here.
3693     MaskVec.push_back(i == Idx ? NumElems : i);
3694   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3695 }
3696
3697 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3698 /// element of the result of the vector shuffle.
3699 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3700                             unsigned Depth) {
3701   if (Depth == 6)
3702     return SDValue();  // Limit search depth.
3703
3704   SDValue V = SDValue(N, 0);
3705   EVT VT = V.getValueType();
3706   unsigned Opcode = V.getOpcode();
3707
3708   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3709   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3710     Index = SV->getMaskElt(Index);
3711
3712     if (Index < 0)
3713       return DAG.getUNDEF(VT.getVectorElementType());
3714
3715     int NumElems = VT.getVectorNumElements();
3716     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3717     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3718   }
3719
3720   // Recurse into target specific vector shuffles to find scalars.
3721   if (isTargetShuffle(Opcode)) {
3722     int NumElems = VT.getVectorNumElements();
3723     SmallVector<unsigned, 16> ShuffleMask;
3724     SDValue ImmN;
3725
3726     switch(Opcode) {
3727     case X86ISD::SHUFPS:
3728     case X86ISD::SHUFPD:
3729       ImmN = N->getOperand(N->getNumOperands()-1);
3730       DecodeSHUFPSMask(NumElems,
3731                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3732                        ShuffleMask);
3733       break;
3734     case X86ISD::PUNPCKHBW:
3735     case X86ISD::PUNPCKHWD:
3736     case X86ISD::PUNPCKHDQ:
3737     case X86ISD::PUNPCKHQDQ:
3738       DecodePUNPCKHMask(NumElems, ShuffleMask);
3739       break;
3740     case X86ISD::UNPCKHPS:
3741     case X86ISD::UNPCKHPD:
3742       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3743       break;
3744     case X86ISD::PUNPCKLBW:
3745     case X86ISD::PUNPCKLWD:
3746     case X86ISD::PUNPCKLDQ:
3747     case X86ISD::PUNPCKLQDQ:
3748       DecodePUNPCKLMask(NumElems, ShuffleMask);
3749       break;
3750     case X86ISD::UNPCKLPS:
3751     case X86ISD::UNPCKLPD:
3752       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3753       break;
3754     case X86ISD::MOVHLPS:
3755       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3756       break;
3757     case X86ISD::MOVLHPS:
3758       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3759       break;
3760     case X86ISD::PSHUFD:
3761       ImmN = N->getOperand(N->getNumOperands()-1);
3762       DecodePSHUFMask(NumElems,
3763                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3764                       ShuffleMask);
3765       break;
3766     case X86ISD::PSHUFHW:
3767       ImmN = N->getOperand(N->getNumOperands()-1);
3768       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3769                         ShuffleMask);
3770       break;
3771     case X86ISD::PSHUFLW:
3772       ImmN = N->getOperand(N->getNumOperands()-1);
3773       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3774                         ShuffleMask);
3775       break;
3776     case X86ISD::MOVSS:
3777     case X86ISD::MOVSD: {
3778       // The index 0 always comes from the first element of the second source,
3779       // this is why MOVSS and MOVSD are used in the first place. The other
3780       // elements come from the other positions of the first source vector.
3781       unsigned OpNum = (Index == 0) ? 1 : 0;
3782       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3783                                  Depth+1);
3784     }
3785     default:
3786       assert("not implemented for target shuffle node");
3787       return SDValue();
3788     }
3789
3790     Index = ShuffleMask[Index];
3791     if (Index < 0)
3792       return DAG.getUNDEF(VT.getVectorElementType());
3793
3794     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3795     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3796                                Depth+1);
3797   }
3798
3799   // Actual nodes that may contain scalar elements
3800   if (Opcode == ISD::BIT_CONVERT) {
3801     V = V.getOperand(0);
3802     EVT SrcVT = V.getValueType();
3803     unsigned NumElems = VT.getVectorNumElements();
3804
3805     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3806       return SDValue();
3807   }
3808
3809   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3810     return (Index == 0) ? V.getOperand(0)
3811                           : DAG.getUNDEF(VT.getVectorElementType());
3812
3813   if (V.getOpcode() == ISD::BUILD_VECTOR)
3814     return V.getOperand(Index);
3815
3816   return SDValue();
3817 }
3818
3819 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3820 /// shuffle operation which come from a consecutively from a zero. The
3821 /// search can start in two diferent directions, from left or right.
3822 static
3823 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3824                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3825   int i = 0;
3826
3827   while (i < NumElems) {
3828     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3829     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3830     if (!(Elt.getNode() &&
3831          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3832       break;
3833     ++i;
3834   }
3835
3836   return i;
3837 }
3838
3839 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3840 /// MaskE correspond consecutively to elements from one of the vector operands,
3841 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3842 static
3843 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3844                               int OpIdx, int NumElems, unsigned &OpNum) {
3845   bool SeenV1 = false;
3846   bool SeenV2 = false;
3847
3848   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3849     int Idx = SVOp->getMaskElt(i);
3850     // Ignore undef indicies
3851     if (Idx < 0)
3852       continue;
3853
3854     if (Idx < NumElems)
3855       SeenV1 = true;
3856     else
3857       SeenV2 = true;
3858
3859     // Only accept consecutive elements from the same vector
3860     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3861       return false;
3862   }
3863
3864   OpNum = SeenV1 ? 0 : 1;
3865   return true;
3866 }
3867
3868 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3869 /// logical left shift of a vector.
3870 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3871                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3872   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3873   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3874               false /* check zeros from right */, DAG);
3875   unsigned OpSrc;
3876
3877   if (!NumZeros)
3878     return false;
3879
3880   // Considering the elements in the mask that are not consecutive zeros,
3881   // check if they consecutively come from only one of the source vectors.
3882   //
3883   //               V1 = {X, A, B, C}     0
3884   //                         \  \  \    /
3885   //   vector_shuffle V1, V2 <1, 2, 3, X>
3886   //
3887   if (!isShuffleMaskConsecutive(SVOp,
3888             0,                   // Mask Start Index
3889             NumElems-NumZeros-1, // Mask End Index
3890             NumZeros,            // Where to start looking in the src vector
3891             NumElems,            // Number of elements in vector
3892             OpSrc))              // Which source operand ?
3893     return false;
3894
3895   isLeft = false;
3896   ShAmt = NumZeros;
3897   ShVal = SVOp->getOperand(OpSrc);
3898   return true;
3899 }
3900
3901 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3902 /// logical left shift of a vector.
3903 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3904                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3905   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3906   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3907               true /* check zeros from left */, DAG);
3908   unsigned OpSrc;
3909
3910   if (!NumZeros)
3911     return false;
3912
3913   // Considering the elements in the mask that are not consecutive zeros,
3914   // check if they consecutively come from only one of the source vectors.
3915   //
3916   //                           0    { A, B, X, X } = V2
3917   //                          / \    /  /
3918   //   vector_shuffle V1, V2 <X, X, 4, 5>
3919   //
3920   if (!isShuffleMaskConsecutive(SVOp,
3921             NumZeros,     // Mask Start Index
3922             NumElems-1,   // Mask End Index
3923             0,            // Where to start looking in the src vector
3924             NumElems,     // Number of elements in vector
3925             OpSrc))       // Which source operand ?
3926     return false;
3927
3928   isLeft = true;
3929   ShAmt = NumZeros;
3930   ShVal = SVOp->getOperand(OpSrc);
3931   return true;
3932 }
3933
3934 /// isVectorShift - Returns true if the shuffle can be implemented as a
3935 /// logical left or right shift of a vector.
3936 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3937                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3938   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3939       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3940     return true;
3941
3942   return false;
3943 }
3944
3945 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3946 ///
3947 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3948                                        unsigned NumNonZero, unsigned NumZero,
3949                                        SelectionDAG &DAG,
3950                                        const TargetLowering &TLI) {
3951   if (NumNonZero > 8)
3952     return SDValue();
3953
3954   DebugLoc dl = Op.getDebugLoc();
3955   SDValue V(0, 0);
3956   bool First = true;
3957   for (unsigned i = 0; i < 16; ++i) {
3958     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3959     if (ThisIsNonZero && First) {
3960       if (NumZero)
3961         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3962       else
3963         V = DAG.getUNDEF(MVT::v8i16);
3964       First = false;
3965     }
3966
3967     if ((i & 1) != 0) {
3968       SDValue ThisElt(0, 0), LastElt(0, 0);
3969       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3970       if (LastIsNonZero) {
3971         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3972                               MVT::i16, Op.getOperand(i-1));
3973       }
3974       if (ThisIsNonZero) {
3975         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3976         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3977                               ThisElt, DAG.getConstant(8, MVT::i8));
3978         if (LastIsNonZero)
3979           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3980       } else
3981         ThisElt = LastElt;
3982
3983       if (ThisElt.getNode())
3984         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3985                         DAG.getIntPtrConstant(i/2));
3986     }
3987   }
3988
3989   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3990 }
3991
3992 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3993 ///
3994 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3995                                      unsigned NumNonZero, unsigned NumZero,
3996                                      SelectionDAG &DAG,
3997                                      const TargetLowering &TLI) {
3998   if (NumNonZero > 4)
3999     return SDValue();
4000
4001   DebugLoc dl = Op.getDebugLoc();
4002   SDValue V(0, 0);
4003   bool First = true;
4004   for (unsigned i = 0; i < 8; ++i) {
4005     bool isNonZero = (NonZeros & (1 << i)) != 0;
4006     if (isNonZero) {
4007       if (First) {
4008         if (NumZero)
4009           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4010         else
4011           V = DAG.getUNDEF(MVT::v8i16);
4012         First = false;
4013       }
4014       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4015                       MVT::v8i16, V, Op.getOperand(i),
4016                       DAG.getIntPtrConstant(i));
4017     }
4018   }
4019
4020   return V;
4021 }
4022
4023 /// getVShift - Return a vector logical shift node.
4024 ///
4025 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4026                          unsigned NumBits, SelectionDAG &DAG,
4027                          const TargetLowering &TLI, DebugLoc dl) {
4028   bool isMMX = VT.getSizeInBits() == 64;
4029   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
4030   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4031   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
4032   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4033                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4034                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4035 }
4036
4037 SDValue
4038 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4039                                           SelectionDAG &DAG) const {
4040   
4041   // Check if the scalar load can be widened into a vector load. And if
4042   // the address is "base + cst" see if the cst can be "absorbed" into
4043   // the shuffle mask.
4044   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4045     SDValue Ptr = LD->getBasePtr();
4046     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4047       return SDValue();
4048     EVT PVT = LD->getValueType(0);
4049     if (PVT != MVT::i32 && PVT != MVT::f32)
4050       return SDValue();
4051
4052     int FI = -1;
4053     int64_t Offset = 0;
4054     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4055       FI = FINode->getIndex();
4056       Offset = 0;
4057     } else if (Ptr.getOpcode() == ISD::ADD &&
4058                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4059                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4060       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4061       Offset = Ptr.getConstantOperandVal(1);
4062       Ptr = Ptr.getOperand(0);
4063     } else {
4064       return SDValue();
4065     }
4066
4067     SDValue Chain = LD->getChain();
4068     // Make sure the stack object alignment is at least 16.
4069     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4070     if (DAG.InferPtrAlignment(Ptr) < 16) {
4071       if (MFI->isFixedObjectIndex(FI)) {
4072         // Can't change the alignment. FIXME: It's possible to compute
4073         // the exact stack offset and reference FI + adjust offset instead.
4074         // If someone *really* cares about this. That's the way to implement it.
4075         return SDValue();
4076       } else {
4077         MFI->setObjectAlignment(FI, 16);
4078       }
4079     }
4080
4081     // (Offset % 16) must be multiple of 4. Then address is then
4082     // Ptr + (Offset & ~15).
4083     if (Offset < 0)
4084       return SDValue();
4085     if ((Offset % 16) & 3)
4086       return SDValue();
4087     int64_t StartOffset = Offset & ~15;
4088     if (StartOffset)
4089       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4090                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4091
4092     int EltNo = (Offset - StartOffset) >> 2;
4093     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4094     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4095     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4096                              LD->getPointerInfo().getWithOffset(StartOffset),
4097                              false, false, 0);
4098     // Canonicalize it to a v4i32 shuffle.
4099     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4100     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4101                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4102                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4103   }
4104
4105   return SDValue();
4106 }
4107
4108 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
4109 /// vector of type 'VT', see if the elements can be replaced by a single large 
4110 /// load which has the same value as a build_vector whose operands are 'elts'.
4111 ///
4112 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4113 /// 
4114 /// FIXME: we'd also like to handle the case where the last elements are zero
4115 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4116 /// There's even a handy isZeroNode for that purpose.
4117 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4118                                         DebugLoc &DL, SelectionDAG &DAG) {
4119   EVT EltVT = VT.getVectorElementType();
4120   unsigned NumElems = Elts.size();
4121   
4122   LoadSDNode *LDBase = NULL;
4123   unsigned LastLoadedElt = -1U;
4124   
4125   // For each element in the initializer, see if we've found a load or an undef.
4126   // If we don't find an initial load element, or later load elements are 
4127   // non-consecutive, bail out.
4128   for (unsigned i = 0; i < NumElems; ++i) {
4129     SDValue Elt = Elts[i];
4130     
4131     if (!Elt.getNode() ||
4132         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4133       return SDValue();
4134     if (!LDBase) {
4135       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4136         return SDValue();
4137       LDBase = cast<LoadSDNode>(Elt.getNode());
4138       LastLoadedElt = i;
4139       continue;
4140     }
4141     if (Elt.getOpcode() == ISD::UNDEF)
4142       continue;
4143
4144     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4145     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4146       return SDValue();
4147     LastLoadedElt = i;
4148   }
4149
4150   // If we have found an entire vector of loads and undefs, then return a large
4151   // load of the entire vector width starting at the base pointer.  If we found
4152   // consecutive loads for the low half, generate a vzext_load node.
4153   if (LastLoadedElt == NumElems - 1) {
4154     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4155       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4156                          LDBase->getPointerInfo(),
4157                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4158     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4159                        LDBase->getPointerInfo(),
4160                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4161                        LDBase->getAlignment());
4162   } else if (NumElems == 4 && LastLoadedElt == 1) {
4163     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4164     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4165     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4166                                               Ops, 2, MVT::i32,
4167                                               LDBase->getMemOperand());
4168     return DAG.getNode(ISD::BIT_CONVERT, DL, VT, ResNode);
4169   }
4170   return SDValue();
4171 }
4172
4173 SDValue
4174 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4175   DebugLoc dl = Op.getDebugLoc();
4176   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4177   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4178   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4179   // is present, so AllOnes is ignored.
4180   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4181       (Op.getValueType().getSizeInBits() != 256 &&
4182        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4183     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
4184     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4185     // eliminated on x86-32 hosts.
4186     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
4187       return Op;
4188
4189     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4190       return getOnesVector(Op.getValueType(), DAG, dl);
4191     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4192   }
4193
4194   EVT VT = Op.getValueType();
4195   EVT ExtVT = VT.getVectorElementType();
4196   unsigned EVTBits = ExtVT.getSizeInBits();
4197
4198   unsigned NumElems = Op.getNumOperands();
4199   unsigned NumZero  = 0;
4200   unsigned NumNonZero = 0;
4201   unsigned NonZeros = 0;
4202   bool IsAllConstants = true;
4203   SmallSet<SDValue, 8> Values;
4204   for (unsigned i = 0; i < NumElems; ++i) {
4205     SDValue Elt = Op.getOperand(i);
4206     if (Elt.getOpcode() == ISD::UNDEF)
4207       continue;
4208     Values.insert(Elt);
4209     if (Elt.getOpcode() != ISD::Constant &&
4210         Elt.getOpcode() != ISD::ConstantFP)
4211       IsAllConstants = false;
4212     if (X86::isZeroNode(Elt))
4213       NumZero++;
4214     else {
4215       NonZeros |= (1 << i);
4216       NumNonZero++;
4217     }
4218   }
4219
4220   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4221   if (NumNonZero == 0)
4222     return DAG.getUNDEF(VT);
4223
4224   // Special case for single non-zero, non-undef, element.
4225   if (NumNonZero == 1) {
4226     unsigned Idx = CountTrailingZeros_32(NonZeros);
4227     SDValue Item = Op.getOperand(Idx);
4228
4229     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4230     // the value are obviously zero, truncate the value to i32 and do the
4231     // insertion that way.  Only do this if the value is non-constant or if the
4232     // value is a constant being inserted into element 0.  It is cheaper to do
4233     // a constant pool load than it is to do a movd + shuffle.
4234     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4235         (!IsAllConstants || Idx == 0)) {
4236       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4237         // Handle MMX and SSE both.
4238         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
4239         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
4240
4241         // Truncate the value (which may itself be a constant) to i32, and
4242         // convert it to a vector with movd (S2V+shuffle to zero extend).
4243         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4244         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4245         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4246                                            Subtarget->hasSSE2(), DAG);
4247
4248         // Now we have our 32-bit value zero extended in the low element of
4249         // a vector.  If Idx != 0, swizzle it into place.
4250         if (Idx != 0) {
4251           SmallVector<int, 4> Mask;
4252           Mask.push_back(Idx);
4253           for (unsigned i = 1; i != VecElts; ++i)
4254             Mask.push_back(i);
4255           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4256                                       DAG.getUNDEF(Item.getValueType()),
4257                                       &Mask[0]);
4258         }
4259         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4260       }
4261     }
4262
4263     // If we have a constant or non-constant insertion into the low element of
4264     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4265     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4266     // depending on what the source datatype is.
4267     if (Idx == 0) {
4268       if (NumZero == 0) {
4269         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4270       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4271           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4272         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4273         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4274         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4275                                            DAG);
4276       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4277         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4278         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
4279         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4280         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4281                                            Subtarget->hasSSE2(), DAG);
4282         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4283       }
4284     }
4285
4286     // Is it a vector logical left shift?
4287     if (NumElems == 2 && Idx == 1 &&
4288         X86::isZeroNode(Op.getOperand(0)) &&
4289         !X86::isZeroNode(Op.getOperand(1))) {
4290       unsigned NumBits = VT.getSizeInBits();
4291       return getVShift(true, VT,
4292                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4293                                    VT, Op.getOperand(1)),
4294                        NumBits/2, DAG, *this, dl);
4295     }
4296
4297     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4298       return SDValue();
4299
4300     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4301     // is a non-constant being inserted into an element other than the low one,
4302     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4303     // movd/movss) to move this into the low element, then shuffle it into
4304     // place.
4305     if (EVTBits == 32) {
4306       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4307
4308       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4309       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4310                                          Subtarget->hasSSE2(), DAG);
4311       SmallVector<int, 8> MaskVec;
4312       for (unsigned i = 0; i < NumElems; i++)
4313         MaskVec.push_back(i == Idx ? 0 : 1);
4314       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4315     }
4316   }
4317
4318   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4319   if (Values.size() == 1) {
4320     if (EVTBits == 32) {
4321       // Instead of a shuffle like this:
4322       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4323       // Check if it's possible to issue this instead.
4324       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4325       unsigned Idx = CountTrailingZeros_32(NonZeros);
4326       SDValue Item = Op.getOperand(Idx);
4327       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4328         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4329     }
4330     return SDValue();
4331   }
4332
4333   // A vector full of immediates; various special cases are already
4334   // handled, so this is best done with a single constant-pool load.
4335   if (IsAllConstants)
4336     return SDValue();
4337
4338   // Let legalizer expand 2-wide build_vectors.
4339   if (EVTBits == 64) {
4340     if (NumNonZero == 1) {
4341       // One half is zero or undef.
4342       unsigned Idx = CountTrailingZeros_32(NonZeros);
4343       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4344                                  Op.getOperand(Idx));
4345       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4346                                          Subtarget->hasSSE2(), DAG);
4347     }
4348     return SDValue();
4349   }
4350
4351   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4352   if (EVTBits == 8 && NumElems == 16) {
4353     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4354                                         *this);
4355     if (V.getNode()) return V;
4356   }
4357
4358   if (EVTBits == 16 && NumElems == 8) {
4359     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4360                                       *this);
4361     if (V.getNode()) return V;
4362   }
4363
4364   // If element VT is == 32 bits, turn it into a number of shuffles.
4365   SmallVector<SDValue, 8> V;
4366   V.resize(NumElems);
4367   if (NumElems == 4 && NumZero > 0) {
4368     for (unsigned i = 0; i < 4; ++i) {
4369       bool isZero = !(NonZeros & (1 << i));
4370       if (isZero)
4371         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4372       else
4373         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4374     }
4375
4376     for (unsigned i = 0; i < 2; ++i) {
4377       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4378         default: break;
4379         case 0:
4380           V[i] = V[i*2];  // Must be a zero vector.
4381           break;
4382         case 1:
4383           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4384           break;
4385         case 2:
4386           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4387           break;
4388         case 3:
4389           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4390           break;
4391       }
4392     }
4393
4394     SmallVector<int, 8> MaskVec;
4395     bool Reverse = (NonZeros & 0x3) == 2;
4396     for (unsigned i = 0; i < 2; ++i)
4397       MaskVec.push_back(Reverse ? 1-i : i);
4398     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4399     for (unsigned i = 0; i < 2; ++i)
4400       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4401     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4402   }
4403
4404   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4405     // Check for a build vector of consecutive loads.
4406     for (unsigned i = 0; i < NumElems; ++i)
4407       V[i] = Op.getOperand(i);
4408     
4409     // Check for elements which are consecutive loads.
4410     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4411     if (LD.getNode())
4412       return LD;
4413     
4414     // For SSE 4.1, use insertps to put the high elements into the low element. 
4415     if (getSubtarget()->hasSSE41()) {
4416       SDValue Result;
4417       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4418         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4419       else
4420         Result = DAG.getUNDEF(VT);
4421       
4422       for (unsigned i = 1; i < NumElems; ++i) {
4423         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4424         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4425                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4426       }
4427       return Result;
4428     }
4429     
4430     // Otherwise, expand into a number of unpckl*, start by extending each of
4431     // our (non-undef) elements to the full vector width with the element in the
4432     // bottom slot of the vector (which generates no code for SSE).
4433     for (unsigned i = 0; i < NumElems; ++i) {
4434       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4435         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4436       else
4437         V[i] = DAG.getUNDEF(VT);
4438     }
4439
4440     // Next, we iteratively mix elements, e.g. for v4f32:
4441     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4442     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4443     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4444     unsigned EltStride = NumElems >> 1;
4445     while (EltStride != 0) {
4446       for (unsigned i = 0; i < EltStride; ++i) {
4447         // If V[i+EltStride] is undef and this is the first round of mixing,
4448         // then it is safe to just drop this shuffle: V[i] is already in the
4449         // right place, the one element (since it's the first round) being
4450         // inserted as undef can be dropped.  This isn't safe for successive
4451         // rounds because they will permute elements within both vectors.
4452         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4453             EltStride == NumElems/2)
4454           continue;
4455         
4456         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4457       }
4458       EltStride >>= 1;
4459     }
4460     return V[0];
4461   }
4462   return SDValue();
4463 }
4464
4465 SDValue
4466 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4467   // We support concatenate two MMX registers and place them in a MMX
4468   // register.  This is better than doing a stack convert.
4469   DebugLoc dl = Op.getDebugLoc();
4470   EVT ResVT = Op.getValueType();
4471   assert(Op.getNumOperands() == 2);
4472   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4473          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4474   int Mask[2];
4475   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4476   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4477   InVec = Op.getOperand(1);
4478   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4479     unsigned NumElts = ResVT.getVectorNumElements();
4480     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4481     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4482                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4483   } else {
4484     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4485     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4486     Mask[0] = 0; Mask[1] = 2;
4487     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4488   }
4489   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4490 }
4491
4492 // v8i16 shuffles - Prefer shuffles in the following order:
4493 // 1. [all]   pshuflw, pshufhw, optional move
4494 // 2. [ssse3] 1 x pshufb
4495 // 3. [ssse3] 2 x pshufb + 1 x por
4496 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4497 SDValue
4498 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4499                                             SelectionDAG &DAG) const {
4500   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4501   SDValue V1 = SVOp->getOperand(0);
4502   SDValue V2 = SVOp->getOperand(1);
4503   DebugLoc dl = SVOp->getDebugLoc();
4504   SmallVector<int, 8> MaskVals;
4505
4506   // Determine if more than 1 of the words in each of the low and high quadwords
4507   // of the result come from the same quadword of one of the two inputs.  Undef
4508   // mask values count as coming from any quadword, for better codegen.
4509   SmallVector<unsigned, 4> LoQuad(4);
4510   SmallVector<unsigned, 4> HiQuad(4);
4511   BitVector InputQuads(4);
4512   for (unsigned i = 0; i < 8; ++i) {
4513     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4514     int EltIdx = SVOp->getMaskElt(i);
4515     MaskVals.push_back(EltIdx);
4516     if (EltIdx < 0) {
4517       ++Quad[0];
4518       ++Quad[1];
4519       ++Quad[2];
4520       ++Quad[3];
4521       continue;
4522     }
4523     ++Quad[EltIdx / 4];
4524     InputQuads.set(EltIdx / 4);
4525   }
4526
4527   int BestLoQuad = -1;
4528   unsigned MaxQuad = 1;
4529   for (unsigned i = 0; i < 4; ++i) {
4530     if (LoQuad[i] > MaxQuad) {
4531       BestLoQuad = i;
4532       MaxQuad = LoQuad[i];
4533     }
4534   }
4535
4536   int BestHiQuad = -1;
4537   MaxQuad = 1;
4538   for (unsigned i = 0; i < 4; ++i) {
4539     if (HiQuad[i] > MaxQuad) {
4540       BestHiQuad = i;
4541       MaxQuad = HiQuad[i];
4542     }
4543   }
4544
4545   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4546   // of the two input vectors, shuffle them into one input vector so only a
4547   // single pshufb instruction is necessary. If There are more than 2 input
4548   // quads, disable the next transformation since it does not help SSSE3.
4549   bool V1Used = InputQuads[0] || InputQuads[1];
4550   bool V2Used = InputQuads[2] || InputQuads[3];
4551   if (Subtarget->hasSSSE3()) {
4552     if (InputQuads.count() == 2 && V1Used && V2Used) {
4553       BestLoQuad = InputQuads.find_first();
4554       BestHiQuad = InputQuads.find_next(BestLoQuad);
4555     }
4556     if (InputQuads.count() > 2) {
4557       BestLoQuad = -1;
4558       BestHiQuad = -1;
4559     }
4560   }
4561
4562   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4563   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4564   // words from all 4 input quadwords.
4565   SDValue NewV;
4566   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4567     SmallVector<int, 8> MaskV;
4568     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4569     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4570     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4571                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4572                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4573     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4574
4575     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4576     // source words for the shuffle, to aid later transformations.
4577     bool AllWordsInNewV = true;
4578     bool InOrder[2] = { true, true };
4579     for (unsigned i = 0; i != 8; ++i) {
4580       int idx = MaskVals[i];
4581       if (idx != (int)i)
4582         InOrder[i/4] = false;
4583       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4584         continue;
4585       AllWordsInNewV = false;
4586       break;
4587     }
4588
4589     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4590     if (AllWordsInNewV) {
4591       for (int i = 0; i != 8; ++i) {
4592         int idx = MaskVals[i];
4593         if (idx < 0)
4594           continue;
4595         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4596         if ((idx != i) && idx < 4)
4597           pshufhw = false;
4598         if ((idx != i) && idx > 3)
4599           pshuflw = false;
4600       }
4601       V1 = NewV;
4602       V2Used = false;
4603       BestLoQuad = 0;
4604       BestHiQuad = 1;
4605     }
4606
4607     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4608     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4609     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4610       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4611       unsigned TargetMask = 0;
4612       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4613                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4614       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4615                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4616       V1 = NewV.getOperand(0);
4617       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4618     }
4619   }
4620
4621   // If we have SSSE3, and all words of the result are from 1 input vector,
4622   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4623   // is present, fall back to case 4.
4624   if (Subtarget->hasSSSE3()) {
4625     SmallVector<SDValue,16> pshufbMask;
4626
4627     // If we have elements from both input vectors, set the high bit of the
4628     // shuffle mask element to zero out elements that come from V2 in the V1
4629     // mask, and elements that come from V1 in the V2 mask, so that the two
4630     // results can be OR'd together.
4631     bool TwoInputs = V1Used && V2Used;
4632     for (unsigned i = 0; i != 8; ++i) {
4633       int EltIdx = MaskVals[i] * 2;
4634       if (TwoInputs && (EltIdx >= 16)) {
4635         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4636         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4637         continue;
4638       }
4639       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4640       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4641     }
4642     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4643     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4644                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4645                                  MVT::v16i8, &pshufbMask[0], 16));
4646     if (!TwoInputs)
4647       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4648
4649     // Calculate the shuffle mask for the second input, shuffle it, and
4650     // OR it with the first shuffled input.
4651     pshufbMask.clear();
4652     for (unsigned i = 0; i != 8; ++i) {
4653       int EltIdx = MaskVals[i] * 2;
4654       if (EltIdx < 16) {
4655         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4656         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4657         continue;
4658       }
4659       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4660       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4661     }
4662     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4663     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4664                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4665                                  MVT::v16i8, &pshufbMask[0], 16));
4666     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4667     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4668   }
4669
4670   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4671   // and update MaskVals with new element order.
4672   BitVector InOrder(8);
4673   if (BestLoQuad >= 0) {
4674     SmallVector<int, 8> MaskV;
4675     for (int i = 0; i != 4; ++i) {
4676       int idx = MaskVals[i];
4677       if (idx < 0) {
4678         MaskV.push_back(-1);
4679         InOrder.set(i);
4680       } else if ((idx / 4) == BestLoQuad) {
4681         MaskV.push_back(idx & 3);
4682         InOrder.set(i);
4683       } else {
4684         MaskV.push_back(-1);
4685       }
4686     }
4687     for (unsigned i = 4; i != 8; ++i)
4688       MaskV.push_back(i);
4689     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4690                                 &MaskV[0]);
4691
4692     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4693       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4694                                NewV.getOperand(0),
4695                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4696                                DAG);
4697   }
4698
4699   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4700   // and update MaskVals with the new element order.
4701   if (BestHiQuad >= 0) {
4702     SmallVector<int, 8> MaskV;
4703     for (unsigned i = 0; i != 4; ++i)
4704       MaskV.push_back(i);
4705     for (unsigned i = 4; i != 8; ++i) {
4706       int idx = MaskVals[i];
4707       if (idx < 0) {
4708         MaskV.push_back(-1);
4709         InOrder.set(i);
4710       } else if ((idx / 4) == BestHiQuad) {
4711         MaskV.push_back((idx & 3) + 4);
4712         InOrder.set(i);
4713       } else {
4714         MaskV.push_back(-1);
4715       }
4716     }
4717     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4718                                 &MaskV[0]);
4719
4720     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4721       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4722                               NewV.getOperand(0),
4723                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4724                               DAG);
4725   }
4726
4727   // In case BestHi & BestLo were both -1, which means each quadword has a word
4728   // from each of the four input quadwords, calculate the InOrder bitvector now
4729   // before falling through to the insert/extract cleanup.
4730   if (BestLoQuad == -1 && BestHiQuad == -1) {
4731     NewV = V1;
4732     for (int i = 0; i != 8; ++i)
4733       if (MaskVals[i] < 0 || MaskVals[i] == i)
4734         InOrder.set(i);
4735   }
4736
4737   // The other elements are put in the right place using pextrw and pinsrw.
4738   for (unsigned i = 0; i != 8; ++i) {
4739     if (InOrder[i])
4740       continue;
4741     int EltIdx = MaskVals[i];
4742     if (EltIdx < 0)
4743       continue;
4744     SDValue ExtOp = (EltIdx < 8)
4745     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4746                   DAG.getIntPtrConstant(EltIdx))
4747     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4748                   DAG.getIntPtrConstant(EltIdx - 8));
4749     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4750                        DAG.getIntPtrConstant(i));
4751   }
4752   return NewV;
4753 }
4754
4755 // v16i8 shuffles - Prefer shuffles in the following order:
4756 // 1. [ssse3] 1 x pshufb
4757 // 2. [ssse3] 2 x pshufb + 1 x por
4758 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4759 static
4760 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4761                                  SelectionDAG &DAG,
4762                                  const X86TargetLowering &TLI) {
4763   SDValue V1 = SVOp->getOperand(0);
4764   SDValue V2 = SVOp->getOperand(1);
4765   DebugLoc dl = SVOp->getDebugLoc();
4766   SmallVector<int, 16> MaskVals;
4767   SVOp->getMask(MaskVals);
4768
4769   // If we have SSSE3, case 1 is generated when all result bytes come from
4770   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4771   // present, fall back to case 3.
4772   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4773   bool V1Only = true;
4774   bool V2Only = true;
4775   for (unsigned i = 0; i < 16; ++i) {
4776     int EltIdx = MaskVals[i];
4777     if (EltIdx < 0)
4778       continue;
4779     if (EltIdx < 16)
4780       V2Only = false;
4781     else
4782       V1Only = false;
4783   }
4784
4785   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4786   if (TLI.getSubtarget()->hasSSSE3()) {
4787     SmallVector<SDValue,16> pshufbMask;
4788
4789     // If all result elements are from one input vector, then only translate
4790     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4791     //
4792     // Otherwise, we have elements from both input vectors, and must zero out
4793     // elements that come from V2 in the first mask, and V1 in the second mask
4794     // so that we can OR them together.
4795     bool TwoInputs = !(V1Only || V2Only);
4796     for (unsigned i = 0; i != 16; ++i) {
4797       int EltIdx = MaskVals[i];
4798       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4799         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4800         continue;
4801       }
4802       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4803     }
4804     // If all the elements are from V2, assign it to V1 and return after
4805     // building the first pshufb.
4806     if (V2Only)
4807       V1 = V2;
4808     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4809                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4810                                  MVT::v16i8, &pshufbMask[0], 16));
4811     if (!TwoInputs)
4812       return V1;
4813
4814     // Calculate the shuffle mask for the second input, shuffle it, and
4815     // OR it with the first shuffled input.
4816     pshufbMask.clear();
4817     for (unsigned i = 0; i != 16; ++i) {
4818       int EltIdx = MaskVals[i];
4819       if (EltIdx < 16) {
4820         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4821         continue;
4822       }
4823       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4824     }
4825     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4826                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4827                                  MVT::v16i8, &pshufbMask[0], 16));
4828     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4829   }
4830
4831   // No SSSE3 - Calculate in place words and then fix all out of place words
4832   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4833   // the 16 different words that comprise the two doublequadword input vectors.
4834   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4835   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4836   SDValue NewV = V2Only ? V2 : V1;
4837   for (int i = 0; i != 8; ++i) {
4838     int Elt0 = MaskVals[i*2];
4839     int Elt1 = MaskVals[i*2+1];
4840
4841     // This word of the result is all undef, skip it.
4842     if (Elt0 < 0 && Elt1 < 0)
4843       continue;
4844
4845     // This word of the result is already in the correct place, skip it.
4846     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4847       continue;
4848     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4849       continue;
4850
4851     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4852     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4853     SDValue InsElt;
4854
4855     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4856     // using a single extract together, load it and store it.
4857     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4858       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4859                            DAG.getIntPtrConstant(Elt1 / 2));
4860       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4861                         DAG.getIntPtrConstant(i));
4862       continue;
4863     }
4864
4865     // If Elt1 is defined, extract it from the appropriate source.  If the
4866     // source byte is not also odd, shift the extracted word left 8 bits
4867     // otherwise clear the bottom 8 bits if we need to do an or.
4868     if (Elt1 >= 0) {
4869       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4870                            DAG.getIntPtrConstant(Elt1 / 2));
4871       if ((Elt1 & 1) == 0)
4872         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4873                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4874       else if (Elt0 >= 0)
4875         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4876                              DAG.getConstant(0xFF00, MVT::i16));
4877     }
4878     // If Elt0 is defined, extract it from the appropriate source.  If the
4879     // source byte is not also even, shift the extracted word right 8 bits. If
4880     // Elt1 was also defined, OR the extracted values together before
4881     // inserting them in the result.
4882     if (Elt0 >= 0) {
4883       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4884                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4885       if ((Elt0 & 1) != 0)
4886         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4887                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4888       else if (Elt1 >= 0)
4889         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4890                              DAG.getConstant(0x00FF, MVT::i16));
4891       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4892                          : InsElt0;
4893     }
4894     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4895                        DAG.getIntPtrConstant(i));
4896   }
4897   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4898 }
4899
4900 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4901 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4902 /// done when every pair / quad of shuffle mask elements point to elements in
4903 /// the right sequence. e.g.
4904 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4905 static
4906 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4907                                  SelectionDAG &DAG, DebugLoc dl) {
4908   EVT VT = SVOp->getValueType(0);
4909   SDValue V1 = SVOp->getOperand(0);
4910   SDValue V2 = SVOp->getOperand(1);
4911   unsigned NumElems = VT.getVectorNumElements();
4912   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4913   EVT NewVT;
4914   switch (VT.getSimpleVT().SimpleTy) {
4915   default: assert(false && "Unexpected!");
4916   case MVT::v4f32: NewVT = MVT::v2f64; break;
4917   case MVT::v4i32: NewVT = MVT::v2i64; break;
4918   case MVT::v8i16: NewVT = MVT::v4i32; break;
4919   case MVT::v16i8: NewVT = MVT::v4i32; break;
4920   }
4921
4922   int Scale = NumElems / NewWidth;
4923   SmallVector<int, 8> MaskVec;
4924   for (unsigned i = 0; i < NumElems; i += Scale) {
4925     int StartIdx = -1;
4926     for (int j = 0; j < Scale; ++j) {
4927       int EltIdx = SVOp->getMaskElt(i+j);
4928       if (EltIdx < 0)
4929         continue;
4930       if (StartIdx == -1)
4931         StartIdx = EltIdx - (EltIdx % Scale);
4932       if (EltIdx != StartIdx + j)
4933         return SDValue();
4934     }
4935     if (StartIdx == -1)
4936       MaskVec.push_back(-1);
4937     else
4938       MaskVec.push_back(StartIdx / Scale);
4939   }
4940
4941   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4942   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4943   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4944 }
4945
4946 /// getVZextMovL - Return a zero-extending vector move low node.
4947 ///
4948 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4949                             SDValue SrcOp, SelectionDAG &DAG,
4950                             const X86Subtarget *Subtarget, DebugLoc dl) {
4951   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4952     LoadSDNode *LD = NULL;
4953     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4954       LD = dyn_cast<LoadSDNode>(SrcOp);
4955     if (!LD) {
4956       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4957       // instead.
4958       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4959       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4960           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4961           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4962           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4963         // PR2108
4964         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4965         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4966                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4967                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4968                                                    OpVT,
4969                                                    SrcOp.getOperand(0)
4970                                                           .getOperand(0))));
4971       }
4972     }
4973   }
4974
4975   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4976                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4977                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4978                                              OpVT, SrcOp)));
4979 }
4980
4981 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4982 /// shuffles.
4983 static SDValue
4984 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4985   SDValue V1 = SVOp->getOperand(0);
4986   SDValue V2 = SVOp->getOperand(1);
4987   DebugLoc dl = SVOp->getDebugLoc();
4988   EVT VT = SVOp->getValueType(0);
4989
4990   SmallVector<std::pair<int, int>, 8> Locs;
4991   Locs.resize(4);
4992   SmallVector<int, 8> Mask1(4U, -1);
4993   SmallVector<int, 8> PermMask;
4994   SVOp->getMask(PermMask);
4995
4996   unsigned NumHi = 0;
4997   unsigned NumLo = 0;
4998   for (unsigned i = 0; i != 4; ++i) {
4999     int Idx = PermMask[i];
5000     if (Idx < 0) {
5001       Locs[i] = std::make_pair(-1, -1);
5002     } else {
5003       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5004       if (Idx < 4) {
5005         Locs[i] = std::make_pair(0, NumLo);
5006         Mask1[NumLo] = Idx;
5007         NumLo++;
5008       } else {
5009         Locs[i] = std::make_pair(1, NumHi);
5010         if (2+NumHi < 4)
5011           Mask1[2+NumHi] = Idx;
5012         NumHi++;
5013       }
5014     }
5015   }
5016
5017   if (NumLo <= 2 && NumHi <= 2) {
5018     // If no more than two elements come from either vector. This can be
5019     // implemented with two shuffles. First shuffle gather the elements.
5020     // The second shuffle, which takes the first shuffle as both of its
5021     // vector operands, put the elements into the right order.
5022     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5023
5024     SmallVector<int, 8> Mask2(4U, -1);
5025
5026     for (unsigned i = 0; i != 4; ++i) {
5027       if (Locs[i].first == -1)
5028         continue;
5029       else {
5030         unsigned Idx = (i < 2) ? 0 : 4;
5031         Idx += Locs[i].first * 2 + Locs[i].second;
5032         Mask2[i] = Idx;
5033       }
5034     }
5035
5036     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5037   } else if (NumLo == 3 || NumHi == 3) {
5038     // Otherwise, we must have three elements from one vector, call it X, and
5039     // one element from the other, call it Y.  First, use a shufps to build an
5040     // intermediate vector with the one element from Y and the element from X
5041     // that will be in the same half in the final destination (the indexes don't
5042     // matter). Then, use a shufps to build the final vector, taking the half
5043     // containing the element from Y from the intermediate, and the other half
5044     // from X.
5045     if (NumHi == 3) {
5046       // Normalize it so the 3 elements come from V1.
5047       CommuteVectorShuffleMask(PermMask, VT);
5048       std::swap(V1, V2);
5049     }
5050
5051     // Find the element from V2.
5052     unsigned HiIndex;
5053     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5054       int Val = PermMask[HiIndex];
5055       if (Val < 0)
5056         continue;
5057       if (Val >= 4)
5058         break;
5059     }
5060
5061     Mask1[0] = PermMask[HiIndex];
5062     Mask1[1] = -1;
5063     Mask1[2] = PermMask[HiIndex^1];
5064     Mask1[3] = -1;
5065     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5066
5067     if (HiIndex >= 2) {
5068       Mask1[0] = PermMask[0];
5069       Mask1[1] = PermMask[1];
5070       Mask1[2] = HiIndex & 1 ? 6 : 4;
5071       Mask1[3] = HiIndex & 1 ? 4 : 6;
5072       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5073     } else {
5074       Mask1[0] = HiIndex & 1 ? 2 : 0;
5075       Mask1[1] = HiIndex & 1 ? 0 : 2;
5076       Mask1[2] = PermMask[2];
5077       Mask1[3] = PermMask[3];
5078       if (Mask1[2] >= 0)
5079         Mask1[2] += 4;
5080       if (Mask1[3] >= 0)
5081         Mask1[3] += 4;
5082       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5083     }
5084   }
5085
5086   // Break it into (shuffle shuffle_hi, shuffle_lo).
5087   Locs.clear();
5088   SmallVector<int,8> LoMask(4U, -1);
5089   SmallVector<int,8> HiMask(4U, -1);
5090
5091   SmallVector<int,8> *MaskPtr = &LoMask;
5092   unsigned MaskIdx = 0;
5093   unsigned LoIdx = 0;
5094   unsigned HiIdx = 2;
5095   for (unsigned i = 0; i != 4; ++i) {
5096     if (i == 2) {
5097       MaskPtr = &HiMask;
5098       MaskIdx = 1;
5099       LoIdx = 0;
5100       HiIdx = 2;
5101     }
5102     int Idx = PermMask[i];
5103     if (Idx < 0) {
5104       Locs[i] = std::make_pair(-1, -1);
5105     } else if (Idx < 4) {
5106       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5107       (*MaskPtr)[LoIdx] = Idx;
5108       LoIdx++;
5109     } else {
5110       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5111       (*MaskPtr)[HiIdx] = Idx;
5112       HiIdx++;
5113     }
5114   }
5115
5116   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5117   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5118   SmallVector<int, 8> MaskOps;
5119   for (unsigned i = 0; i != 4; ++i) {
5120     if (Locs[i].first == -1) {
5121       MaskOps.push_back(-1);
5122     } else {
5123       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5124       MaskOps.push_back(Idx);
5125     }
5126   }
5127   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5128 }
5129
5130 static bool MayFoldVectorLoad(SDValue V) {
5131   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5132     V = V.getOperand(0);
5133   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5134     V = V.getOperand(0);
5135   if (MayFoldLoad(V))
5136     return true;
5137   return false;
5138 }
5139
5140 // FIXME: the version above should always be used. Since there's
5141 // a bug where several vector shuffles can't be folded because the
5142 // DAG is not updated during lowering and a node claims to have two
5143 // uses while it only has one, use this version, and let isel match
5144 // another instruction if the load really happens to have more than
5145 // one use. Remove this version after this bug get fixed.
5146 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5147   if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5148     V = V.getOperand(0);
5149   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5150     V = V.getOperand(0);
5151   if (ISD::isNormalLoad(V.getNode()))
5152     return true;
5153   return false;
5154 }
5155
5156 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5157 /// a vector extract, and if both can be later optimized into a single load.
5158 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5159 /// here because otherwise a target specific shuffle node is going to be
5160 /// emitted for this shuffle, and the optimization not done.
5161 /// FIXME: This is probably not the best approach, but fix the problem
5162 /// until the right path is decided.
5163 static
5164 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5165                                          const TargetLowering &TLI) {
5166   EVT VT = V.getValueType();
5167   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5168
5169   // Be sure that the vector shuffle is present in a pattern like this:
5170   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5171   if (!V.hasOneUse())
5172     return false;
5173
5174   SDNode *N = *V.getNode()->use_begin();
5175   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5176     return false;
5177
5178   SDValue EltNo = N->getOperand(1);
5179   if (!isa<ConstantSDNode>(EltNo))
5180     return false;
5181
5182   // If the bit convert changed the number of elements, it is unsafe
5183   // to examine the mask.
5184   bool HasShuffleIntoBitcast = false;
5185   if (V.getOpcode() == ISD::BIT_CONVERT) {
5186     EVT SrcVT = V.getOperand(0).getValueType();
5187     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5188       return false;
5189     V = V.getOperand(0);
5190     HasShuffleIntoBitcast = true;
5191   }
5192
5193   // Select the input vector, guarding against out of range extract vector.
5194   unsigned NumElems = VT.getVectorNumElements();
5195   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5196   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5197   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5198
5199   // Skip one more bit_convert if necessary
5200   if (V.getOpcode() == ISD::BIT_CONVERT)
5201     V = V.getOperand(0);
5202
5203   if (ISD::isNormalLoad(V.getNode())) {
5204     // Is the original load suitable?
5205     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5206
5207     // FIXME: avoid the multi-use bug that is preventing lots of
5208     // of foldings to be detected, this is still wrong of course, but
5209     // give the temporary desired behavior, and if it happens that
5210     // the load has real more uses, during isel it will not fold, and
5211     // will generate poor code.
5212     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5213       return false;
5214
5215     if (!HasShuffleIntoBitcast)
5216       return true;
5217
5218     // If there's a bitcast before the shuffle, check if the load type and
5219     // alignment is valid.
5220     unsigned Align = LN0->getAlignment();
5221     unsigned NewAlign =
5222       TLI.getTargetData()->getABITypeAlignment(
5223                                     VT.getTypeForEVT(*DAG.getContext()));
5224
5225     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5226       return false;
5227   }
5228
5229   return true;
5230 }
5231
5232 static
5233 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5234                         bool HasSSE2) {
5235   SDValue V1 = Op.getOperand(0);
5236   SDValue V2 = Op.getOperand(1);
5237   EVT VT = Op.getValueType();
5238
5239   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5240
5241   if (HasSSE2 && VT == MVT::v2f64)
5242     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5243
5244   // v4f32 or v4i32
5245   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5246 }
5247
5248 static
5249 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5250   SDValue V1 = Op.getOperand(0);
5251   SDValue V2 = Op.getOperand(1);
5252   EVT VT = Op.getValueType();
5253
5254   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5255          "unsupported shuffle type");
5256
5257   if (V2.getOpcode() == ISD::UNDEF)
5258     V2 = V1;
5259
5260   // v4i32 or v4f32
5261   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5262 }
5263
5264 static
5265 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5266   SDValue V1 = Op.getOperand(0);
5267   SDValue V2 = Op.getOperand(1);
5268   EVT VT = Op.getValueType();
5269   unsigned NumElems = VT.getVectorNumElements();
5270
5271   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5272   // operand of these instructions is only memory, so check if there's a
5273   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5274   // same masks.
5275   bool CanFoldLoad = false;
5276
5277   // Trivial case, when V2 comes from a load.
5278   if (MayFoldVectorLoad(V2))
5279     CanFoldLoad = true;
5280
5281   // When V1 is a load, it can be folded later into a store in isel, example:
5282   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5283   //    turns into:
5284   //  (MOVLPSmr addr:$src1, VR128:$src2)
5285   // So, recognize this potential and also use MOVLPS or MOVLPD
5286   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5287     CanFoldLoad = true;
5288
5289   if (CanFoldLoad) {
5290     if (HasSSE2 && NumElems == 2)
5291       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5292
5293     if (NumElems == 4)
5294       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5295   }
5296
5297   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5298   // movl and movlp will both match v2i64, but v2i64 is never matched by
5299   // movl earlier because we make it strict to avoid messing with the movlp load
5300   // folding logic (see the code above getMOVLP call). Match it here then,
5301   // this is horrible, but will stay like this until we move all shuffle
5302   // matching to x86 specific nodes. Note that for the 1st condition all
5303   // types are matched with movsd.
5304   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5305     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5306   else if (HasSSE2)
5307     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5308
5309
5310   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5311
5312   // Invert the operand order and use SHUFPS to match it.
5313   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5314                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5315 }
5316
5317 static inline unsigned getUNPCKLOpcode(EVT VT) {
5318   switch(VT.getSimpleVT().SimpleTy) {
5319   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5320   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5321   case MVT::v4f32: return X86ISD::UNPCKLPS;
5322   case MVT::v2f64: return X86ISD::UNPCKLPD;
5323   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5324   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5325   default:
5326     llvm_unreachable("Unknow type for unpckl");
5327   }
5328   return 0;
5329 }
5330
5331 static inline unsigned getUNPCKHOpcode(EVT VT) {
5332   switch(VT.getSimpleVT().SimpleTy) {
5333   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5334   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5335   case MVT::v4f32: return X86ISD::UNPCKHPS;
5336   case MVT::v2f64: return X86ISD::UNPCKHPD;
5337   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5338   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5339   default:
5340     llvm_unreachable("Unknow type for unpckh");
5341   }
5342   return 0;
5343 }
5344
5345 static
5346 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5347                                const TargetLowering &TLI,
5348                                const X86Subtarget *Subtarget) {
5349   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5350   EVT VT = Op.getValueType();
5351   DebugLoc dl = Op.getDebugLoc();
5352   SDValue V1 = Op.getOperand(0);
5353   SDValue V2 = Op.getOperand(1);
5354
5355   if (isZeroShuffle(SVOp))
5356     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5357
5358   // Handle splat operations
5359   if (SVOp->isSplat()) {
5360     // Special case, this is the only place now where it's
5361     // allowed to return a vector_shuffle operation without
5362     // using a target specific node, because *hopefully* it
5363     // will be optimized away by the dag combiner.
5364     if (VT.getVectorNumElements() <= 4 &&
5365         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5366       return Op;
5367
5368     // Handle splats by matching through known masks
5369     if (VT.getVectorNumElements() <= 4)
5370       return SDValue();
5371
5372     // Canonize all of the remaining to v4f32.
5373     return PromoteSplat(SVOp, DAG);
5374   }
5375
5376   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5377   // do it!
5378   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5379     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5380     if (NewOp.getNode())
5381       return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5382   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5383     // FIXME: Figure out a cleaner way to do this.
5384     // Try to make use of movq to zero out the top part.
5385     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5386       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5387       if (NewOp.getNode()) {
5388         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5389           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5390                               DAG, Subtarget, dl);
5391       }
5392     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5393       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5394       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5395         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5396                             DAG, Subtarget, dl);
5397     }
5398   }
5399   return SDValue();
5400 }
5401
5402 SDValue
5403 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5404   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5405   SDValue V1 = Op.getOperand(0);
5406   SDValue V2 = Op.getOperand(1);
5407   EVT VT = Op.getValueType();
5408   DebugLoc dl = Op.getDebugLoc();
5409   unsigned NumElems = VT.getVectorNumElements();
5410   bool isMMX = VT.getSizeInBits() == 64;
5411   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5412   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5413   bool V1IsSplat = false;
5414   bool V2IsSplat = false;
5415   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5416   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5417   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5418   MachineFunction &MF = DAG.getMachineFunction();
5419   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5420
5421   // FIXME: this is somehow handled during isel by MMX pattern fragments. Remove
5422   // the check or come up with another solution when all MMX move to intrinsics,
5423   // but don't allow this to be considered legal, we don't want vector_shuffle
5424   // operations to be matched during isel anymore.
5425   if (isMMX && SVOp->isSplat())
5426     return Op;
5427
5428   // Vector shuffle lowering takes 3 steps:
5429   //
5430   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5431   //    narrowing and commutation of operands should be handled.
5432   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5433   //    shuffle nodes.
5434   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5435   //    so the shuffle can be broken into other shuffles and the legalizer can
5436   //    try the lowering again.
5437   //
5438   // The general ideia is that no vector_shuffle operation should be left to
5439   // be matched during isel, all of them must be converted to a target specific
5440   // node here.
5441
5442   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5443   // narrowing and commutation of operands should be handled. The actual code
5444   // doesn't include all of those, work in progress...
5445   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5446   if (NewOp.getNode())
5447     return NewOp;
5448
5449   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5450   // unpckh_undef). Only use pshufd if speed is more important than size.
5451   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5452     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5453       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5454   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5455     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5456       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5457
5458   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5459       RelaxedMayFoldVectorLoad(V1) && !isMMX)
5460     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
5461
5462   if (!isMMX && X86::isMOVHLPS_v_undef_Mask(SVOp))
5463     return getMOVHighToLow(Op, dl, DAG);
5464
5465   // Use to match splats
5466   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5467       (VT == MVT::v2f64 || VT == MVT::v2i64))
5468     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5469
5470   if (X86::isPSHUFDMask(SVOp)) {
5471     // The actual implementation will match the mask in the if above and then
5472     // during isel it can match several different instructions, not only pshufd
5473     // as its name says, sad but true, emulate the behavior for now...
5474     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5475         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5476
5477     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5478
5479     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5480       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5481
5482     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5483       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5484                                   TargetMask, DAG);
5485
5486     if (VT == MVT::v4f32)
5487       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5488                                   TargetMask, DAG);
5489   }
5490
5491   // Check if this can be converted into a logical shift.
5492   bool isLeft = false;
5493   unsigned ShAmt = 0;
5494   SDValue ShVal;
5495   bool isShift = getSubtarget()->hasSSE2() &&
5496     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5497   if (isShift && ShVal.hasOneUse()) {
5498     // If the shifted value has multiple uses, it may be cheaper to use
5499     // v_set0 + movlhps or movhlps, etc.
5500     EVT EltVT = VT.getVectorElementType();
5501     ShAmt *= EltVT.getSizeInBits();
5502     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5503   }
5504
5505   if (X86::isMOVLMask(SVOp)) {
5506     if (V1IsUndef)
5507       return V2;
5508     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5509       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5510     if (!isMMX && !X86::isMOVLPMask(SVOp)) {
5511       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5512         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5513
5514       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5515         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5516     }
5517   }
5518
5519   // FIXME: fold these into legal mask.
5520   if (!isMMX) {
5521     if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5522       return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5523
5524     if (X86::isMOVHLPSMask(SVOp))
5525       return getMOVHighToLow(Op, dl, DAG);
5526
5527     if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5528       return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5529
5530     if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5531       return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5532
5533     if (X86::isMOVLPMask(SVOp))
5534       return getMOVLP(Op, dl, DAG, HasSSE2);
5535   }
5536
5537   if (ShouldXformToMOVHLPS(SVOp) ||
5538       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5539     return CommuteVectorShuffle(SVOp, DAG);
5540
5541   if (isShift) {
5542     // No better options. Use a vshl / vsrl.
5543     EVT EltVT = VT.getVectorElementType();
5544     ShAmt *= EltVT.getSizeInBits();
5545     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5546   }
5547
5548   bool Commuted = false;
5549   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5550   // 1,1,1,1 -> v8i16 though.
5551   V1IsSplat = isSplatVector(V1.getNode());
5552   V2IsSplat = isSplatVector(V2.getNode());
5553
5554   // Canonicalize the splat or undef, if present, to be on the RHS.
5555   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5556     Op = CommuteVectorShuffle(SVOp, DAG);
5557     SVOp = cast<ShuffleVectorSDNode>(Op);
5558     V1 = SVOp->getOperand(0);
5559     V2 = SVOp->getOperand(1);
5560     std::swap(V1IsSplat, V2IsSplat);
5561     std::swap(V1IsUndef, V2IsUndef);
5562     Commuted = true;
5563   }
5564
5565   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5566     // Shuffling low element of v1 into undef, just return v1.
5567     if (V2IsUndef)
5568       return V1;
5569     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5570     // the instruction selector will not match, so get a canonical MOVL with
5571     // swapped operands to undo the commute.
5572     return getMOVL(DAG, dl, VT, V2, V1);
5573   }
5574
5575   if (X86::isUNPCKLMask(SVOp))
5576     return (isMMX) ?
5577       Op : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5578
5579   if (X86::isUNPCKHMask(SVOp))
5580     return (isMMX) ?
5581       Op : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5582
5583   if (V2IsSplat) {
5584     // Normalize mask so all entries that point to V2 points to its first
5585     // element then try to match unpck{h|l} again. If match, return a
5586     // new vector_shuffle with the corrected mask.
5587     SDValue NewMask = NormalizeMask(SVOp, DAG);
5588     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5589     if (NSVOp != SVOp) {
5590       if (X86::isUNPCKLMask(NSVOp, true)) {
5591         return NewMask;
5592       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5593         return NewMask;
5594       }
5595     }
5596   }
5597
5598   if (Commuted) {
5599     // Commute is back and try unpck* again.
5600     // FIXME: this seems wrong.
5601     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5602     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5603
5604     if (X86::isUNPCKLMask(NewSVOp))
5605       return (isMMX) ?
5606         NewOp : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5607
5608     if (X86::isUNPCKHMask(NewSVOp))
5609       return (isMMX) ?
5610         NewOp : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5611   }
5612
5613   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
5614
5615   // Normalize the node to match x86 shuffle ops if needed
5616   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5617     return CommuteVectorShuffle(SVOp, DAG);
5618
5619   // The checks below are all present in isShuffleMaskLegal, but they are
5620   // inlined here right now to enable us to directly emit target specific
5621   // nodes, and remove one by one until they don't return Op anymore.
5622   SmallVector<int, 16> M;
5623   SVOp->getMask(M);
5624
5625   if (isPALIGNRMask(M, VT, HasSSSE3))
5626     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5627                                 X86::getShufflePALIGNRImmediate(SVOp),
5628                                 DAG);
5629
5630   // Only a few shuffle masks are handled for 64-bit vectors (MMX), and
5631   // 64-bit vectors which made to this point can't be handled, they are
5632   // expanded.
5633   if (isMMX)
5634     return SDValue();
5635
5636   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5637       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5638     if (VT == MVT::v2f64)
5639       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5640     if (VT == MVT::v2i64)
5641       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5642   }
5643
5644   if (isPSHUFHWMask(M, VT))
5645     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5646                                 X86::getShufflePSHUFHWImmediate(SVOp),
5647                                 DAG);
5648
5649   if (isPSHUFLWMask(M, VT))
5650     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5651                                 X86::getShufflePSHUFLWImmediate(SVOp),
5652                                 DAG);
5653
5654   if (isSHUFPMask(M, VT)) {
5655     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5656     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5657       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5658                                   TargetMask, DAG);
5659     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5660       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5661                                   TargetMask, DAG);
5662   }
5663
5664   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5665     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5666       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5667   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5668     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5669       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5670
5671   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5672   if (VT == MVT::v8i16) {
5673     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5674     if (NewOp.getNode())
5675       return NewOp;
5676   }
5677
5678   if (VT == MVT::v16i8) {
5679     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5680     if (NewOp.getNode())
5681       return NewOp;
5682   }
5683
5684   // Handle all 4 wide cases with a number of shuffles except for MMX.
5685   if (NumElems == 4 && !isMMX)
5686     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5687
5688   return SDValue();
5689 }
5690
5691 SDValue
5692 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5693                                                 SelectionDAG &DAG) const {
5694   EVT VT = Op.getValueType();
5695   DebugLoc dl = Op.getDebugLoc();
5696   if (VT.getSizeInBits() == 8) {
5697     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5698                                     Op.getOperand(0), Op.getOperand(1));
5699     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5700                                     DAG.getValueType(VT));
5701     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5702   } else if (VT.getSizeInBits() == 16) {
5703     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5704     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5705     if (Idx == 0)
5706       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5707                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5708                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5709                                                  MVT::v4i32,
5710                                                  Op.getOperand(0)),
5711                                      Op.getOperand(1)));
5712     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5713                                     Op.getOperand(0), Op.getOperand(1));
5714     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5715                                     DAG.getValueType(VT));
5716     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5717   } else if (VT == MVT::f32) {
5718     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5719     // the result back to FR32 register. It's only worth matching if the
5720     // result has a single use which is a store or a bitcast to i32.  And in
5721     // the case of a store, it's not worth it if the index is a constant 0,
5722     // because a MOVSSmr can be used instead, which is smaller and faster.
5723     if (!Op.hasOneUse())
5724       return SDValue();
5725     SDNode *User = *Op.getNode()->use_begin();
5726     if ((User->getOpcode() != ISD::STORE ||
5727          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5728           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5729         (User->getOpcode() != ISD::BIT_CONVERT ||
5730          User->getValueType(0) != MVT::i32))
5731       return SDValue();
5732     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5733                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5734                                               Op.getOperand(0)),
5735                                               Op.getOperand(1));
5736     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5737   } else if (VT == MVT::i32) {
5738     // ExtractPS works with constant index.
5739     if (isa<ConstantSDNode>(Op.getOperand(1)))
5740       return Op;
5741   }
5742   return SDValue();
5743 }
5744
5745
5746 SDValue
5747 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5748                                            SelectionDAG &DAG) const {
5749   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5750     return SDValue();
5751
5752   if (Subtarget->hasSSE41()) {
5753     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5754     if (Res.getNode())
5755       return Res;
5756   }
5757
5758   EVT VT = Op.getValueType();
5759   DebugLoc dl = Op.getDebugLoc();
5760   // TODO: handle v16i8.
5761   if (VT.getSizeInBits() == 16) {
5762     SDValue Vec = Op.getOperand(0);
5763     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5764     if (Idx == 0)
5765       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5766                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5767                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5768                                                  MVT::v4i32, Vec),
5769                                      Op.getOperand(1)));
5770     // Transform it so it match pextrw which produces a 32-bit result.
5771     EVT EltVT = MVT::i32;
5772     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5773                                     Op.getOperand(0), Op.getOperand(1));
5774     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5775                                     DAG.getValueType(VT));
5776     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5777   } else if (VT.getSizeInBits() == 32) {
5778     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5779     if (Idx == 0)
5780       return Op;
5781
5782     // SHUFPS the element to the lowest double word, then movss.
5783     int Mask[4] = { Idx, -1, -1, -1 };
5784     EVT VVT = Op.getOperand(0).getValueType();
5785     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5786                                        DAG.getUNDEF(VVT), Mask);
5787     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5788                        DAG.getIntPtrConstant(0));
5789   } else if (VT.getSizeInBits() == 64) {
5790     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5791     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5792     //        to match extract_elt for f64.
5793     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5794     if (Idx == 0)
5795       return Op;
5796
5797     // UNPCKHPD the element to the lowest double word, then movsd.
5798     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5799     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5800     int Mask[2] = { 1, -1 };
5801     EVT VVT = Op.getOperand(0).getValueType();
5802     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5803                                        DAG.getUNDEF(VVT), Mask);
5804     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5805                        DAG.getIntPtrConstant(0));
5806   }
5807
5808   return SDValue();
5809 }
5810
5811 SDValue
5812 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5813                                                SelectionDAG &DAG) const {
5814   EVT VT = Op.getValueType();
5815   EVT EltVT = VT.getVectorElementType();
5816   DebugLoc dl = Op.getDebugLoc();
5817
5818   SDValue N0 = Op.getOperand(0);
5819   SDValue N1 = Op.getOperand(1);
5820   SDValue N2 = Op.getOperand(2);
5821
5822   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5823       isa<ConstantSDNode>(N2)) {
5824     unsigned Opc;
5825     if (VT == MVT::v8i16)
5826       Opc = X86ISD::PINSRW;
5827     else if (VT == MVT::v4i16)
5828       Opc = X86ISD::MMX_PINSRW;
5829     else if (VT == MVT::v16i8)
5830       Opc = X86ISD::PINSRB;
5831     else
5832       Opc = X86ISD::PINSRB;
5833
5834     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5835     // argument.
5836     if (N1.getValueType() != MVT::i32)
5837       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5838     if (N2.getValueType() != MVT::i32)
5839       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5840     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5841   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5842     // Bits [7:6] of the constant are the source select.  This will always be
5843     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5844     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5845     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5846     // Bits [5:4] of the constant are the destination select.  This is the
5847     //  value of the incoming immediate.
5848     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5849     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5850     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5851     // Create this as a scalar to vector..
5852     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5853     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5854   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5855     // PINSR* works with constant index.
5856     return Op;
5857   }
5858   return SDValue();
5859 }
5860
5861 SDValue
5862 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5863   EVT VT = Op.getValueType();
5864   EVT EltVT = VT.getVectorElementType();
5865
5866   if (Subtarget->hasSSE41())
5867     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5868
5869   if (EltVT == MVT::i8)
5870     return SDValue();
5871
5872   DebugLoc dl = Op.getDebugLoc();
5873   SDValue N0 = Op.getOperand(0);
5874   SDValue N1 = Op.getOperand(1);
5875   SDValue N2 = Op.getOperand(2);
5876
5877   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5878     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5879     // as its second argument.
5880     if (N1.getValueType() != MVT::i32)
5881       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5882     if (N2.getValueType() != MVT::i32)
5883       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5884     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5885                        dl, VT, N0, N1, N2);
5886   }
5887   return SDValue();
5888 }
5889
5890 SDValue
5891 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5892   DebugLoc dl = Op.getDebugLoc();
5893   
5894   if (Op.getValueType() == MVT::v1i64 &&
5895       Op.getOperand(0).getValueType() == MVT::i64)
5896     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5897
5898   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5899   EVT VT = MVT::v2i32;
5900   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5901   default: break;
5902   case MVT::v16i8:
5903   case MVT::v8i16:
5904     VT = MVT::v4i32;
5905     break;
5906   }
5907   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5908                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5909 }
5910
5911 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5912 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5913 // one of the above mentioned nodes. It has to be wrapped because otherwise
5914 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5915 // be used to form addressing mode. These wrapped nodes will be selected
5916 // into MOV32ri.
5917 SDValue
5918 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5919   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5920
5921   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5922   // global base reg.
5923   unsigned char OpFlag = 0;
5924   unsigned WrapperKind = X86ISD::Wrapper;
5925   CodeModel::Model M = getTargetMachine().getCodeModel();
5926
5927   if (Subtarget->isPICStyleRIPRel() &&
5928       (M == CodeModel::Small || M == CodeModel::Kernel))
5929     WrapperKind = X86ISD::WrapperRIP;
5930   else if (Subtarget->isPICStyleGOT())
5931     OpFlag = X86II::MO_GOTOFF;
5932   else if (Subtarget->isPICStyleStubPIC())
5933     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5934
5935   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5936                                              CP->getAlignment(),
5937                                              CP->getOffset(), OpFlag);
5938   DebugLoc DL = CP->getDebugLoc();
5939   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5940   // With PIC, the address is actually $g + Offset.
5941   if (OpFlag) {
5942     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5943                          DAG.getNode(X86ISD::GlobalBaseReg,
5944                                      DebugLoc(), getPointerTy()),
5945                          Result);
5946   }
5947
5948   return Result;
5949 }
5950
5951 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5952   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5953
5954   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5955   // global base reg.
5956   unsigned char OpFlag = 0;
5957   unsigned WrapperKind = X86ISD::Wrapper;
5958   CodeModel::Model M = getTargetMachine().getCodeModel();
5959
5960   if (Subtarget->isPICStyleRIPRel() &&
5961       (M == CodeModel::Small || M == CodeModel::Kernel))
5962     WrapperKind = X86ISD::WrapperRIP;
5963   else if (Subtarget->isPICStyleGOT())
5964     OpFlag = X86II::MO_GOTOFF;
5965   else if (Subtarget->isPICStyleStubPIC())
5966     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5967
5968   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5969                                           OpFlag);
5970   DebugLoc DL = JT->getDebugLoc();
5971   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5972
5973   // With PIC, the address is actually $g + Offset.
5974   if (OpFlag) {
5975     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5976                          DAG.getNode(X86ISD::GlobalBaseReg,
5977                                      DebugLoc(), getPointerTy()),
5978                          Result);
5979   }
5980
5981   return Result;
5982 }
5983
5984 SDValue
5985 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5986   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5987
5988   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5989   // global base reg.
5990   unsigned char OpFlag = 0;
5991   unsigned WrapperKind = X86ISD::Wrapper;
5992   CodeModel::Model M = getTargetMachine().getCodeModel();
5993
5994   if (Subtarget->isPICStyleRIPRel() &&
5995       (M == CodeModel::Small || M == CodeModel::Kernel))
5996     WrapperKind = X86ISD::WrapperRIP;
5997   else if (Subtarget->isPICStyleGOT())
5998     OpFlag = X86II::MO_GOTOFF;
5999   else if (Subtarget->isPICStyleStubPIC())
6000     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6001
6002   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6003
6004   DebugLoc DL = Op.getDebugLoc();
6005   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6006
6007
6008   // With PIC, the address is actually $g + Offset.
6009   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6010       !Subtarget->is64Bit()) {
6011     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6012                          DAG.getNode(X86ISD::GlobalBaseReg,
6013                                      DebugLoc(), getPointerTy()),
6014                          Result);
6015   }
6016
6017   return Result;
6018 }
6019
6020 SDValue
6021 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6022   // Create the TargetBlockAddressAddress node.
6023   unsigned char OpFlags =
6024     Subtarget->ClassifyBlockAddressReference();
6025   CodeModel::Model M = getTargetMachine().getCodeModel();
6026   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6027   DebugLoc dl = Op.getDebugLoc();
6028   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6029                                        /*isTarget=*/true, OpFlags);
6030
6031   if (Subtarget->isPICStyleRIPRel() &&
6032       (M == CodeModel::Small || M == CodeModel::Kernel))
6033     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6034   else
6035     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6036
6037   // With PIC, the address is actually $g + Offset.
6038   if (isGlobalRelativeToPICBase(OpFlags)) {
6039     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6040                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6041                          Result);
6042   }
6043
6044   return Result;
6045 }
6046
6047 SDValue
6048 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6049                                       int64_t Offset,
6050                                       SelectionDAG &DAG) const {
6051   // Create the TargetGlobalAddress node, folding in the constant
6052   // offset if it is legal.
6053   unsigned char OpFlags =
6054     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6055   CodeModel::Model M = getTargetMachine().getCodeModel();
6056   SDValue Result;
6057   if (OpFlags == X86II::MO_NO_FLAG &&
6058       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6059     // A direct static reference to a global.
6060     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6061     Offset = 0;
6062   } else {
6063     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6064   }
6065
6066   if (Subtarget->isPICStyleRIPRel() &&
6067       (M == CodeModel::Small || M == CodeModel::Kernel))
6068     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6069   else
6070     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6071
6072   // With PIC, the address is actually $g + Offset.
6073   if (isGlobalRelativeToPICBase(OpFlags)) {
6074     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6075                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6076                          Result);
6077   }
6078
6079   // For globals that require a load from a stub to get the address, emit the
6080   // load.
6081   if (isGlobalStubReference(OpFlags))
6082     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6083                          MachinePointerInfo::getGOT(), false, false, 0);
6084
6085   // If there was a non-zero offset that we didn't fold, create an explicit
6086   // addition for it.
6087   if (Offset != 0)
6088     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6089                          DAG.getConstant(Offset, getPointerTy()));
6090
6091   return Result;
6092 }
6093
6094 SDValue
6095 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6096   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6097   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6098   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6099 }
6100
6101 static SDValue
6102 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6103            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6104            unsigned char OperandFlags) {
6105   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6106   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6107   DebugLoc dl = GA->getDebugLoc();
6108   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6109                                            GA->getValueType(0),
6110                                            GA->getOffset(),
6111                                            OperandFlags);
6112   if (InFlag) {
6113     SDValue Ops[] = { Chain,  TGA, *InFlag };
6114     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6115   } else {
6116     SDValue Ops[]  = { Chain, TGA };
6117     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6118   }
6119
6120   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6121   MFI->setAdjustsStack(true);
6122
6123   SDValue Flag = Chain.getValue(1);
6124   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6125 }
6126
6127 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6128 static SDValue
6129 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6130                                 const EVT PtrVT) {
6131   SDValue InFlag;
6132   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6133   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6134                                      DAG.getNode(X86ISD::GlobalBaseReg,
6135                                                  DebugLoc(), PtrVT), InFlag);
6136   InFlag = Chain.getValue(1);
6137
6138   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6139 }
6140
6141 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6142 static SDValue
6143 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6144                                 const EVT PtrVT) {
6145   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6146                     X86::RAX, X86II::MO_TLSGD);
6147 }
6148
6149 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6150 // "local exec" model.
6151 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6152                                    const EVT PtrVT, TLSModel::Model model,
6153                                    bool is64Bit) {
6154   DebugLoc dl = GA->getDebugLoc();
6155   
6156   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6157   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6158                                                          is64Bit ? 257 : 256));
6159
6160   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 
6161                                       DAG.getIntPtrConstant(0),
6162                                       MachinePointerInfo(Ptr), false, false, 0);
6163
6164   unsigned char OperandFlags = 0;
6165   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6166   // initialexec.
6167   unsigned WrapperKind = X86ISD::Wrapper;
6168   if (model == TLSModel::LocalExec) {
6169     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6170   } else if (is64Bit) {
6171     assert(model == TLSModel::InitialExec);
6172     OperandFlags = X86II::MO_GOTTPOFF;
6173     WrapperKind = X86ISD::WrapperRIP;
6174   } else {
6175     assert(model == TLSModel::InitialExec);
6176     OperandFlags = X86II::MO_INDNTPOFF;
6177   }
6178
6179   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6180   // exec)
6181   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 
6182                                            GA->getValueType(0),
6183                                            GA->getOffset(), OperandFlags);
6184   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6185
6186   if (model == TLSModel::InitialExec)
6187     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6188                          MachinePointerInfo::getGOT(), false, false, 0);
6189
6190   // The address of the thread local variable is the add of the thread
6191   // pointer with the offset of the variable.
6192   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6193 }
6194
6195 SDValue
6196 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6197   
6198   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6199   const GlobalValue *GV = GA->getGlobal();
6200
6201   if (Subtarget->isTargetELF()) {
6202     // TODO: implement the "local dynamic" model
6203     // TODO: implement the "initial exec"model for pic executables
6204     
6205     // If GV is an alias then use the aliasee for determining
6206     // thread-localness.
6207     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6208       GV = GA->resolveAliasedGlobal(false);
6209     
6210     TLSModel::Model model 
6211       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6212     
6213     switch (model) {
6214       case TLSModel::GeneralDynamic:
6215       case TLSModel::LocalDynamic: // not implemented
6216         if (Subtarget->is64Bit())
6217           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6218         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6219         
6220       case TLSModel::InitialExec:
6221       case TLSModel::LocalExec:
6222         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6223                                    Subtarget->is64Bit());
6224     }
6225   } else if (Subtarget->isTargetDarwin()) {
6226     // Darwin only has one model of TLS.  Lower to that.
6227     unsigned char OpFlag = 0;
6228     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6229                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6230     
6231     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6232     // global base reg.
6233     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6234                   !Subtarget->is64Bit();
6235     if (PIC32)
6236       OpFlag = X86II::MO_TLVP_PIC_BASE;
6237     else
6238       OpFlag = X86II::MO_TLVP;
6239     DebugLoc DL = Op.getDebugLoc();    
6240     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6241                                                 getPointerTy(),
6242                                                 GA->getOffset(), OpFlag);
6243     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6244   
6245     // With PIC32, the address is actually $g + Offset.
6246     if (PIC32)
6247       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6248                            DAG.getNode(X86ISD::GlobalBaseReg,
6249                                        DebugLoc(), getPointerTy()),
6250                            Offset);
6251     
6252     // Lowering the machine isd will make sure everything is in the right
6253     // location.
6254     SDValue Args[] = { Offset };
6255     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6256     
6257     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6258     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6259     MFI->setAdjustsStack(true);
6260
6261     // And our return value (tls address) is in the standard call return value
6262     // location.
6263     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6264     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6265   }
6266   
6267   assert(false &&
6268          "TLS not implemented for this target.");
6269
6270   llvm_unreachable("Unreachable");
6271   return SDValue();
6272 }
6273
6274
6275 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6276 /// take a 2 x i32 value to shift plus a shift amount.
6277 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6278   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6279   EVT VT = Op.getValueType();
6280   unsigned VTBits = VT.getSizeInBits();
6281   DebugLoc dl = Op.getDebugLoc();
6282   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6283   SDValue ShOpLo = Op.getOperand(0);
6284   SDValue ShOpHi = Op.getOperand(1);
6285   SDValue ShAmt  = Op.getOperand(2);
6286   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6287                                      DAG.getConstant(VTBits - 1, MVT::i8))
6288                        : DAG.getConstant(0, VT);
6289
6290   SDValue Tmp2, Tmp3;
6291   if (Op.getOpcode() == ISD::SHL_PARTS) {
6292     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6293     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6294   } else {
6295     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6296     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6297   }
6298
6299   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6300                                 DAG.getConstant(VTBits, MVT::i8));
6301   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6302                              AndNode, DAG.getConstant(0, MVT::i8));
6303
6304   SDValue Hi, Lo;
6305   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6306   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6307   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6308
6309   if (Op.getOpcode() == ISD::SHL_PARTS) {
6310     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6311     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6312   } else {
6313     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6314     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6315   }
6316
6317   SDValue Ops[2] = { Lo, Hi };
6318   return DAG.getMergeValues(Ops, 2, dl);
6319 }
6320
6321 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6322                                            SelectionDAG &DAG) const {
6323   EVT SrcVT = Op.getOperand(0).getValueType();
6324
6325   if (SrcVT.isVector()) {
6326     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64)
6327       return Op;
6328     return SDValue();
6329   }
6330
6331   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6332          "Unknown SINT_TO_FP to lower!");
6333
6334   // These are really Legal; return the operand so the caller accepts it as
6335   // Legal.
6336   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6337     return Op;
6338   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6339       Subtarget->is64Bit()) {
6340     return Op;
6341   }
6342
6343   DebugLoc dl = Op.getDebugLoc();
6344   unsigned Size = SrcVT.getSizeInBits()/8;
6345   MachineFunction &MF = DAG.getMachineFunction();
6346   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6347   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6348   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6349                                StackSlot,
6350                                MachinePointerInfo::getFixedStack(SSFI),
6351                                false, false, 0);
6352   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6353 }
6354
6355 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6356                                      SDValue StackSlot, 
6357                                      SelectionDAG &DAG) const {
6358   // Build the FILD
6359   DebugLoc DL = Op.getDebugLoc();
6360   SDVTList Tys;
6361   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6362   if (useSSE)
6363     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6364   else
6365     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6366   
6367   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6368   
6369   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6370   MachineMemOperand *MMO =
6371     DAG.getMachineFunction()
6372     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6373                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6374   
6375   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6376   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6377                                            X86ISD::FILD, DL,
6378                                            Tys, Ops, array_lengthof(Ops),
6379                                            SrcVT, MMO);
6380
6381   if (useSSE) {
6382     Chain = Result.getValue(1);
6383     SDValue InFlag = Result.getValue(2);
6384
6385     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6386     // shouldn't be necessary except that RFP cannot be live across
6387     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6388     MachineFunction &MF = DAG.getMachineFunction();
6389     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6390     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6391     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6392     Tys = DAG.getVTList(MVT::Other);
6393     SDValue Ops[] = {
6394       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6395     };
6396     MachineMemOperand *MMO =
6397       DAG.getMachineFunction()
6398       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6399                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6400     
6401     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6402                                     Ops, array_lengthof(Ops),
6403                                     Op.getValueType(), MMO);
6404     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6405                          MachinePointerInfo::getFixedStack(SSFI),
6406                          false, false, 0);
6407   }
6408
6409   return Result;
6410 }
6411
6412 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6413 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6414                                                SelectionDAG &DAG) const {
6415   // This algorithm is not obvious. Here it is in C code, more or less:
6416   /*
6417     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6418       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6419       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6420
6421       // Copy ints to xmm registers.
6422       __m128i xh = _mm_cvtsi32_si128( hi );
6423       __m128i xl = _mm_cvtsi32_si128( lo );
6424
6425       // Combine into low half of a single xmm register.
6426       __m128i x = _mm_unpacklo_epi32( xh, xl );
6427       __m128d d;
6428       double sd;
6429
6430       // Merge in appropriate exponents to give the integer bits the right
6431       // magnitude.
6432       x = _mm_unpacklo_epi32( x, exp );
6433
6434       // Subtract away the biases to deal with the IEEE-754 double precision
6435       // implicit 1.
6436       d = _mm_sub_pd( (__m128d) x, bias );
6437
6438       // All conversions up to here are exact. The correctly rounded result is
6439       // calculated using the current rounding mode using the following
6440       // horizontal add.
6441       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6442       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6443                                 // store doesn't really need to be here (except
6444                                 // maybe to zero the other double)
6445       return sd;
6446     }
6447   */
6448
6449   DebugLoc dl = Op.getDebugLoc();
6450   LLVMContext *Context = DAG.getContext();
6451
6452   // Build some magic constants.
6453   std::vector<Constant*> CV0;
6454   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6455   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6456   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6457   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6458   Constant *C0 = ConstantVector::get(CV0);
6459   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6460
6461   std::vector<Constant*> CV1;
6462   CV1.push_back(
6463     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6464   CV1.push_back(
6465     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6466   Constant *C1 = ConstantVector::get(CV1);
6467   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6468
6469   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6470                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6471                                         Op.getOperand(0),
6472                                         DAG.getIntPtrConstant(1)));
6473   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6474                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6475                                         Op.getOperand(0),
6476                                         DAG.getIntPtrConstant(0)));
6477   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6478   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6479                               MachinePointerInfo::getConstantPool(),
6480                               false, false, 16);
6481   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6482   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6483   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6484                               MachinePointerInfo::getConstantPool(),
6485                               false, false, 16);
6486   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6487
6488   // Add the halves; easiest way is to swap them into another reg first.
6489   int ShufMask[2] = { 1, -1 };
6490   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6491                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6492   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6493   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6494                      DAG.getIntPtrConstant(0));
6495 }
6496
6497 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6498 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6499                                                SelectionDAG &DAG) const {
6500   DebugLoc dl = Op.getDebugLoc();
6501   // FP constant to bias correct the final result.
6502   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6503                                    MVT::f64);
6504
6505   // Load the 32-bit value into an XMM register.
6506   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6507                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6508                                          Op.getOperand(0),
6509                                          DAG.getIntPtrConstant(0)));
6510
6511   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6512                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6513                      DAG.getIntPtrConstant(0));
6514
6515   // Or the load with the bias.
6516   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6517                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6518                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6519                                                    MVT::v2f64, Load)),
6520                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6521                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6522                                                    MVT::v2f64, Bias)));
6523   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6524                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6525                    DAG.getIntPtrConstant(0));
6526
6527   // Subtract the bias.
6528   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6529
6530   // Handle final rounding.
6531   EVT DestVT = Op.getValueType();
6532
6533   if (DestVT.bitsLT(MVT::f64)) {
6534     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6535                        DAG.getIntPtrConstant(0));
6536   } else if (DestVT.bitsGT(MVT::f64)) {
6537     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6538   }
6539
6540   // Handle final rounding.
6541   return Sub;
6542 }
6543
6544 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6545                                            SelectionDAG &DAG) const {
6546   SDValue N0 = Op.getOperand(0);
6547   DebugLoc dl = Op.getDebugLoc();
6548
6549   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6550   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6551   // the optimization here.
6552   if (DAG.SignBitIsZero(N0))
6553     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6554
6555   EVT SrcVT = N0.getValueType();
6556   EVT DstVT = Op.getValueType();
6557   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6558     return LowerUINT_TO_FP_i64(Op, DAG);
6559   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6560     return LowerUINT_TO_FP_i32(Op, DAG);
6561
6562   // Make a 64-bit buffer, and use it to build an FILD.
6563   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6564   if (SrcVT == MVT::i32) {
6565     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6566     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6567                                      getPointerTy(), StackSlot, WordOff);
6568     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6569                                   StackSlot, MachinePointerInfo(),
6570                                   false, false, 0);
6571     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6572                                   OffsetSlot, MachinePointerInfo(),
6573                                   false, false, 0);
6574     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6575     return Fild;
6576   }
6577
6578   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6579   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6580                                 StackSlot, MachinePointerInfo(),
6581                                false, false, 0);
6582   // For i64 source, we need to add the appropriate power of 2 if the input
6583   // was negative.  This is the same as the optimization in
6584   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6585   // we must be careful to do the computation in x87 extended precision, not
6586   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6587   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6588   MachineMemOperand *MMO =
6589     DAG.getMachineFunction()
6590     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6591                           MachineMemOperand::MOLoad, 8, 8);
6592   
6593   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6594   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6595   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6596                                          MVT::i64, MMO);
6597
6598   APInt FF(32, 0x5F800000ULL);
6599
6600   // Check whether the sign bit is set.
6601   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6602                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6603                                  ISD::SETLT);
6604
6605   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6606   SDValue FudgePtr = DAG.getConstantPool(
6607                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6608                                          getPointerTy());
6609
6610   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6611   SDValue Zero = DAG.getIntPtrConstant(0);
6612   SDValue Four = DAG.getIntPtrConstant(4);
6613   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6614                                Zero, Four);
6615   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6616
6617   // Load the value out, extending it from f32 to f80.
6618   // FIXME: Avoid the extend by constructing the right constant pool?
6619   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6620                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6621                                  MVT::f32, false, false, 4);
6622   // Extend everything to 80 bits to force it to be done on x87.
6623   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6624   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6625 }
6626
6627 std::pair<SDValue,SDValue> X86TargetLowering::
6628 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6629   DebugLoc DL = Op.getDebugLoc();
6630
6631   EVT DstTy = Op.getValueType();
6632
6633   if (!IsSigned) {
6634     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6635     DstTy = MVT::i64;
6636   }
6637
6638   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6639          DstTy.getSimpleVT() >= MVT::i16 &&
6640          "Unknown FP_TO_SINT to lower!");
6641
6642   // These are really Legal.
6643   if (DstTy == MVT::i32 &&
6644       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6645     return std::make_pair(SDValue(), SDValue());
6646   if (Subtarget->is64Bit() &&
6647       DstTy == MVT::i64 &&
6648       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6649     return std::make_pair(SDValue(), SDValue());
6650
6651   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6652   // stack slot.
6653   MachineFunction &MF = DAG.getMachineFunction();
6654   unsigned MemSize = DstTy.getSizeInBits()/8;
6655   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6656   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6657
6658   
6659   
6660   unsigned Opc;
6661   switch (DstTy.getSimpleVT().SimpleTy) {
6662   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6663   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6664   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6665   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6666   }
6667
6668   SDValue Chain = DAG.getEntryNode();
6669   SDValue Value = Op.getOperand(0);
6670   EVT TheVT = Op.getOperand(0).getValueType();
6671   if (isScalarFPTypeInSSEReg(TheVT)) {
6672     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6673     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6674                          MachinePointerInfo::getFixedStack(SSFI),
6675                          false, false, 0);
6676     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6677     SDValue Ops[] = {
6678       Chain, StackSlot, DAG.getValueType(TheVT)
6679     };
6680     
6681     MachineMemOperand *MMO =
6682       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6683                               MachineMemOperand::MOLoad, MemSize, MemSize);
6684     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6685                                     DstTy, MMO);
6686     Chain = Value.getValue(1);
6687     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6688     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6689   }
6690   
6691   MachineMemOperand *MMO =
6692     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6693                             MachineMemOperand::MOStore, MemSize, MemSize);
6694
6695   // Build the FP_TO_INT*_IN_MEM
6696   SDValue Ops[] = { Chain, Value, StackSlot };
6697   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6698                                          Ops, 3, DstTy, MMO);
6699
6700   return std::make_pair(FIST, StackSlot);
6701 }
6702
6703 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6704                                            SelectionDAG &DAG) const {
6705   if (Op.getValueType().isVector()) {
6706     if (Op.getValueType() == MVT::v2i32 &&
6707         Op.getOperand(0).getValueType() == MVT::v2f64) {
6708       return Op;
6709     }
6710     return SDValue();
6711   }
6712
6713   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6714   SDValue FIST = Vals.first, StackSlot = Vals.second;
6715   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6716   if (FIST.getNode() == 0) return Op;
6717
6718   // Load the result.
6719   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6720                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6721 }
6722
6723 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6724                                            SelectionDAG &DAG) const {
6725   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6726   SDValue FIST = Vals.first, StackSlot = Vals.second;
6727   assert(FIST.getNode() && "Unexpected failure");
6728
6729   // Load the result.
6730   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6731                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6732 }
6733
6734 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6735                                      SelectionDAG &DAG) const {
6736   LLVMContext *Context = DAG.getContext();
6737   DebugLoc dl = Op.getDebugLoc();
6738   EVT VT = Op.getValueType();
6739   EVT EltVT = VT;
6740   if (VT.isVector())
6741     EltVT = VT.getVectorElementType();
6742   std::vector<Constant*> CV;
6743   if (EltVT == MVT::f64) {
6744     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6745     CV.push_back(C);
6746     CV.push_back(C);
6747   } else {
6748     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6749     CV.push_back(C);
6750     CV.push_back(C);
6751     CV.push_back(C);
6752     CV.push_back(C);
6753   }
6754   Constant *C = ConstantVector::get(CV);
6755   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6756   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6757                              MachinePointerInfo::getConstantPool(),
6758                              false, false, 16);
6759   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6760 }
6761
6762 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6763   LLVMContext *Context = DAG.getContext();
6764   DebugLoc dl = Op.getDebugLoc();
6765   EVT VT = Op.getValueType();
6766   EVT EltVT = VT;
6767   if (VT.isVector())
6768     EltVT = VT.getVectorElementType();
6769   std::vector<Constant*> CV;
6770   if (EltVT == MVT::f64) {
6771     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6772     CV.push_back(C);
6773     CV.push_back(C);
6774   } else {
6775     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6776     CV.push_back(C);
6777     CV.push_back(C);
6778     CV.push_back(C);
6779     CV.push_back(C);
6780   }
6781   Constant *C = ConstantVector::get(CV);
6782   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6783   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6784                              MachinePointerInfo::getConstantPool(),
6785                              false, false, 16);
6786   if (VT.isVector()) {
6787     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6788                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6789                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6790                                 Op.getOperand(0)),
6791                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6792   } else {
6793     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6794   }
6795 }
6796
6797 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6798   LLVMContext *Context = DAG.getContext();
6799   SDValue Op0 = Op.getOperand(0);
6800   SDValue Op1 = Op.getOperand(1);
6801   DebugLoc dl = Op.getDebugLoc();
6802   EVT VT = Op.getValueType();
6803   EVT SrcVT = Op1.getValueType();
6804
6805   // If second operand is smaller, extend it first.
6806   if (SrcVT.bitsLT(VT)) {
6807     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6808     SrcVT = VT;
6809   }
6810   // And if it is bigger, shrink it first.
6811   if (SrcVT.bitsGT(VT)) {
6812     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6813     SrcVT = VT;
6814   }
6815
6816   // At this point the operands and the result should have the same
6817   // type, and that won't be f80 since that is not custom lowered.
6818
6819   // First get the sign bit of second operand.
6820   std::vector<Constant*> CV;
6821   if (SrcVT == MVT::f64) {
6822     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6823     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6824   } else {
6825     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6826     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6827     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6828     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6829   }
6830   Constant *C = ConstantVector::get(CV);
6831   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6832   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6833                               MachinePointerInfo::getConstantPool(),
6834                               false, false, 16);
6835   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6836
6837   // Shift sign bit right or left if the two operands have different types.
6838   if (SrcVT.bitsGT(VT)) {
6839     // Op0 is MVT::f32, Op1 is MVT::f64.
6840     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6841     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6842                           DAG.getConstant(32, MVT::i32));
6843     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6844     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6845                           DAG.getIntPtrConstant(0));
6846   }
6847
6848   // Clear first operand sign bit.
6849   CV.clear();
6850   if (VT == MVT::f64) {
6851     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6852     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6853   } else {
6854     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6855     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6856     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6857     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6858   }
6859   C = ConstantVector::get(CV);
6860   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6861   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6862                               MachinePointerInfo::getConstantPool(),
6863                               false, false, 16);
6864   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6865
6866   // Or the value with the sign bit.
6867   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6868 }
6869
6870 /// Emit nodes that will be selected as "test Op0,Op0", or something
6871 /// equivalent.
6872 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6873                                     SelectionDAG &DAG) const {
6874   DebugLoc dl = Op.getDebugLoc();
6875
6876   // CF and OF aren't always set the way we want. Determine which
6877   // of these we need.
6878   bool NeedCF = false;
6879   bool NeedOF = false;
6880   switch (X86CC) {
6881   default: break;
6882   case X86::COND_A: case X86::COND_AE:
6883   case X86::COND_B: case X86::COND_BE:
6884     NeedCF = true;
6885     break;
6886   case X86::COND_G: case X86::COND_GE:
6887   case X86::COND_L: case X86::COND_LE:
6888   case X86::COND_O: case X86::COND_NO:
6889     NeedOF = true;
6890     break;
6891   }
6892
6893   // See if we can use the EFLAGS value from the operand instead of
6894   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6895   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6896   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6897     // Emit a CMP with 0, which is the TEST pattern.
6898     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6899                        DAG.getConstant(0, Op.getValueType()));
6900
6901   unsigned Opcode = 0;
6902   unsigned NumOperands = 0;
6903   switch (Op.getNode()->getOpcode()) {
6904   case ISD::ADD:
6905     // Due to an isel shortcoming, be conservative if this add is likely to be
6906     // selected as part of a load-modify-store instruction. When the root node
6907     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6908     // uses of other nodes in the match, such as the ADD in this case. This
6909     // leads to the ADD being left around and reselected, with the result being
6910     // two adds in the output.  Alas, even if none our users are stores, that
6911     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6912     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6913     // climbing the DAG back to the root, and it doesn't seem to be worth the
6914     // effort.
6915     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6916            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6917       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6918         goto default_case;
6919
6920     if (ConstantSDNode *C =
6921         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6922       // An add of one will be selected as an INC.
6923       if (C->getAPIntValue() == 1) {
6924         Opcode = X86ISD::INC;
6925         NumOperands = 1;
6926         break;
6927       }
6928
6929       // An add of negative one (subtract of one) will be selected as a DEC.
6930       if (C->getAPIntValue().isAllOnesValue()) {
6931         Opcode = X86ISD::DEC;
6932         NumOperands = 1;
6933         break;
6934       }
6935     }
6936
6937     // Otherwise use a regular EFLAGS-setting add.
6938     Opcode = X86ISD::ADD;
6939     NumOperands = 2;
6940     break;
6941   case ISD::AND: {
6942     // If the primary and result isn't used, don't bother using X86ISD::AND,
6943     // because a TEST instruction will be better.
6944     bool NonFlagUse = false;
6945     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6946            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6947       SDNode *User = *UI;
6948       unsigned UOpNo = UI.getOperandNo();
6949       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6950         // Look pass truncate.
6951         UOpNo = User->use_begin().getOperandNo();
6952         User = *User->use_begin();
6953       }
6954
6955       if (User->getOpcode() != ISD::BRCOND &&
6956           User->getOpcode() != ISD::SETCC &&
6957           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6958         NonFlagUse = true;
6959         break;
6960       }
6961     }
6962
6963     if (!NonFlagUse)
6964       break;
6965   }
6966     // FALL THROUGH
6967   case ISD::SUB:
6968   case ISD::OR:
6969   case ISD::XOR:
6970     // Due to the ISEL shortcoming noted above, be conservative if this op is
6971     // likely to be selected as part of a load-modify-store instruction.
6972     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6973            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6974       if (UI->getOpcode() == ISD::STORE)
6975         goto default_case;
6976
6977     // Otherwise use a regular EFLAGS-setting instruction.
6978     switch (Op.getNode()->getOpcode()) {
6979     default: llvm_unreachable("unexpected operator!");
6980     case ISD::SUB: Opcode = X86ISD::SUB; break;
6981     case ISD::OR:  Opcode = X86ISD::OR;  break;
6982     case ISD::XOR: Opcode = X86ISD::XOR; break;
6983     case ISD::AND: Opcode = X86ISD::AND; break;
6984     }
6985
6986     NumOperands = 2;
6987     break;
6988   case X86ISD::ADD:
6989   case X86ISD::SUB:
6990   case X86ISD::INC:
6991   case X86ISD::DEC:
6992   case X86ISD::OR:
6993   case X86ISD::XOR:
6994   case X86ISD::AND:
6995     return SDValue(Op.getNode(), 1);
6996   default:
6997   default_case:
6998     break;
6999   }
7000
7001   if (Opcode == 0)
7002     // Emit a CMP with 0, which is the TEST pattern.
7003     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7004                        DAG.getConstant(0, Op.getValueType()));
7005
7006   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7007   SmallVector<SDValue, 4> Ops;
7008   for (unsigned i = 0; i != NumOperands; ++i)
7009     Ops.push_back(Op.getOperand(i));
7010
7011   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7012   DAG.ReplaceAllUsesWith(Op, New);
7013   return SDValue(New.getNode(), 1);
7014 }
7015
7016 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7017 /// equivalent.
7018 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7019                                    SelectionDAG &DAG) const {
7020   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7021     if (C->getAPIntValue() == 0)
7022       return EmitTest(Op0, X86CC, DAG);
7023
7024   DebugLoc dl = Op0.getDebugLoc();
7025   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7026 }
7027
7028 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7029 /// if it's possible.
7030 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7031                                      DebugLoc dl, SelectionDAG &DAG) const {
7032   SDValue Op0 = And.getOperand(0);
7033   SDValue Op1 = And.getOperand(1);
7034   if (Op0.getOpcode() == ISD::TRUNCATE)
7035     Op0 = Op0.getOperand(0);
7036   if (Op1.getOpcode() == ISD::TRUNCATE)
7037     Op1 = Op1.getOperand(0);
7038
7039   SDValue LHS, RHS;
7040   if (Op1.getOpcode() == ISD::SHL)
7041     std::swap(Op0, Op1);
7042   if (Op0.getOpcode() == ISD::SHL) {
7043     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7044       if (And00C->getZExtValue() == 1) {
7045         // If we looked past a truncate, check that it's only truncating away
7046         // known zeros.
7047         unsigned BitWidth = Op0.getValueSizeInBits();
7048         unsigned AndBitWidth = And.getValueSizeInBits();
7049         if (BitWidth > AndBitWidth) {
7050           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7051           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7052           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7053             return SDValue();
7054         }
7055         LHS = Op1;
7056         RHS = Op0.getOperand(1);
7057       }
7058   } else if (Op1.getOpcode() == ISD::Constant) {
7059     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7060     SDValue AndLHS = Op0;
7061     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7062       LHS = AndLHS.getOperand(0);
7063       RHS = AndLHS.getOperand(1);
7064     }
7065   }
7066
7067   if (LHS.getNode()) {
7068     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7069     // instruction.  Since the shift amount is in-range-or-undefined, we know
7070     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7071     // the encoding for the i16 version is larger than the i32 version.
7072     // Also promote i16 to i32 for performance / code size reason.
7073     if (LHS.getValueType() == MVT::i8 ||
7074         LHS.getValueType() == MVT::i16)
7075       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7076
7077     // If the operand types disagree, extend the shift amount to match.  Since
7078     // BT ignores high bits (like shifts) we can use anyextend.
7079     if (LHS.getValueType() != RHS.getValueType())
7080       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7081
7082     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7083     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7084     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7085                        DAG.getConstant(Cond, MVT::i8), BT);
7086   }
7087
7088   return SDValue();
7089 }
7090
7091 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7092   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7093   SDValue Op0 = Op.getOperand(0);
7094   SDValue Op1 = Op.getOperand(1);
7095   DebugLoc dl = Op.getDebugLoc();
7096   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7097
7098   // Optimize to BT if possible.
7099   // Lower (X & (1 << N)) == 0 to BT(X, N).
7100   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7101   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7102   if (Op0.getOpcode() == ISD::AND &&
7103       Op0.hasOneUse() &&
7104       Op1.getOpcode() == ISD::Constant &&
7105       cast<ConstantSDNode>(Op1)->isNullValue() &&
7106       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7107     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7108     if (NewSetCC.getNode())
7109       return NewSetCC;
7110   }
7111
7112   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7113   if (Op0.getOpcode() == X86ISD::SETCC &&
7114       Op1.getOpcode() == ISD::Constant &&
7115       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7116        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7117       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7118     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7119     bool Invert = (CC == ISD::SETNE) ^
7120       cast<ConstantSDNode>(Op1)->isNullValue();
7121     if (Invert)
7122       CCode = X86::GetOppositeBranchCondition(CCode);
7123     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7124                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7125   }
7126
7127   bool isFP = Op1.getValueType().isFloatingPoint();
7128   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7129   if (X86CC == X86::COND_INVALID)
7130     return SDValue();
7131
7132   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7133
7134   // Use sbb x, x to materialize carry bit into a GPR.
7135   if (X86CC == X86::COND_B)
7136     return DAG.getNode(ISD::AND, dl, MVT::i8,
7137                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7138                                    DAG.getConstant(X86CC, MVT::i8), Cond),
7139                        DAG.getConstant(1, MVT::i8));
7140
7141   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7142                      DAG.getConstant(X86CC, MVT::i8), Cond);
7143 }
7144
7145 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7146   SDValue Cond;
7147   SDValue Op0 = Op.getOperand(0);
7148   SDValue Op1 = Op.getOperand(1);
7149   SDValue CC = Op.getOperand(2);
7150   EVT VT = Op.getValueType();
7151   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7152   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7153   DebugLoc dl = Op.getDebugLoc();
7154
7155   if (isFP) {
7156     unsigned SSECC = 8;
7157     EVT VT0 = Op0.getValueType();
7158     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7159     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7160     bool Swap = false;
7161
7162     switch (SetCCOpcode) {
7163     default: break;
7164     case ISD::SETOEQ:
7165     case ISD::SETEQ:  SSECC = 0; break;
7166     case ISD::SETOGT:
7167     case ISD::SETGT: Swap = true; // Fallthrough
7168     case ISD::SETLT:
7169     case ISD::SETOLT: SSECC = 1; break;
7170     case ISD::SETOGE:
7171     case ISD::SETGE: Swap = true; // Fallthrough
7172     case ISD::SETLE:
7173     case ISD::SETOLE: SSECC = 2; break;
7174     case ISD::SETUO:  SSECC = 3; break;
7175     case ISD::SETUNE:
7176     case ISD::SETNE:  SSECC = 4; break;
7177     case ISD::SETULE: Swap = true;
7178     case ISD::SETUGE: SSECC = 5; break;
7179     case ISD::SETULT: Swap = true;
7180     case ISD::SETUGT: SSECC = 6; break;
7181     case ISD::SETO:   SSECC = 7; break;
7182     }
7183     if (Swap)
7184       std::swap(Op0, Op1);
7185
7186     // In the two special cases we can't handle, emit two comparisons.
7187     if (SSECC == 8) {
7188       if (SetCCOpcode == ISD::SETUEQ) {
7189         SDValue UNORD, EQ;
7190         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7191         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7192         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7193       }
7194       else if (SetCCOpcode == ISD::SETONE) {
7195         SDValue ORD, NEQ;
7196         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7197         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7198         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7199       }
7200       llvm_unreachable("Illegal FP comparison");
7201     }
7202     // Handle all other FP comparisons here.
7203     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7204   }
7205
7206   // We are handling one of the integer comparisons here.  Since SSE only has
7207   // GT and EQ comparisons for integer, swapping operands and multiple
7208   // operations may be required for some comparisons.
7209   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7210   bool Swap = false, Invert = false, FlipSigns = false;
7211
7212   switch (VT.getSimpleVT().SimpleTy) {
7213   default: break;
7214   case MVT::v8i8:
7215   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7216   case MVT::v4i16:
7217   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7218   case MVT::v2i32:
7219   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7220   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7221   }
7222
7223   switch (SetCCOpcode) {
7224   default: break;
7225   case ISD::SETNE:  Invert = true;
7226   case ISD::SETEQ:  Opc = EQOpc; break;
7227   case ISD::SETLT:  Swap = true;
7228   case ISD::SETGT:  Opc = GTOpc; break;
7229   case ISD::SETGE:  Swap = true;
7230   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7231   case ISD::SETULT: Swap = true;
7232   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7233   case ISD::SETUGE: Swap = true;
7234   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7235   }
7236   if (Swap)
7237     std::swap(Op0, Op1);
7238
7239   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7240   // bits of the inputs before performing those operations.
7241   if (FlipSigns) {
7242     EVT EltVT = VT.getVectorElementType();
7243     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7244                                       EltVT);
7245     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7246     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7247                                     SignBits.size());
7248     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7249     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7250   }
7251
7252   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7253
7254   // If the logical-not of the result is required, perform that now.
7255   if (Invert)
7256     Result = DAG.getNOT(dl, Result, VT);
7257
7258   return Result;
7259 }
7260
7261 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7262 static bool isX86LogicalCmp(SDValue Op) {
7263   unsigned Opc = Op.getNode()->getOpcode();
7264   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7265     return true;
7266   if (Op.getResNo() == 1 &&
7267       (Opc == X86ISD::ADD ||
7268        Opc == X86ISD::SUB ||
7269        Opc == X86ISD::SMUL ||
7270        Opc == X86ISD::UMUL ||
7271        Opc == X86ISD::INC ||
7272        Opc == X86ISD::DEC ||
7273        Opc == X86ISD::OR ||
7274        Opc == X86ISD::XOR ||
7275        Opc == X86ISD::AND))
7276     return true;
7277
7278   return false;
7279 }
7280
7281 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7282   bool addTest = true;
7283   SDValue Cond  = Op.getOperand(0);
7284   DebugLoc dl = Op.getDebugLoc();
7285   SDValue CC;
7286
7287   if (Cond.getOpcode() == ISD::SETCC) {
7288     SDValue NewCond = LowerSETCC(Cond, DAG);
7289     if (NewCond.getNode())
7290       Cond = NewCond;
7291   }
7292
7293   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7294   SDValue Op1 = Op.getOperand(1);
7295   SDValue Op2 = Op.getOperand(2);
7296   if (Cond.getOpcode() == X86ISD::SETCC &&
7297       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7298     SDValue Cmp = Cond.getOperand(1);
7299     if (Cmp.getOpcode() == X86ISD::CMP) {
7300       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7301       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7302       ConstantSDNode *RHSC =
7303         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7304       if (N1C && N1C->isAllOnesValue() &&
7305           N2C && N2C->isNullValue() &&
7306           RHSC && RHSC->isNullValue()) {
7307         SDValue CmpOp0 = Cmp.getOperand(0);
7308         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7309                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7310         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7311                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7312       }
7313     }
7314   }
7315
7316   // Look pass (and (setcc_carry (cmp ...)), 1).
7317   if (Cond.getOpcode() == ISD::AND &&
7318       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7319     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7320     if (C && C->getAPIntValue() == 1) 
7321       Cond = Cond.getOperand(0);
7322   }
7323
7324   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7325   // setting operand in place of the X86ISD::SETCC.
7326   if (Cond.getOpcode() == X86ISD::SETCC ||
7327       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7328     CC = Cond.getOperand(0);
7329
7330     SDValue Cmp = Cond.getOperand(1);
7331     unsigned Opc = Cmp.getOpcode();
7332     EVT VT = Op.getValueType();
7333
7334     bool IllegalFPCMov = false;
7335     if (VT.isFloatingPoint() && !VT.isVector() &&
7336         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7337       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7338
7339     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7340         Opc == X86ISD::BT) { // FIXME
7341       Cond = Cmp;
7342       addTest = false;
7343     }
7344   }
7345
7346   if (addTest) {
7347     // Look pass the truncate.
7348     if (Cond.getOpcode() == ISD::TRUNCATE)
7349       Cond = Cond.getOperand(0);
7350
7351     // We know the result of AND is compared against zero. Try to match
7352     // it to BT.
7353     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7354       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7355       if (NewSetCC.getNode()) {
7356         CC = NewSetCC.getOperand(0);
7357         Cond = NewSetCC.getOperand(1);
7358         addTest = false;
7359       }
7360     }
7361   }
7362
7363   if (addTest) {
7364     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7365     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7366   }
7367
7368   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7369   // condition is true.
7370   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7371   SDValue Ops[] = { Op2, Op1, CC, Cond };
7372   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7373 }
7374
7375 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7376 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7377 // from the AND / OR.
7378 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7379   Opc = Op.getOpcode();
7380   if (Opc != ISD::OR && Opc != ISD::AND)
7381     return false;
7382   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7383           Op.getOperand(0).hasOneUse() &&
7384           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7385           Op.getOperand(1).hasOneUse());
7386 }
7387
7388 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7389 // 1 and that the SETCC node has a single use.
7390 static bool isXor1OfSetCC(SDValue Op) {
7391   if (Op.getOpcode() != ISD::XOR)
7392     return false;
7393   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7394   if (N1C && N1C->getAPIntValue() == 1) {
7395     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7396       Op.getOperand(0).hasOneUse();
7397   }
7398   return false;
7399 }
7400
7401 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7402   bool addTest = true;
7403   SDValue Chain = Op.getOperand(0);
7404   SDValue Cond  = Op.getOperand(1);
7405   SDValue Dest  = Op.getOperand(2);
7406   DebugLoc dl = Op.getDebugLoc();
7407   SDValue CC;
7408
7409   if (Cond.getOpcode() == ISD::SETCC) {
7410     SDValue NewCond = LowerSETCC(Cond, DAG);
7411     if (NewCond.getNode())
7412       Cond = NewCond;
7413   }
7414 #if 0
7415   // FIXME: LowerXALUO doesn't handle these!!
7416   else if (Cond.getOpcode() == X86ISD::ADD  ||
7417            Cond.getOpcode() == X86ISD::SUB  ||
7418            Cond.getOpcode() == X86ISD::SMUL ||
7419            Cond.getOpcode() == X86ISD::UMUL)
7420     Cond = LowerXALUO(Cond, DAG);
7421 #endif
7422
7423   // Look pass (and (setcc_carry (cmp ...)), 1).
7424   if (Cond.getOpcode() == ISD::AND &&
7425       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7426     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7427     if (C && C->getAPIntValue() == 1) 
7428       Cond = Cond.getOperand(0);
7429   }
7430
7431   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7432   // setting operand in place of the X86ISD::SETCC.
7433   if (Cond.getOpcode() == X86ISD::SETCC ||
7434       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7435     CC = Cond.getOperand(0);
7436
7437     SDValue Cmp = Cond.getOperand(1);
7438     unsigned Opc = Cmp.getOpcode();
7439     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7440     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7441       Cond = Cmp;
7442       addTest = false;
7443     } else {
7444       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7445       default: break;
7446       case X86::COND_O:
7447       case X86::COND_B:
7448         // These can only come from an arithmetic instruction with overflow,
7449         // e.g. SADDO, UADDO.
7450         Cond = Cond.getNode()->getOperand(1);
7451         addTest = false;
7452         break;
7453       }
7454     }
7455   } else {
7456     unsigned CondOpc;
7457     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7458       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7459       if (CondOpc == ISD::OR) {
7460         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7461         // two branches instead of an explicit OR instruction with a
7462         // separate test.
7463         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7464             isX86LogicalCmp(Cmp)) {
7465           CC = Cond.getOperand(0).getOperand(0);
7466           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7467                               Chain, Dest, CC, Cmp);
7468           CC = Cond.getOperand(1).getOperand(0);
7469           Cond = Cmp;
7470           addTest = false;
7471         }
7472       } else { // ISD::AND
7473         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7474         // two branches instead of an explicit AND instruction with a
7475         // separate test. However, we only do this if this block doesn't
7476         // have a fall-through edge, because this requires an explicit
7477         // jmp when the condition is false.
7478         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7479             isX86LogicalCmp(Cmp) &&
7480             Op.getNode()->hasOneUse()) {
7481           X86::CondCode CCode =
7482             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7483           CCode = X86::GetOppositeBranchCondition(CCode);
7484           CC = DAG.getConstant(CCode, MVT::i8);
7485           SDNode *User = *Op.getNode()->use_begin();
7486           // Look for an unconditional branch following this conditional branch.
7487           // We need this because we need to reverse the successors in order
7488           // to implement FCMP_OEQ.
7489           if (User->getOpcode() == ISD::BR) {
7490             SDValue FalseBB = User->getOperand(1);
7491             SDNode *NewBR =
7492               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7493             assert(NewBR == User);
7494             (void)NewBR;
7495             Dest = FalseBB;
7496
7497             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7498                                 Chain, Dest, CC, Cmp);
7499             X86::CondCode CCode =
7500               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7501             CCode = X86::GetOppositeBranchCondition(CCode);
7502             CC = DAG.getConstant(CCode, MVT::i8);
7503             Cond = Cmp;
7504             addTest = false;
7505           }
7506         }
7507       }
7508     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7509       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7510       // It should be transformed during dag combiner except when the condition
7511       // is set by a arithmetics with overflow node.
7512       X86::CondCode CCode =
7513         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7514       CCode = X86::GetOppositeBranchCondition(CCode);
7515       CC = DAG.getConstant(CCode, MVT::i8);
7516       Cond = Cond.getOperand(0).getOperand(1);
7517       addTest = false;
7518     }
7519   }
7520
7521   if (addTest) {
7522     // Look pass the truncate.
7523     if (Cond.getOpcode() == ISD::TRUNCATE)
7524       Cond = Cond.getOperand(0);
7525
7526     // We know the result of AND is compared against zero. Try to match
7527     // it to BT.
7528     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
7529       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7530       if (NewSetCC.getNode()) {
7531         CC = NewSetCC.getOperand(0);
7532         Cond = NewSetCC.getOperand(1);
7533         addTest = false;
7534       }
7535     }
7536   }
7537
7538   if (addTest) {
7539     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7540     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7541   }
7542   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7543                      Chain, Dest, CC, Cond);
7544 }
7545
7546
7547 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7548 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7549 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7550 // that the guard pages used by the OS virtual memory manager are allocated in
7551 // correct sequence.
7552 SDValue
7553 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7554                                            SelectionDAG &DAG) const {
7555   assert(Subtarget->isTargetCygMing() &&
7556          "This should be used only on Cygwin/Mingw targets");
7557   DebugLoc dl = Op.getDebugLoc();
7558
7559   // Get the inputs.
7560   SDValue Chain = Op.getOperand(0);
7561   SDValue Size  = Op.getOperand(1);
7562   // FIXME: Ensure alignment here
7563
7564   SDValue Flag;
7565
7566   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7567
7568   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7569   Flag = Chain.getValue(1);
7570
7571   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7572
7573   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7574   Flag = Chain.getValue(1);
7575
7576   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7577
7578   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7579   return DAG.getMergeValues(Ops1, 2, dl);
7580 }
7581
7582 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7583   MachineFunction &MF = DAG.getMachineFunction();
7584   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7585
7586   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7587   DebugLoc DL = Op.getDebugLoc();
7588
7589   if (!Subtarget->is64Bit()) {
7590     // vastart just stores the address of the VarArgsFrameIndex slot into the
7591     // memory location argument.
7592     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7593                                    getPointerTy());
7594     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7595                         MachinePointerInfo(SV), false, false, 0);
7596   }
7597
7598   // __va_list_tag:
7599   //   gp_offset         (0 - 6 * 8)
7600   //   fp_offset         (48 - 48 + 8 * 16)
7601   //   overflow_arg_area (point to parameters coming in memory).
7602   //   reg_save_area
7603   SmallVector<SDValue, 8> MemOps;
7604   SDValue FIN = Op.getOperand(1);
7605   // Store gp_offset
7606   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7607                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7608                                                MVT::i32),
7609                                FIN, MachinePointerInfo(SV), false, false, 0);
7610   MemOps.push_back(Store);
7611
7612   // Store fp_offset
7613   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7614                     FIN, DAG.getIntPtrConstant(4));
7615   Store = DAG.getStore(Op.getOperand(0), DL,
7616                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7617                                        MVT::i32),
7618                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7619   MemOps.push_back(Store);
7620
7621   // Store ptr to overflow_arg_area
7622   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7623                     FIN, DAG.getIntPtrConstant(4));
7624   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7625                                     getPointerTy());
7626   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7627                        MachinePointerInfo(SV, 8),
7628                        false, false, 0);
7629   MemOps.push_back(Store);
7630
7631   // Store ptr to reg_save_area.
7632   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7633                     FIN, DAG.getIntPtrConstant(8));
7634   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7635                                     getPointerTy());
7636   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7637                        MachinePointerInfo(SV, 16), false, false, 0);
7638   MemOps.push_back(Store);
7639   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7640                      &MemOps[0], MemOps.size());
7641 }
7642
7643 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7644   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7645   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7646
7647   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7648   return SDValue();
7649 }
7650
7651 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7652   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7653   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7654   SDValue Chain = Op.getOperand(0);
7655   SDValue DstPtr = Op.getOperand(1);
7656   SDValue SrcPtr = Op.getOperand(2);
7657   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7658   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7659   DebugLoc DL = Op.getDebugLoc();
7660
7661   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7662                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7663                        false, 
7664                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7665 }
7666
7667 SDValue
7668 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7669   DebugLoc dl = Op.getDebugLoc();
7670   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7671   switch (IntNo) {
7672   default: return SDValue();    // Don't custom lower most intrinsics.
7673   // Comparison intrinsics.
7674   case Intrinsic::x86_sse_comieq_ss:
7675   case Intrinsic::x86_sse_comilt_ss:
7676   case Intrinsic::x86_sse_comile_ss:
7677   case Intrinsic::x86_sse_comigt_ss:
7678   case Intrinsic::x86_sse_comige_ss:
7679   case Intrinsic::x86_sse_comineq_ss:
7680   case Intrinsic::x86_sse_ucomieq_ss:
7681   case Intrinsic::x86_sse_ucomilt_ss:
7682   case Intrinsic::x86_sse_ucomile_ss:
7683   case Intrinsic::x86_sse_ucomigt_ss:
7684   case Intrinsic::x86_sse_ucomige_ss:
7685   case Intrinsic::x86_sse_ucomineq_ss:
7686   case Intrinsic::x86_sse2_comieq_sd:
7687   case Intrinsic::x86_sse2_comilt_sd:
7688   case Intrinsic::x86_sse2_comile_sd:
7689   case Intrinsic::x86_sse2_comigt_sd:
7690   case Intrinsic::x86_sse2_comige_sd:
7691   case Intrinsic::x86_sse2_comineq_sd:
7692   case Intrinsic::x86_sse2_ucomieq_sd:
7693   case Intrinsic::x86_sse2_ucomilt_sd:
7694   case Intrinsic::x86_sse2_ucomile_sd:
7695   case Intrinsic::x86_sse2_ucomigt_sd:
7696   case Intrinsic::x86_sse2_ucomige_sd:
7697   case Intrinsic::x86_sse2_ucomineq_sd: {
7698     unsigned Opc = 0;
7699     ISD::CondCode CC = ISD::SETCC_INVALID;
7700     switch (IntNo) {
7701     default: break;
7702     case Intrinsic::x86_sse_comieq_ss:
7703     case Intrinsic::x86_sse2_comieq_sd:
7704       Opc = X86ISD::COMI;
7705       CC = ISD::SETEQ;
7706       break;
7707     case Intrinsic::x86_sse_comilt_ss:
7708     case Intrinsic::x86_sse2_comilt_sd:
7709       Opc = X86ISD::COMI;
7710       CC = ISD::SETLT;
7711       break;
7712     case Intrinsic::x86_sse_comile_ss:
7713     case Intrinsic::x86_sse2_comile_sd:
7714       Opc = X86ISD::COMI;
7715       CC = ISD::SETLE;
7716       break;
7717     case Intrinsic::x86_sse_comigt_ss:
7718     case Intrinsic::x86_sse2_comigt_sd:
7719       Opc = X86ISD::COMI;
7720       CC = ISD::SETGT;
7721       break;
7722     case Intrinsic::x86_sse_comige_ss:
7723     case Intrinsic::x86_sse2_comige_sd:
7724       Opc = X86ISD::COMI;
7725       CC = ISD::SETGE;
7726       break;
7727     case Intrinsic::x86_sse_comineq_ss:
7728     case Intrinsic::x86_sse2_comineq_sd:
7729       Opc = X86ISD::COMI;
7730       CC = ISD::SETNE;
7731       break;
7732     case Intrinsic::x86_sse_ucomieq_ss:
7733     case Intrinsic::x86_sse2_ucomieq_sd:
7734       Opc = X86ISD::UCOMI;
7735       CC = ISD::SETEQ;
7736       break;
7737     case Intrinsic::x86_sse_ucomilt_ss:
7738     case Intrinsic::x86_sse2_ucomilt_sd:
7739       Opc = X86ISD::UCOMI;
7740       CC = ISD::SETLT;
7741       break;
7742     case Intrinsic::x86_sse_ucomile_ss:
7743     case Intrinsic::x86_sse2_ucomile_sd:
7744       Opc = X86ISD::UCOMI;
7745       CC = ISD::SETLE;
7746       break;
7747     case Intrinsic::x86_sse_ucomigt_ss:
7748     case Intrinsic::x86_sse2_ucomigt_sd:
7749       Opc = X86ISD::UCOMI;
7750       CC = ISD::SETGT;
7751       break;
7752     case Intrinsic::x86_sse_ucomige_ss:
7753     case Intrinsic::x86_sse2_ucomige_sd:
7754       Opc = X86ISD::UCOMI;
7755       CC = ISD::SETGE;
7756       break;
7757     case Intrinsic::x86_sse_ucomineq_ss:
7758     case Intrinsic::x86_sse2_ucomineq_sd:
7759       Opc = X86ISD::UCOMI;
7760       CC = ISD::SETNE;
7761       break;
7762     }
7763
7764     SDValue LHS = Op.getOperand(1);
7765     SDValue RHS = Op.getOperand(2);
7766     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7767     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7768     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7769     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7770                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7771     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7772   }
7773   // ptest and testp intrinsics. The intrinsic these come from are designed to
7774   // return an integer value, not just an instruction so lower it to the ptest
7775   // or testp pattern and a setcc for the result.
7776   case Intrinsic::x86_sse41_ptestz:
7777   case Intrinsic::x86_sse41_ptestc:
7778   case Intrinsic::x86_sse41_ptestnzc:
7779   case Intrinsic::x86_avx_ptestz_256:
7780   case Intrinsic::x86_avx_ptestc_256:
7781   case Intrinsic::x86_avx_ptestnzc_256:
7782   case Intrinsic::x86_avx_vtestz_ps:
7783   case Intrinsic::x86_avx_vtestc_ps:
7784   case Intrinsic::x86_avx_vtestnzc_ps:
7785   case Intrinsic::x86_avx_vtestz_pd:
7786   case Intrinsic::x86_avx_vtestc_pd:
7787   case Intrinsic::x86_avx_vtestnzc_pd:
7788   case Intrinsic::x86_avx_vtestz_ps_256:
7789   case Intrinsic::x86_avx_vtestc_ps_256:
7790   case Intrinsic::x86_avx_vtestnzc_ps_256:
7791   case Intrinsic::x86_avx_vtestz_pd_256:
7792   case Intrinsic::x86_avx_vtestc_pd_256:
7793   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7794     bool IsTestPacked = false;
7795     unsigned X86CC = 0;
7796     switch (IntNo) {
7797     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7798     case Intrinsic::x86_avx_vtestz_ps:
7799     case Intrinsic::x86_avx_vtestz_pd:
7800     case Intrinsic::x86_avx_vtestz_ps_256:
7801     case Intrinsic::x86_avx_vtestz_pd_256:
7802       IsTestPacked = true; // Fallthrough
7803     case Intrinsic::x86_sse41_ptestz:
7804     case Intrinsic::x86_avx_ptestz_256:
7805       // ZF = 1
7806       X86CC = X86::COND_E;
7807       break;
7808     case Intrinsic::x86_avx_vtestc_ps:
7809     case Intrinsic::x86_avx_vtestc_pd:
7810     case Intrinsic::x86_avx_vtestc_ps_256:
7811     case Intrinsic::x86_avx_vtestc_pd_256:
7812       IsTestPacked = true; // Fallthrough
7813     case Intrinsic::x86_sse41_ptestc:
7814     case Intrinsic::x86_avx_ptestc_256:
7815       // CF = 1
7816       X86CC = X86::COND_B;
7817       break;
7818     case Intrinsic::x86_avx_vtestnzc_ps:
7819     case Intrinsic::x86_avx_vtestnzc_pd:
7820     case Intrinsic::x86_avx_vtestnzc_ps_256:
7821     case Intrinsic::x86_avx_vtestnzc_pd_256:
7822       IsTestPacked = true; // Fallthrough
7823     case Intrinsic::x86_sse41_ptestnzc:
7824     case Intrinsic::x86_avx_ptestnzc_256:
7825       // ZF and CF = 0
7826       X86CC = X86::COND_A;
7827       break;
7828     }
7829
7830     SDValue LHS = Op.getOperand(1);
7831     SDValue RHS = Op.getOperand(2);
7832     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7833     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7834     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7835     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7836     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7837   }
7838
7839   // Fix vector shift instructions where the last operand is a non-immediate
7840   // i32 value.
7841   case Intrinsic::x86_sse2_pslli_w:
7842   case Intrinsic::x86_sse2_pslli_d:
7843   case Intrinsic::x86_sse2_pslli_q:
7844   case Intrinsic::x86_sse2_psrli_w:
7845   case Intrinsic::x86_sse2_psrli_d:
7846   case Intrinsic::x86_sse2_psrli_q:
7847   case Intrinsic::x86_sse2_psrai_w:
7848   case Intrinsic::x86_sse2_psrai_d:
7849   case Intrinsic::x86_mmx_pslli_w:
7850   case Intrinsic::x86_mmx_pslli_d:
7851   case Intrinsic::x86_mmx_pslli_q:
7852   case Intrinsic::x86_mmx_psrli_w:
7853   case Intrinsic::x86_mmx_psrli_d:
7854   case Intrinsic::x86_mmx_psrli_q:
7855   case Intrinsic::x86_mmx_psrai_w:
7856   case Intrinsic::x86_mmx_psrai_d: {
7857     SDValue ShAmt = Op.getOperand(2);
7858     if (isa<ConstantSDNode>(ShAmt))
7859       return SDValue();
7860
7861     unsigned NewIntNo = 0;
7862     EVT ShAmtVT = MVT::v4i32;
7863     switch (IntNo) {
7864     case Intrinsic::x86_sse2_pslli_w:
7865       NewIntNo = Intrinsic::x86_sse2_psll_w;
7866       break;
7867     case Intrinsic::x86_sse2_pslli_d:
7868       NewIntNo = Intrinsic::x86_sse2_psll_d;
7869       break;
7870     case Intrinsic::x86_sse2_pslli_q:
7871       NewIntNo = Intrinsic::x86_sse2_psll_q;
7872       break;
7873     case Intrinsic::x86_sse2_psrli_w:
7874       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7875       break;
7876     case Intrinsic::x86_sse2_psrli_d:
7877       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7878       break;
7879     case Intrinsic::x86_sse2_psrli_q:
7880       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7881       break;
7882     case Intrinsic::x86_sse2_psrai_w:
7883       NewIntNo = Intrinsic::x86_sse2_psra_w;
7884       break;
7885     case Intrinsic::x86_sse2_psrai_d:
7886       NewIntNo = Intrinsic::x86_sse2_psra_d;
7887       break;
7888     default: {
7889       ShAmtVT = MVT::v2i32;
7890       switch (IntNo) {
7891       case Intrinsic::x86_mmx_pslli_w:
7892         NewIntNo = Intrinsic::x86_mmx_psll_w;
7893         break;
7894       case Intrinsic::x86_mmx_pslli_d:
7895         NewIntNo = Intrinsic::x86_mmx_psll_d;
7896         break;
7897       case Intrinsic::x86_mmx_pslli_q:
7898         NewIntNo = Intrinsic::x86_mmx_psll_q;
7899         break;
7900       case Intrinsic::x86_mmx_psrli_w:
7901         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7902         break;
7903       case Intrinsic::x86_mmx_psrli_d:
7904         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7905         break;
7906       case Intrinsic::x86_mmx_psrli_q:
7907         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7908         break;
7909       case Intrinsic::x86_mmx_psrai_w:
7910         NewIntNo = Intrinsic::x86_mmx_psra_w;
7911         break;
7912       case Intrinsic::x86_mmx_psrai_d:
7913         NewIntNo = Intrinsic::x86_mmx_psra_d;
7914         break;
7915       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7916       }
7917       break;
7918     }
7919     }
7920
7921     // The vector shift intrinsics with scalars uses 32b shift amounts but
7922     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7923     // to be zero.
7924     SDValue ShOps[4];
7925     ShOps[0] = ShAmt;
7926     ShOps[1] = DAG.getConstant(0, MVT::i32);
7927     if (ShAmtVT == MVT::v4i32) {
7928       ShOps[2] = DAG.getUNDEF(MVT::i32);
7929       ShOps[3] = DAG.getUNDEF(MVT::i32);
7930       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7931     } else {
7932       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7933     }
7934
7935     EVT VT = Op.getValueType();
7936     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7937     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7938                        DAG.getConstant(NewIntNo, MVT::i32),
7939                        Op.getOperand(1), ShAmt);
7940   }
7941   }
7942 }
7943
7944 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7945                                            SelectionDAG &DAG) const {
7946   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7947   MFI->setReturnAddressIsTaken(true);
7948
7949   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7950   DebugLoc dl = Op.getDebugLoc();
7951
7952   if (Depth > 0) {
7953     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7954     SDValue Offset =
7955       DAG.getConstant(TD->getPointerSize(),
7956                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7957     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7958                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7959                                    FrameAddr, Offset),
7960                        MachinePointerInfo(), false, false, 0);
7961   }
7962
7963   // Just load the return address.
7964   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7965   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7966                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7967 }
7968
7969 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7970   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7971   MFI->setFrameAddressIsTaken(true);
7972
7973   EVT VT = Op.getValueType();
7974   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7975   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7976   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7977   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7978   while (Depth--)
7979     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7980                             MachinePointerInfo(),
7981                             false, false, 0);
7982   return FrameAddr;
7983 }
7984
7985 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7986                                                      SelectionDAG &DAG) const {
7987   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7988 }
7989
7990 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7991   MachineFunction &MF = DAG.getMachineFunction();
7992   SDValue Chain     = Op.getOperand(0);
7993   SDValue Offset    = Op.getOperand(1);
7994   SDValue Handler   = Op.getOperand(2);
7995   DebugLoc dl       = Op.getDebugLoc();
7996
7997   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7998                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7999                                      getPointerTy());
8000   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8001
8002   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8003                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8004   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8005   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8006                        false, false, 0);
8007   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8008   MF.getRegInfo().addLiveOut(StoreAddrReg);
8009
8010   return DAG.getNode(X86ISD::EH_RETURN, dl,
8011                      MVT::Other,
8012                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8013 }
8014
8015 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8016                                              SelectionDAG &DAG) const {
8017   SDValue Root = Op.getOperand(0);
8018   SDValue Trmp = Op.getOperand(1); // trampoline
8019   SDValue FPtr = Op.getOperand(2); // nested function
8020   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8021   DebugLoc dl  = Op.getDebugLoc();
8022
8023   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8024
8025   if (Subtarget->is64Bit()) {
8026     SDValue OutChains[6];
8027
8028     // Large code-model.
8029     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8030     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8031
8032     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8033     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8034
8035     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8036
8037     // Load the pointer to the nested function into R11.
8038     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8039     SDValue Addr = Trmp;
8040     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8041                                 Addr, MachinePointerInfo(TrmpAddr),
8042                                 false, false, 0);
8043
8044     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8045                        DAG.getConstant(2, MVT::i64));
8046     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8047                                 MachinePointerInfo(TrmpAddr, 2),
8048                                 false, false, 2);
8049
8050     // Load the 'nest' parameter value into R10.
8051     // R10 is specified in X86CallingConv.td
8052     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8053     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8054                        DAG.getConstant(10, MVT::i64));
8055     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8056                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8057                                 false, false, 0);
8058
8059     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8060                        DAG.getConstant(12, MVT::i64));
8061     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8062                                 MachinePointerInfo(TrmpAddr, 12),
8063                                 false, false, 2);
8064
8065     // Jump to the nested function.
8066     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8067     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8068                        DAG.getConstant(20, MVT::i64));
8069     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8070                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8071                                 false, false, 0);
8072
8073     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8074     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8075                        DAG.getConstant(22, MVT::i64));
8076     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8077                                 MachinePointerInfo(TrmpAddr, 22),
8078                                 false, false, 0);
8079
8080     SDValue Ops[] =
8081       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8082     return DAG.getMergeValues(Ops, 2, dl);
8083   } else {
8084     const Function *Func =
8085       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8086     CallingConv::ID CC = Func->getCallingConv();
8087     unsigned NestReg;
8088
8089     switch (CC) {
8090     default:
8091       llvm_unreachable("Unsupported calling convention");
8092     case CallingConv::C:
8093     case CallingConv::X86_StdCall: {
8094       // Pass 'nest' parameter in ECX.
8095       // Must be kept in sync with X86CallingConv.td
8096       NestReg = X86::ECX;
8097
8098       // Check that ECX wasn't needed by an 'inreg' parameter.
8099       const FunctionType *FTy = Func->getFunctionType();
8100       const AttrListPtr &Attrs = Func->getAttributes();
8101
8102       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8103         unsigned InRegCount = 0;
8104         unsigned Idx = 1;
8105
8106         for (FunctionType::param_iterator I = FTy->param_begin(),
8107              E = FTy->param_end(); I != E; ++I, ++Idx)
8108           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8109             // FIXME: should only count parameters that are lowered to integers.
8110             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8111
8112         if (InRegCount > 2) {
8113           report_fatal_error("Nest register in use - reduce number of inreg"
8114                              " parameters!");
8115         }
8116       }
8117       break;
8118     }
8119     case CallingConv::X86_FastCall:
8120     case CallingConv::X86_ThisCall:
8121     case CallingConv::Fast:
8122       // Pass 'nest' parameter in EAX.
8123       // Must be kept in sync with X86CallingConv.td
8124       NestReg = X86::EAX;
8125       break;
8126     }
8127
8128     SDValue OutChains[4];
8129     SDValue Addr, Disp;
8130
8131     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8132                        DAG.getConstant(10, MVT::i32));
8133     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8134
8135     // This is storing the opcode for MOV32ri.
8136     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8137     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8138     OutChains[0] = DAG.getStore(Root, dl,
8139                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8140                                 Trmp, MachinePointerInfo(TrmpAddr),
8141                                 false, false, 0);
8142
8143     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8144                        DAG.getConstant(1, MVT::i32));
8145     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8146                                 MachinePointerInfo(TrmpAddr, 1),
8147                                 false, false, 1);
8148
8149     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8150     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8151                        DAG.getConstant(5, MVT::i32));
8152     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8153                                 MachinePointerInfo(TrmpAddr, 5),
8154                                 false, false, 1);
8155
8156     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8157                        DAG.getConstant(6, MVT::i32));
8158     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8159                                 MachinePointerInfo(TrmpAddr, 6),
8160                                 false, false, 1);
8161
8162     SDValue Ops[] =
8163       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8164     return DAG.getMergeValues(Ops, 2, dl);
8165   }
8166 }
8167
8168 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8169                                             SelectionDAG &DAG) const {
8170   /*
8171    The rounding mode is in bits 11:10 of FPSR, and has the following
8172    settings:
8173      00 Round to nearest
8174      01 Round to -inf
8175      10 Round to +inf
8176      11 Round to 0
8177
8178   FLT_ROUNDS, on the other hand, expects the following:
8179     -1 Undefined
8180      0 Round to 0
8181      1 Round to nearest
8182      2 Round to +inf
8183      3 Round to -inf
8184
8185   To perform the conversion, we do:
8186     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8187   */
8188
8189   MachineFunction &MF = DAG.getMachineFunction();
8190   const TargetMachine &TM = MF.getTarget();
8191   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8192   unsigned StackAlignment = TFI.getStackAlignment();
8193   EVT VT = Op.getValueType();
8194   DebugLoc DL = Op.getDebugLoc();
8195
8196   // Save FP Control Word to stack slot
8197   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8198   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8199
8200   
8201   MachineMemOperand *MMO =
8202    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8203                            MachineMemOperand::MOStore, 2, 2);
8204   
8205   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8206   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8207                                           DAG.getVTList(MVT::Other),
8208                                           Ops, 2, MVT::i16, MMO);
8209
8210   // Load FP Control Word from stack slot
8211   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8212                             MachinePointerInfo(), false, false, 0);
8213
8214   // Transform as necessary
8215   SDValue CWD1 =
8216     DAG.getNode(ISD::SRL, DL, MVT::i16,
8217                 DAG.getNode(ISD::AND, DL, MVT::i16,
8218                             CWD, DAG.getConstant(0x800, MVT::i16)),
8219                 DAG.getConstant(11, MVT::i8));
8220   SDValue CWD2 =
8221     DAG.getNode(ISD::SRL, DL, MVT::i16,
8222                 DAG.getNode(ISD::AND, DL, MVT::i16,
8223                             CWD, DAG.getConstant(0x400, MVT::i16)),
8224                 DAG.getConstant(9, MVT::i8));
8225
8226   SDValue RetVal =
8227     DAG.getNode(ISD::AND, DL, MVT::i16,
8228                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8229                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8230                             DAG.getConstant(1, MVT::i16)),
8231                 DAG.getConstant(3, MVT::i16));
8232
8233
8234   return DAG.getNode((VT.getSizeInBits() < 16 ?
8235                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8236 }
8237
8238 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8239   EVT VT = Op.getValueType();
8240   EVT OpVT = VT;
8241   unsigned NumBits = VT.getSizeInBits();
8242   DebugLoc dl = Op.getDebugLoc();
8243
8244   Op = Op.getOperand(0);
8245   if (VT == MVT::i8) {
8246     // Zero extend to i32 since there is not an i8 bsr.
8247     OpVT = MVT::i32;
8248     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8249   }
8250
8251   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8252   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8253   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8254
8255   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8256   SDValue Ops[] = {
8257     Op,
8258     DAG.getConstant(NumBits+NumBits-1, OpVT),
8259     DAG.getConstant(X86::COND_E, MVT::i8),
8260     Op.getValue(1)
8261   };
8262   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8263
8264   // Finally xor with NumBits-1.
8265   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8266
8267   if (VT == MVT::i8)
8268     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8269   return Op;
8270 }
8271
8272 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8273   EVT VT = Op.getValueType();
8274   EVT OpVT = VT;
8275   unsigned NumBits = VT.getSizeInBits();
8276   DebugLoc dl = Op.getDebugLoc();
8277
8278   Op = Op.getOperand(0);
8279   if (VT == MVT::i8) {
8280     OpVT = MVT::i32;
8281     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8282   }
8283
8284   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8285   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8286   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8287
8288   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8289   SDValue Ops[] = {
8290     Op,
8291     DAG.getConstant(NumBits, OpVT),
8292     DAG.getConstant(X86::COND_E, MVT::i8),
8293     Op.getValue(1)
8294   };
8295   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8296
8297   if (VT == MVT::i8)
8298     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8299   return Op;
8300 }
8301
8302 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8303   EVT VT = Op.getValueType();
8304   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8305   DebugLoc dl = Op.getDebugLoc();
8306
8307   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8308   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8309   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8310   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8311   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8312   //
8313   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8314   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8315   //  return AloBlo + AloBhi + AhiBlo;
8316
8317   SDValue A = Op.getOperand(0);
8318   SDValue B = Op.getOperand(1);
8319
8320   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8321                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8322                        A, DAG.getConstant(32, MVT::i32));
8323   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8324                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8325                        B, DAG.getConstant(32, MVT::i32));
8326   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8327                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8328                        A, B);
8329   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8330                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8331                        A, Bhi);
8332   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8333                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8334                        Ahi, B);
8335   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8336                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8337                        AloBhi, DAG.getConstant(32, MVT::i32));
8338   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8339                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8340                        AhiBlo, DAG.getConstant(32, MVT::i32));
8341   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8342   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8343   return Res;
8344 }
8345
8346 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8347   EVT VT = Op.getValueType();
8348   DebugLoc dl = Op.getDebugLoc();
8349   SDValue R = Op.getOperand(0);
8350
8351   LLVMContext *Context = DAG.getContext();
8352
8353   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8354
8355   if (VT == MVT::v4i32) {
8356     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8357                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8358                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8359
8360     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8361     
8362     std::vector<Constant*> CV(4, CI);
8363     Constant *C = ConstantVector::get(CV);
8364     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8365     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8366                                  MachinePointerInfo::getConstantPool(),
8367                                  false, false, 16);
8368
8369     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8370     Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8371     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8372     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8373   }
8374   if (VT == MVT::v16i8) {
8375     // a = a << 5;
8376     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8377                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8378                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8379
8380     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8381     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8382
8383     std::vector<Constant*> CVM1(16, CM1);
8384     std::vector<Constant*> CVM2(16, CM2);
8385     Constant *C = ConstantVector::get(CVM1);
8386     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8387     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8388                             MachinePointerInfo::getConstantPool(),
8389                             false, false, 16);
8390
8391     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8392     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8393     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8394                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8395                     DAG.getConstant(4, MVT::i32));
8396     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8397                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8398                     R, M, Op);
8399     // a += a
8400     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8401     
8402     C = ConstantVector::get(CVM2);
8403     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8404     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8405                     MachinePointerInfo::getConstantPool(),
8406                     false, false, 16);
8407     
8408     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8409     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8410     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8411                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8412                     DAG.getConstant(2, MVT::i32));
8413     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8414                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8415                     R, M, Op);
8416     // a += a
8417     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8418     
8419     // return pblendv(r, r+r, a);
8420     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8421                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8422                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8423     return R;
8424   }
8425   return SDValue();
8426 }
8427
8428 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8429   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8430   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8431   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8432   // has only one use.
8433   SDNode *N = Op.getNode();
8434   SDValue LHS = N->getOperand(0);
8435   SDValue RHS = N->getOperand(1);
8436   unsigned BaseOp = 0;
8437   unsigned Cond = 0;
8438   DebugLoc dl = Op.getDebugLoc();
8439
8440   switch (Op.getOpcode()) {
8441   default: llvm_unreachable("Unknown ovf instruction!");
8442   case ISD::SADDO:
8443     // A subtract of one will be selected as a INC. Note that INC doesn't
8444     // set CF, so we can't do this for UADDO.
8445     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8446       if (C->getAPIntValue() == 1) {
8447         BaseOp = X86ISD::INC;
8448         Cond = X86::COND_O;
8449         break;
8450       }
8451     BaseOp = X86ISD::ADD;
8452     Cond = X86::COND_O;
8453     break;
8454   case ISD::UADDO:
8455     BaseOp = X86ISD::ADD;
8456     Cond = X86::COND_B;
8457     break;
8458   case ISD::SSUBO:
8459     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8460     // set CF, so we can't do this for USUBO.
8461     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8462       if (C->getAPIntValue() == 1) {
8463         BaseOp = X86ISD::DEC;
8464         Cond = X86::COND_O;
8465         break;
8466       }
8467     BaseOp = X86ISD::SUB;
8468     Cond = X86::COND_O;
8469     break;
8470   case ISD::USUBO:
8471     BaseOp = X86ISD::SUB;
8472     Cond = X86::COND_B;
8473     break;
8474   case ISD::SMULO:
8475     BaseOp = X86ISD::SMUL;
8476     Cond = X86::COND_O;
8477     break;
8478   case ISD::UMULO:
8479     BaseOp = X86ISD::UMUL;
8480     Cond = X86::COND_B;
8481     break;
8482   }
8483
8484   // Also sets EFLAGS.
8485   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8486   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8487
8488   SDValue SetCC =
8489     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8490                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8491
8492   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8493   return Sum;
8494 }
8495
8496 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8497   DebugLoc dl = Op.getDebugLoc();
8498   
8499   if (!Subtarget->hasSSE2()) {
8500     SDValue Chain = Op.getOperand(0);
8501     SDValue Zero = DAG.getConstant(0, 
8502                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8503     SDValue Ops[] = {
8504       DAG.getRegister(X86::ESP, MVT::i32), // Base
8505       DAG.getTargetConstant(1, MVT::i8),   // Scale
8506       DAG.getRegister(0, MVT::i32),        // Index
8507       DAG.getTargetConstant(0, MVT::i32),  // Disp
8508       DAG.getRegister(0, MVT::i32),        // Segment.
8509       Zero,
8510       Chain
8511     };
8512     SDNode *Res = 
8513       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8514                           array_lengthof(Ops));
8515     return SDValue(Res, 0);
8516   }
8517   
8518   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8519   if (!isDev)
8520     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8521   
8522   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8523   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8524   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8525   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8526   
8527   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8528   if (!Op1 && !Op2 && !Op3 && Op4)
8529     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8530   
8531   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8532   if (Op1 && !Op2 && !Op3 && !Op4)
8533     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8534   
8535   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 
8536   //           (MFENCE)>;
8537   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8538 }
8539
8540 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8541   EVT T = Op.getValueType();
8542   DebugLoc DL = Op.getDebugLoc();
8543   unsigned Reg = 0;
8544   unsigned size = 0;
8545   switch(T.getSimpleVT().SimpleTy) {
8546   default:
8547     assert(false && "Invalid value type!");
8548   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8549   case MVT::i16: Reg = X86::AX;  size = 2; break;
8550   case MVT::i32: Reg = X86::EAX; size = 4; break;
8551   case MVT::i64:
8552     assert(Subtarget->is64Bit() && "Node not type legal!");
8553     Reg = X86::RAX; size = 8;
8554     break;
8555   }
8556   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8557                                     Op.getOperand(2), SDValue());
8558   SDValue Ops[] = { cpIn.getValue(0),
8559                     Op.getOperand(1),
8560                     Op.getOperand(3),
8561                     DAG.getTargetConstant(size, MVT::i8),
8562                     cpIn.getValue(1) };
8563   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8564   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8565   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8566                                            Ops, 5, T, MMO);
8567   SDValue cpOut =
8568     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8569   return cpOut;
8570 }
8571
8572 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8573                                                  SelectionDAG &DAG) const {
8574   assert(Subtarget->is64Bit() && "Result not type legalized?");
8575   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8576   SDValue TheChain = Op.getOperand(0);
8577   DebugLoc dl = Op.getDebugLoc();
8578   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8579   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8580   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8581                                    rax.getValue(2));
8582   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8583                             DAG.getConstant(32, MVT::i8));
8584   SDValue Ops[] = {
8585     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8586     rdx.getValue(1)
8587   };
8588   return DAG.getMergeValues(Ops, 2, dl);
8589 }
8590
8591 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8592                                             SelectionDAG &DAG) const {
8593   EVT SrcVT = Op.getOperand(0).getValueType();
8594   EVT DstVT = Op.getValueType();
8595   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
8596           Subtarget->hasMMX() && !DisableMMX) &&
8597          "Unexpected custom BIT_CONVERT");
8598   assert((DstVT == MVT::i64 || 
8599           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8600          "Unexpected custom BIT_CONVERT");
8601   // i64 <=> MMX conversions are Legal.
8602   if (SrcVT==MVT::i64 && DstVT.isVector())
8603     return Op;
8604   if (DstVT==MVT::i64 && SrcVT.isVector())
8605     return Op;
8606   // MMX <=> MMX conversions are Legal.
8607   if (SrcVT.isVector() && DstVT.isVector())
8608     return Op;
8609   // All other conversions need to be expanded.
8610   return SDValue();
8611 }
8612 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8613   SDNode *Node = Op.getNode();
8614   DebugLoc dl = Node->getDebugLoc();
8615   EVT T = Node->getValueType(0);
8616   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8617                               DAG.getConstant(0, T), Node->getOperand(2));
8618   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8619                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8620                        Node->getOperand(0),
8621                        Node->getOperand(1), negOp,
8622                        cast<AtomicSDNode>(Node)->getSrcValue(),
8623                        cast<AtomicSDNode>(Node)->getAlignment());
8624 }
8625
8626 /// LowerOperation - Provide custom lowering hooks for some operations.
8627 ///
8628 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8629   switch (Op.getOpcode()) {
8630   default: llvm_unreachable("Should not custom lower this!");
8631   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8632   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8633   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8634   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8635   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8636   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8637   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8638   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8639   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8640   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8641   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8642   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8643   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8644   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8645   case ISD::SHL_PARTS:
8646   case ISD::SRA_PARTS:
8647   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8648   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8649   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8650   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8651   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8652   case ISD::FABS:               return LowerFABS(Op, DAG);
8653   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8654   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8655   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8656   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8657   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8658   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8659   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8660   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8661   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8662   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8663   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8664   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8665   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8666   case ISD::FRAME_TO_ARGS_OFFSET:
8667                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8668   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8669   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8670   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8671   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8672   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8673   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8674   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8675   case ISD::SHL:                return LowerSHL(Op, DAG);
8676   case ISD::SADDO:
8677   case ISD::UADDO:
8678   case ISD::SSUBO:
8679   case ISD::USUBO:
8680   case ISD::SMULO:
8681   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8682   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8683   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
8684   }
8685 }
8686
8687 void X86TargetLowering::
8688 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8689                         SelectionDAG &DAG, unsigned NewOp) const {
8690   EVT T = Node->getValueType(0);
8691   DebugLoc dl = Node->getDebugLoc();
8692   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8693
8694   SDValue Chain = Node->getOperand(0);
8695   SDValue In1 = Node->getOperand(1);
8696   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8697                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8698   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8699                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8700   SDValue Ops[] = { Chain, In1, In2L, In2H };
8701   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8702   SDValue Result =
8703     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8704                             cast<MemSDNode>(Node)->getMemOperand());
8705   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8706   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8707   Results.push_back(Result.getValue(2));
8708 }
8709
8710 /// ReplaceNodeResults - Replace a node with an illegal result type
8711 /// with a new node built out of custom code.
8712 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8713                                            SmallVectorImpl<SDValue>&Results,
8714                                            SelectionDAG &DAG) const {
8715   DebugLoc dl = N->getDebugLoc();
8716   switch (N->getOpcode()) {
8717   default:
8718     assert(false && "Do not know how to custom type legalize this operation!");
8719     return;
8720   case ISD::FP_TO_SINT: {
8721     std::pair<SDValue,SDValue> Vals =
8722         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8723     SDValue FIST = Vals.first, StackSlot = Vals.second;
8724     if (FIST.getNode() != 0) {
8725       EVT VT = N->getValueType(0);
8726       // Return a load from the stack slot.
8727       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8728                                     MachinePointerInfo(), false, false, 0));
8729     }
8730     return;
8731   }
8732   case ISD::READCYCLECOUNTER: {
8733     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8734     SDValue TheChain = N->getOperand(0);
8735     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8736     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8737                                      rd.getValue(1));
8738     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8739                                      eax.getValue(2));
8740     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8741     SDValue Ops[] = { eax, edx };
8742     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8743     Results.push_back(edx.getValue(1));
8744     return;
8745   }
8746   case ISD::ATOMIC_CMP_SWAP: {
8747     EVT T = N->getValueType(0);
8748     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8749     SDValue cpInL, cpInH;
8750     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8751                         DAG.getConstant(0, MVT::i32));
8752     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8753                         DAG.getConstant(1, MVT::i32));
8754     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8755     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8756                              cpInL.getValue(1));
8757     SDValue swapInL, swapInH;
8758     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8759                           DAG.getConstant(0, MVT::i32));
8760     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8761                           DAG.getConstant(1, MVT::i32));
8762     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8763                                cpInH.getValue(1));
8764     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8765                                swapInL.getValue(1));
8766     SDValue Ops[] = { swapInH.getValue(0),
8767                       N->getOperand(1),
8768                       swapInH.getValue(1) };
8769     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8770     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8771     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8772                                         MVT::i32, Result.getValue(1));
8773     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8774                                         MVT::i32, cpOutL.getValue(2));
8775     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8776     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8777     Results.push_back(cpOutH.getValue(1));
8778     return;
8779   }
8780   case ISD::ATOMIC_LOAD_ADD:
8781     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8782     return;
8783   case ISD::ATOMIC_LOAD_AND:
8784     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8785     return;
8786   case ISD::ATOMIC_LOAD_NAND:
8787     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8788     return;
8789   case ISD::ATOMIC_LOAD_OR:
8790     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8791     return;
8792   case ISD::ATOMIC_LOAD_SUB:
8793     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8794     return;
8795   case ISD::ATOMIC_LOAD_XOR:
8796     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8797     return;
8798   case ISD::ATOMIC_SWAP:
8799     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8800     return;
8801   }
8802 }
8803
8804 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8805   switch (Opcode) {
8806   default: return NULL;
8807   case X86ISD::BSF:                return "X86ISD::BSF";
8808   case X86ISD::BSR:                return "X86ISD::BSR";
8809   case X86ISD::SHLD:               return "X86ISD::SHLD";
8810   case X86ISD::SHRD:               return "X86ISD::SHRD";
8811   case X86ISD::FAND:               return "X86ISD::FAND";
8812   case X86ISD::FOR:                return "X86ISD::FOR";
8813   case X86ISD::FXOR:               return "X86ISD::FXOR";
8814   case X86ISD::FSRL:               return "X86ISD::FSRL";
8815   case X86ISD::FILD:               return "X86ISD::FILD";
8816   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8817   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8818   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8819   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8820   case X86ISD::FLD:                return "X86ISD::FLD";
8821   case X86ISD::FST:                return "X86ISD::FST";
8822   case X86ISD::CALL:               return "X86ISD::CALL";
8823   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8824   case X86ISD::BT:                 return "X86ISD::BT";
8825   case X86ISD::CMP:                return "X86ISD::CMP";
8826   case X86ISD::COMI:               return "X86ISD::COMI";
8827   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8828   case X86ISD::SETCC:              return "X86ISD::SETCC";
8829   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8830   case X86ISD::CMOV:               return "X86ISD::CMOV";
8831   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8832   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8833   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8834   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8835   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8836   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8837   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8838   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8839   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8840   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8841   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8842   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8843   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
8844   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8845   case X86ISD::FMAX:               return "X86ISD::FMAX";
8846   case X86ISD::FMIN:               return "X86ISD::FMIN";
8847   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8848   case X86ISD::FRCP:               return "X86ISD::FRCP";
8849   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8850   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8851   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8852   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8853   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8854   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8855   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8856   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8857   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8858   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8859   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8860   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8861   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8862   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8863   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8864   case X86ISD::VSHL:               return "X86ISD::VSHL";
8865   case X86ISD::VSRL:               return "X86ISD::VSRL";
8866   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8867   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8868   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8869   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8870   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8871   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8872   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8873   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8874   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8875   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8876   case X86ISD::ADD:                return "X86ISD::ADD";
8877   case X86ISD::SUB:                return "X86ISD::SUB";
8878   case X86ISD::SMUL:               return "X86ISD::SMUL";
8879   case X86ISD::UMUL:               return "X86ISD::UMUL";
8880   case X86ISD::INC:                return "X86ISD::INC";
8881   case X86ISD::DEC:                return "X86ISD::DEC";
8882   case X86ISD::OR:                 return "X86ISD::OR";
8883   case X86ISD::XOR:                return "X86ISD::XOR";
8884   case X86ISD::AND:                return "X86ISD::AND";
8885   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8886   case X86ISD::PTEST:              return "X86ISD::PTEST";
8887   case X86ISD::TESTP:              return "X86ISD::TESTP";
8888   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8889   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8890   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8891   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8892   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8893   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8894   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8895   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8896   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8897   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8898   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8899   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8900   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8901   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8902   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8903   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8904   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8905   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8906   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8907   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8908   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8909   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8910   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8911   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8912   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8913   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8914   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8915   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8916   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8917   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8918   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8919   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8920   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8921   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8922   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
8923   }
8924 }
8925
8926 // isLegalAddressingMode - Return true if the addressing mode represented
8927 // by AM is legal for this target, for a load/store of the specified type.
8928 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8929                                               const Type *Ty) const {
8930   // X86 supports extremely general addressing modes.
8931   CodeModel::Model M = getTargetMachine().getCodeModel();
8932   Reloc::Model R = getTargetMachine().getRelocationModel();
8933
8934   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8935   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8936     return false;
8937
8938   if (AM.BaseGV) {
8939     unsigned GVFlags =
8940       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8941
8942     // If a reference to this global requires an extra load, we can't fold it.
8943     if (isGlobalStubReference(GVFlags))
8944       return false;
8945
8946     // If BaseGV requires a register for the PIC base, we cannot also have a
8947     // BaseReg specified.
8948     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8949       return false;
8950
8951     // If lower 4G is not available, then we must use rip-relative addressing.
8952     if ((M != CodeModel::Small || R != Reloc::Static) &&
8953         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8954       return false;
8955   }
8956
8957   switch (AM.Scale) {
8958   case 0:
8959   case 1:
8960   case 2:
8961   case 4:
8962   case 8:
8963     // These scales always work.
8964     break;
8965   case 3:
8966   case 5:
8967   case 9:
8968     // These scales are formed with basereg+scalereg.  Only accept if there is
8969     // no basereg yet.
8970     if (AM.HasBaseReg)
8971       return false;
8972     break;
8973   default:  // Other stuff never works.
8974     return false;
8975   }
8976
8977   return true;
8978 }
8979
8980
8981 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8982   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8983     return false;
8984   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8985   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8986   if (NumBits1 <= NumBits2)
8987     return false;
8988   return true;
8989 }
8990
8991 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8992   if (!VT1.isInteger() || !VT2.isInteger())
8993     return false;
8994   unsigned NumBits1 = VT1.getSizeInBits();
8995   unsigned NumBits2 = VT2.getSizeInBits();
8996   if (NumBits1 <= NumBits2)
8997     return false;
8998   return true;
8999 }
9000
9001 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9002   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9003   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9004 }
9005
9006 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9007   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9008   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9009 }
9010
9011 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9012   // i16 instructions are longer (0x66 prefix) and potentially slower.
9013   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9014 }
9015
9016 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9017 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9018 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9019 /// are assumed to be legal.
9020 bool
9021 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9022                                       EVT VT) const {
9023   // Very little shuffling can be done for 64-bit vectors right now.
9024   if (VT.getSizeInBits() == 64)
9025     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9026
9027   // FIXME: pshufb, blends, shifts.
9028   return (VT.getVectorNumElements() == 2 ||
9029           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9030           isMOVLMask(M, VT) ||
9031           isSHUFPMask(M, VT) ||
9032           isPSHUFDMask(M, VT) ||
9033           isPSHUFHWMask(M, VT) ||
9034           isPSHUFLWMask(M, VT) ||
9035           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9036           isUNPCKLMask(M, VT) ||
9037           isUNPCKHMask(M, VT) ||
9038           isUNPCKL_v_undef_Mask(M, VT) ||
9039           isUNPCKH_v_undef_Mask(M, VT));
9040 }
9041
9042 bool
9043 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9044                                           EVT VT) const {
9045   unsigned NumElts = VT.getVectorNumElements();
9046   // FIXME: This collection of masks seems suspect.
9047   if (NumElts == 2)
9048     return true;
9049   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9050     return (isMOVLMask(Mask, VT)  ||
9051             isCommutedMOVLMask(Mask, VT, true) ||
9052             isSHUFPMask(Mask, VT) ||
9053             isCommutedSHUFPMask(Mask, VT));
9054   }
9055   return false;
9056 }
9057
9058 //===----------------------------------------------------------------------===//
9059 //                           X86 Scheduler Hooks
9060 //===----------------------------------------------------------------------===//
9061
9062 // private utility function
9063 MachineBasicBlock *
9064 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9065                                                        MachineBasicBlock *MBB,
9066                                                        unsigned regOpc,
9067                                                        unsigned immOpc,
9068                                                        unsigned LoadOpc,
9069                                                        unsigned CXchgOpc,
9070                                                        unsigned notOpc,
9071                                                        unsigned EAXreg,
9072                                                        TargetRegisterClass *RC,
9073                                                        bool invSrc) const {
9074   // For the atomic bitwise operator, we generate
9075   //   thisMBB:
9076   //   newMBB:
9077   //     ld  t1 = [bitinstr.addr]
9078   //     op  t2 = t1, [bitinstr.val]
9079   //     mov EAX = t1
9080   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9081   //     bz  newMBB
9082   //     fallthrough -->nextMBB
9083   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9084   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9085   MachineFunction::iterator MBBIter = MBB;
9086   ++MBBIter;
9087
9088   /// First build the CFG
9089   MachineFunction *F = MBB->getParent();
9090   MachineBasicBlock *thisMBB = MBB;
9091   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9092   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9093   F->insert(MBBIter, newMBB);
9094   F->insert(MBBIter, nextMBB);
9095
9096   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9097   nextMBB->splice(nextMBB->begin(), thisMBB,
9098                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9099                   thisMBB->end());
9100   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9101
9102   // Update thisMBB to fall through to newMBB
9103   thisMBB->addSuccessor(newMBB);
9104
9105   // newMBB jumps to itself and fall through to nextMBB
9106   newMBB->addSuccessor(nextMBB);
9107   newMBB->addSuccessor(newMBB);
9108
9109   // Insert instructions into newMBB based on incoming instruction
9110   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9111          "unexpected number of operands");
9112   DebugLoc dl = bInstr->getDebugLoc();
9113   MachineOperand& destOper = bInstr->getOperand(0);
9114   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9115   int numArgs = bInstr->getNumOperands() - 1;
9116   for (int i=0; i < numArgs; ++i)
9117     argOpers[i] = &bInstr->getOperand(i+1);
9118
9119   // x86 address has 4 operands: base, index, scale, and displacement
9120   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9121   int valArgIndx = lastAddrIndx + 1;
9122
9123   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9124   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9125   for (int i=0; i <= lastAddrIndx; ++i)
9126     (*MIB).addOperand(*argOpers[i]);
9127
9128   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9129   if (invSrc) {
9130     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9131   }
9132   else
9133     tt = t1;
9134
9135   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9136   assert((argOpers[valArgIndx]->isReg() ||
9137           argOpers[valArgIndx]->isImm()) &&
9138          "invalid operand");
9139   if (argOpers[valArgIndx]->isReg())
9140     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9141   else
9142     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9143   MIB.addReg(tt);
9144   (*MIB).addOperand(*argOpers[valArgIndx]);
9145
9146   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9147   MIB.addReg(t1);
9148
9149   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9150   for (int i=0; i <= lastAddrIndx; ++i)
9151     (*MIB).addOperand(*argOpers[i]);
9152   MIB.addReg(t2);
9153   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9154   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9155                     bInstr->memoperands_end());
9156
9157   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9158   MIB.addReg(EAXreg);
9159
9160   // insert branch
9161   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9162
9163   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9164   return nextMBB;
9165 }
9166
9167 // private utility function:  64 bit atomics on 32 bit host.
9168 MachineBasicBlock *
9169 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9170                                                        MachineBasicBlock *MBB,
9171                                                        unsigned regOpcL,
9172                                                        unsigned regOpcH,
9173                                                        unsigned immOpcL,
9174                                                        unsigned immOpcH,
9175                                                        bool invSrc) const {
9176   // For the atomic bitwise operator, we generate
9177   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9178   //     ld t1,t2 = [bitinstr.addr]
9179   //   newMBB:
9180   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9181   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9182   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9183   //     mov ECX, EBX <- t5, t6
9184   //     mov EAX, EDX <- t1, t2
9185   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9186   //     mov t3, t4 <- EAX, EDX
9187   //     bz  newMBB
9188   //     result in out1, out2
9189   //     fallthrough -->nextMBB
9190
9191   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9192   const unsigned LoadOpc = X86::MOV32rm;
9193   const unsigned NotOpc = X86::NOT32r;
9194   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9195   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9196   MachineFunction::iterator MBBIter = MBB;
9197   ++MBBIter;
9198
9199   /// First build the CFG
9200   MachineFunction *F = MBB->getParent();
9201   MachineBasicBlock *thisMBB = MBB;
9202   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9203   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9204   F->insert(MBBIter, newMBB);
9205   F->insert(MBBIter, nextMBB);
9206
9207   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9208   nextMBB->splice(nextMBB->begin(), thisMBB,
9209                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9210                   thisMBB->end());
9211   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9212
9213   // Update thisMBB to fall through to newMBB
9214   thisMBB->addSuccessor(newMBB);
9215
9216   // newMBB jumps to itself and fall through to nextMBB
9217   newMBB->addSuccessor(nextMBB);
9218   newMBB->addSuccessor(newMBB);
9219
9220   DebugLoc dl = bInstr->getDebugLoc();
9221   // Insert instructions into newMBB based on incoming instruction
9222   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9223   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9224          "unexpected number of operands");
9225   MachineOperand& dest1Oper = bInstr->getOperand(0);
9226   MachineOperand& dest2Oper = bInstr->getOperand(1);
9227   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9228   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9229     argOpers[i] = &bInstr->getOperand(i+2);
9230
9231     // We use some of the operands multiple times, so conservatively just
9232     // clear any kill flags that might be present.
9233     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9234       argOpers[i]->setIsKill(false);
9235   }
9236
9237   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9238   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9239
9240   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9241   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9242   for (int i=0; i <= lastAddrIndx; ++i)
9243     (*MIB).addOperand(*argOpers[i]);
9244   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9245   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9246   // add 4 to displacement.
9247   for (int i=0; i <= lastAddrIndx-2; ++i)
9248     (*MIB).addOperand(*argOpers[i]);
9249   MachineOperand newOp3 = *(argOpers[3]);
9250   if (newOp3.isImm())
9251     newOp3.setImm(newOp3.getImm()+4);
9252   else
9253     newOp3.setOffset(newOp3.getOffset()+4);
9254   (*MIB).addOperand(newOp3);
9255   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9256
9257   // t3/4 are defined later, at the bottom of the loop
9258   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9259   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9260   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9261     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9262   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9263     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9264
9265   // The subsequent operations should be using the destination registers of
9266   //the PHI instructions.
9267   if (invSrc) {
9268     t1 = F->getRegInfo().createVirtualRegister(RC);
9269     t2 = F->getRegInfo().createVirtualRegister(RC);
9270     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9271     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9272   } else {
9273     t1 = dest1Oper.getReg();
9274     t2 = dest2Oper.getReg();
9275   }
9276
9277   int valArgIndx = lastAddrIndx + 1;
9278   assert((argOpers[valArgIndx]->isReg() ||
9279           argOpers[valArgIndx]->isImm()) &&
9280          "invalid operand");
9281   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9282   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9283   if (argOpers[valArgIndx]->isReg())
9284     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9285   else
9286     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9287   if (regOpcL != X86::MOV32rr)
9288     MIB.addReg(t1);
9289   (*MIB).addOperand(*argOpers[valArgIndx]);
9290   assert(argOpers[valArgIndx + 1]->isReg() ==
9291          argOpers[valArgIndx]->isReg());
9292   assert(argOpers[valArgIndx + 1]->isImm() ==
9293          argOpers[valArgIndx]->isImm());
9294   if (argOpers[valArgIndx + 1]->isReg())
9295     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9296   else
9297     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9298   if (regOpcH != X86::MOV32rr)
9299     MIB.addReg(t2);
9300   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9301
9302   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9303   MIB.addReg(t1);
9304   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9305   MIB.addReg(t2);
9306
9307   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9308   MIB.addReg(t5);
9309   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9310   MIB.addReg(t6);
9311
9312   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9313   for (int i=0; i <= lastAddrIndx; ++i)
9314     (*MIB).addOperand(*argOpers[i]);
9315
9316   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9317   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9318                     bInstr->memoperands_end());
9319
9320   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9321   MIB.addReg(X86::EAX);
9322   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9323   MIB.addReg(X86::EDX);
9324
9325   // insert branch
9326   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9327
9328   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9329   return nextMBB;
9330 }
9331
9332 // private utility function
9333 MachineBasicBlock *
9334 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9335                                                       MachineBasicBlock *MBB,
9336                                                       unsigned cmovOpc) const {
9337   // For the atomic min/max operator, we generate
9338   //   thisMBB:
9339   //   newMBB:
9340   //     ld t1 = [min/max.addr]
9341   //     mov t2 = [min/max.val]
9342   //     cmp  t1, t2
9343   //     cmov[cond] t2 = t1
9344   //     mov EAX = t1
9345   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9346   //     bz   newMBB
9347   //     fallthrough -->nextMBB
9348   //
9349   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9350   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9351   MachineFunction::iterator MBBIter = MBB;
9352   ++MBBIter;
9353
9354   /// First build the CFG
9355   MachineFunction *F = MBB->getParent();
9356   MachineBasicBlock *thisMBB = MBB;
9357   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9358   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9359   F->insert(MBBIter, newMBB);
9360   F->insert(MBBIter, nextMBB);
9361
9362   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9363   nextMBB->splice(nextMBB->begin(), thisMBB,
9364                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9365                   thisMBB->end());
9366   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9367
9368   // Update thisMBB to fall through to newMBB
9369   thisMBB->addSuccessor(newMBB);
9370
9371   // newMBB jumps to newMBB and fall through to nextMBB
9372   newMBB->addSuccessor(nextMBB);
9373   newMBB->addSuccessor(newMBB);
9374
9375   DebugLoc dl = mInstr->getDebugLoc();
9376   // Insert instructions into newMBB based on incoming instruction
9377   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9378          "unexpected number of operands");
9379   MachineOperand& destOper = mInstr->getOperand(0);
9380   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9381   int numArgs = mInstr->getNumOperands() - 1;
9382   for (int i=0; i < numArgs; ++i)
9383     argOpers[i] = &mInstr->getOperand(i+1);
9384
9385   // x86 address has 4 operands: base, index, scale, and displacement
9386   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9387   int valArgIndx = lastAddrIndx + 1;
9388
9389   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9390   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9391   for (int i=0; i <= lastAddrIndx; ++i)
9392     (*MIB).addOperand(*argOpers[i]);
9393
9394   // We only support register and immediate values
9395   assert((argOpers[valArgIndx]->isReg() ||
9396           argOpers[valArgIndx]->isImm()) &&
9397          "invalid operand");
9398
9399   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9400   if (argOpers[valArgIndx]->isReg())
9401     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9402   else
9403     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9404   (*MIB).addOperand(*argOpers[valArgIndx]);
9405
9406   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9407   MIB.addReg(t1);
9408
9409   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9410   MIB.addReg(t1);
9411   MIB.addReg(t2);
9412
9413   // Generate movc
9414   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9415   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9416   MIB.addReg(t2);
9417   MIB.addReg(t1);
9418
9419   // Cmp and exchange if none has modified the memory location
9420   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9421   for (int i=0; i <= lastAddrIndx; ++i)
9422     (*MIB).addOperand(*argOpers[i]);
9423   MIB.addReg(t3);
9424   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9425   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9426                     mInstr->memoperands_end());
9427
9428   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9429   MIB.addReg(X86::EAX);
9430
9431   // insert branch
9432   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9433
9434   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9435   return nextMBB;
9436 }
9437
9438 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9439 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9440 // in the .td file.
9441 MachineBasicBlock *
9442 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9443                             unsigned numArgs, bool memArg) const {
9444
9445   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9446          "Target must have SSE4.2 or AVX features enabled");
9447
9448   DebugLoc dl = MI->getDebugLoc();
9449   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9450
9451   unsigned Opc;
9452
9453   if (!Subtarget->hasAVX()) {
9454     if (memArg)
9455       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9456     else
9457       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9458   } else {
9459     if (memArg)
9460       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9461     else
9462       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9463   }
9464
9465   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9466
9467   for (unsigned i = 0; i < numArgs; ++i) {
9468     MachineOperand &Op = MI->getOperand(i+1);
9469
9470     if (!(Op.isReg() && Op.isImplicit()))
9471       MIB.addOperand(Op);
9472   }
9473
9474   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9475     .addReg(X86::XMM0);
9476
9477   MI->eraseFromParent();
9478
9479   return BB;
9480 }
9481
9482 MachineBasicBlock *
9483 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9484                                                  MachineInstr *MI,
9485                                                  MachineBasicBlock *MBB) const {
9486   // Emit code to save XMM registers to the stack. The ABI says that the
9487   // number of registers to save is given in %al, so it's theoretically
9488   // possible to do an indirect jump trick to avoid saving all of them,
9489   // however this code takes a simpler approach and just executes all
9490   // of the stores if %al is non-zero. It's less code, and it's probably
9491   // easier on the hardware branch predictor, and stores aren't all that
9492   // expensive anyway.
9493
9494   // Create the new basic blocks. One block contains all the XMM stores,
9495   // and one block is the final destination regardless of whether any
9496   // stores were performed.
9497   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9498   MachineFunction *F = MBB->getParent();
9499   MachineFunction::iterator MBBIter = MBB;
9500   ++MBBIter;
9501   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9502   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9503   F->insert(MBBIter, XMMSaveMBB);
9504   F->insert(MBBIter, EndMBB);
9505
9506   // Transfer the remainder of MBB and its successor edges to EndMBB.
9507   EndMBB->splice(EndMBB->begin(), MBB,
9508                  llvm::next(MachineBasicBlock::iterator(MI)),
9509                  MBB->end());
9510   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9511
9512   // The original block will now fall through to the XMM save block.
9513   MBB->addSuccessor(XMMSaveMBB);
9514   // The XMMSaveMBB will fall through to the end block.
9515   XMMSaveMBB->addSuccessor(EndMBB);
9516
9517   // Now add the instructions.
9518   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9519   DebugLoc DL = MI->getDebugLoc();
9520
9521   unsigned CountReg = MI->getOperand(0).getReg();
9522   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9523   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9524
9525   if (!Subtarget->isTargetWin64()) {
9526     // If %al is 0, branch around the XMM save block.
9527     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9528     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9529     MBB->addSuccessor(EndMBB);
9530   }
9531
9532   // In the XMM save block, save all the XMM argument registers.
9533   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9534     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9535     MachineMemOperand *MMO =
9536       F->getMachineMemOperand(
9537           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9538         MachineMemOperand::MOStore,
9539         /*Size=*/16, /*Align=*/16);
9540     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9541       .addFrameIndex(RegSaveFrameIndex)
9542       .addImm(/*Scale=*/1)
9543       .addReg(/*IndexReg=*/0)
9544       .addImm(/*Disp=*/Offset)
9545       .addReg(/*Segment=*/0)
9546       .addReg(MI->getOperand(i).getReg())
9547       .addMemOperand(MMO);
9548   }
9549
9550   MI->eraseFromParent();   // The pseudo instruction is gone now.
9551
9552   return EndMBB;
9553 }
9554
9555 MachineBasicBlock *
9556 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9557                                      MachineBasicBlock *BB) const {
9558   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9559   DebugLoc DL = MI->getDebugLoc();
9560
9561   // To "insert" a SELECT_CC instruction, we actually have to insert the
9562   // diamond control-flow pattern.  The incoming instruction knows the
9563   // destination vreg to set, the condition code register to branch on, the
9564   // true/false values to select between, and a branch opcode to use.
9565   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9566   MachineFunction::iterator It = BB;
9567   ++It;
9568
9569   //  thisMBB:
9570   //  ...
9571   //   TrueVal = ...
9572   //   cmpTY ccX, r1, r2
9573   //   bCC copy1MBB
9574   //   fallthrough --> copy0MBB
9575   MachineBasicBlock *thisMBB = BB;
9576   MachineFunction *F = BB->getParent();
9577   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9578   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9579   F->insert(It, copy0MBB);
9580   F->insert(It, sinkMBB);
9581
9582   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9583   // live into the sink and copy blocks.
9584   const MachineFunction *MF = BB->getParent();
9585   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9586   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9587
9588   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9589     const MachineOperand &MO = MI->getOperand(I);
9590     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9591     unsigned Reg = MO.getReg();
9592     if (Reg != X86::EFLAGS) continue;
9593     copy0MBB->addLiveIn(Reg);
9594     sinkMBB->addLiveIn(Reg);
9595   }
9596
9597   // Transfer the remainder of BB and its successor edges to sinkMBB.
9598   sinkMBB->splice(sinkMBB->begin(), BB,
9599                   llvm::next(MachineBasicBlock::iterator(MI)),
9600                   BB->end());
9601   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9602
9603   // Add the true and fallthrough blocks as its successors.
9604   BB->addSuccessor(copy0MBB);
9605   BB->addSuccessor(sinkMBB);
9606
9607   // Create the conditional branch instruction.
9608   unsigned Opc =
9609     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9610   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9611
9612   //  copy0MBB:
9613   //   %FalseValue = ...
9614   //   # fallthrough to sinkMBB
9615   copy0MBB->addSuccessor(sinkMBB);
9616
9617   //  sinkMBB:
9618   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9619   //  ...
9620   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9621           TII->get(X86::PHI), MI->getOperand(0).getReg())
9622     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9623     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9624
9625   MI->eraseFromParent();   // The pseudo instruction is gone now.
9626   return sinkMBB;
9627 }
9628
9629 MachineBasicBlock *
9630 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9631                                           MachineBasicBlock *BB) const {
9632   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9633   DebugLoc DL = MI->getDebugLoc();
9634
9635   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9636   // non-trivial part is impdef of ESP.
9637   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9638   // mingw-w64.
9639
9640   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9641     .addExternalSymbol("_alloca")
9642     .addReg(X86::EAX, RegState::Implicit)
9643     .addReg(X86::ESP, RegState::Implicit)
9644     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9645     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9646     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9647
9648   MI->eraseFromParent();   // The pseudo instruction is gone now.
9649   return BB;
9650 }
9651
9652 MachineBasicBlock *
9653 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9654                                       MachineBasicBlock *BB) const {
9655   // This is pretty easy.  We're taking the value that we received from
9656   // our load from the relocation, sticking it in either RDI (x86-64)
9657   // or EAX and doing an indirect call.  The return value will then
9658   // be in the normal return register.
9659   const X86InstrInfo *TII 
9660     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9661   DebugLoc DL = MI->getDebugLoc();
9662   MachineFunction *F = BB->getParent();
9663   bool IsWin64 = Subtarget->isTargetWin64();
9664   
9665   assert(MI->getOperand(3).isGlobal() && "This should be a global");
9666   
9667   if (Subtarget->is64Bit()) {
9668     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9669                                       TII->get(X86::MOV64rm), X86::RDI)
9670     .addReg(X86::RIP)
9671     .addImm(0).addReg(0)
9672     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9673                       MI->getOperand(3).getTargetFlags())
9674     .addReg(0);
9675     MIB = BuildMI(*BB, MI, DL, TII->get(IsWin64 ? X86::WINCALL64m : X86::CALL64m));
9676     addDirectMem(MIB, X86::RDI);
9677   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9678     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9679                                       TII->get(X86::MOV32rm), X86::EAX)
9680     .addReg(0)
9681     .addImm(0).addReg(0)
9682     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9683                       MI->getOperand(3).getTargetFlags())
9684     .addReg(0);
9685     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9686     addDirectMem(MIB, X86::EAX);
9687   } else {
9688     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9689                                       TII->get(X86::MOV32rm), X86::EAX)
9690     .addReg(TII->getGlobalBaseReg(F))
9691     .addImm(0).addReg(0)
9692     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
9693                       MI->getOperand(3).getTargetFlags())
9694     .addReg(0);
9695     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9696     addDirectMem(MIB, X86::EAX);
9697   }
9698   
9699   MI->eraseFromParent(); // The pseudo instruction is gone now.
9700   return BB;
9701 }
9702
9703 MachineBasicBlock *
9704 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9705                                                MachineBasicBlock *BB) const {
9706   switch (MI->getOpcode()) {
9707   default: assert(false && "Unexpected instr type to insert");
9708   case X86::MINGW_ALLOCA:
9709     return EmitLoweredMingwAlloca(MI, BB);
9710   case X86::TLSCall_32:
9711   case X86::TLSCall_64:
9712     return EmitLoweredTLSCall(MI, BB);
9713   case X86::CMOV_GR8:
9714   case X86::CMOV_V1I64:
9715   case X86::CMOV_FR32:
9716   case X86::CMOV_FR64:
9717   case X86::CMOV_V4F32:
9718   case X86::CMOV_V2F64:
9719   case X86::CMOV_V2I64:
9720   case X86::CMOV_GR16:
9721   case X86::CMOV_GR32:
9722   case X86::CMOV_RFP32:
9723   case X86::CMOV_RFP64:
9724   case X86::CMOV_RFP80:
9725     return EmitLoweredSelect(MI, BB);
9726
9727   case X86::FP32_TO_INT16_IN_MEM:
9728   case X86::FP32_TO_INT32_IN_MEM:
9729   case X86::FP32_TO_INT64_IN_MEM:
9730   case X86::FP64_TO_INT16_IN_MEM:
9731   case X86::FP64_TO_INT32_IN_MEM:
9732   case X86::FP64_TO_INT64_IN_MEM:
9733   case X86::FP80_TO_INT16_IN_MEM:
9734   case X86::FP80_TO_INT32_IN_MEM:
9735   case X86::FP80_TO_INT64_IN_MEM: {
9736     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9737     DebugLoc DL = MI->getDebugLoc();
9738
9739     // Change the floating point control register to use "round towards zero"
9740     // mode when truncating to an integer value.
9741     MachineFunction *F = BB->getParent();
9742     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9743     addFrameReference(BuildMI(*BB, MI, DL,
9744                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
9745
9746     // Load the old value of the high byte of the control word...
9747     unsigned OldCW =
9748       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9749     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9750                       CWFrameIdx);
9751
9752     // Set the high part to be round to zero...
9753     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9754       .addImm(0xC7F);
9755
9756     // Reload the modified control word now...
9757     addFrameReference(BuildMI(*BB, MI, DL,
9758                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9759
9760     // Restore the memory image of control word to original value
9761     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9762       .addReg(OldCW);
9763
9764     // Get the X86 opcode to use.
9765     unsigned Opc;
9766     switch (MI->getOpcode()) {
9767     default: llvm_unreachable("illegal opcode!");
9768     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9769     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9770     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9771     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9772     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9773     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9774     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9775     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9776     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9777     }
9778
9779     X86AddressMode AM;
9780     MachineOperand &Op = MI->getOperand(0);
9781     if (Op.isReg()) {
9782       AM.BaseType = X86AddressMode::RegBase;
9783       AM.Base.Reg = Op.getReg();
9784     } else {
9785       AM.BaseType = X86AddressMode::FrameIndexBase;
9786       AM.Base.FrameIndex = Op.getIndex();
9787     }
9788     Op = MI->getOperand(1);
9789     if (Op.isImm())
9790       AM.Scale = Op.getImm();
9791     Op = MI->getOperand(2);
9792     if (Op.isImm())
9793       AM.IndexReg = Op.getImm();
9794     Op = MI->getOperand(3);
9795     if (Op.isGlobal()) {
9796       AM.GV = Op.getGlobal();
9797     } else {
9798       AM.Disp = Op.getImm();
9799     }
9800     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9801                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9802
9803     // Reload the original control word now.
9804     addFrameReference(BuildMI(*BB, MI, DL,
9805                               TII->get(X86::FLDCW16m)), CWFrameIdx);
9806
9807     MI->eraseFromParent();   // The pseudo instruction is gone now.
9808     return BB;
9809   }
9810     // String/text processing lowering.
9811   case X86::PCMPISTRM128REG:
9812   case X86::VPCMPISTRM128REG:
9813     return EmitPCMP(MI, BB, 3, false /* in-mem */);
9814   case X86::PCMPISTRM128MEM:
9815   case X86::VPCMPISTRM128MEM:
9816     return EmitPCMP(MI, BB, 3, true /* in-mem */);
9817   case X86::PCMPESTRM128REG:
9818   case X86::VPCMPESTRM128REG:
9819     return EmitPCMP(MI, BB, 5, false /* in mem */);
9820   case X86::PCMPESTRM128MEM:
9821   case X86::VPCMPESTRM128MEM:
9822     return EmitPCMP(MI, BB, 5, true /* in mem */);
9823
9824     // Atomic Lowering.
9825   case X86::ATOMAND32:
9826     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9827                                                X86::AND32ri, X86::MOV32rm,
9828                                                X86::LCMPXCHG32,
9829                                                X86::NOT32r, X86::EAX,
9830                                                X86::GR32RegisterClass);
9831   case X86::ATOMOR32:
9832     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9833                                                X86::OR32ri, X86::MOV32rm,
9834                                                X86::LCMPXCHG32,
9835                                                X86::NOT32r, X86::EAX,
9836                                                X86::GR32RegisterClass);
9837   case X86::ATOMXOR32:
9838     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9839                                                X86::XOR32ri, X86::MOV32rm,
9840                                                X86::LCMPXCHG32,
9841                                                X86::NOT32r, X86::EAX,
9842                                                X86::GR32RegisterClass);
9843   case X86::ATOMNAND32:
9844     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9845                                                X86::AND32ri, X86::MOV32rm,
9846                                                X86::LCMPXCHG32,
9847                                                X86::NOT32r, X86::EAX,
9848                                                X86::GR32RegisterClass, true);
9849   case X86::ATOMMIN32:
9850     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9851   case X86::ATOMMAX32:
9852     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9853   case X86::ATOMUMIN32:
9854     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9855   case X86::ATOMUMAX32:
9856     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9857
9858   case X86::ATOMAND16:
9859     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9860                                                X86::AND16ri, X86::MOV16rm,
9861                                                X86::LCMPXCHG16,
9862                                                X86::NOT16r, X86::AX,
9863                                                X86::GR16RegisterClass);
9864   case X86::ATOMOR16:
9865     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9866                                                X86::OR16ri, X86::MOV16rm,
9867                                                X86::LCMPXCHG16,
9868                                                X86::NOT16r, X86::AX,
9869                                                X86::GR16RegisterClass);
9870   case X86::ATOMXOR16:
9871     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9872                                                X86::XOR16ri, X86::MOV16rm,
9873                                                X86::LCMPXCHG16,
9874                                                X86::NOT16r, X86::AX,
9875                                                X86::GR16RegisterClass);
9876   case X86::ATOMNAND16:
9877     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9878                                                X86::AND16ri, X86::MOV16rm,
9879                                                X86::LCMPXCHG16,
9880                                                X86::NOT16r, X86::AX,
9881                                                X86::GR16RegisterClass, true);
9882   case X86::ATOMMIN16:
9883     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9884   case X86::ATOMMAX16:
9885     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9886   case X86::ATOMUMIN16:
9887     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9888   case X86::ATOMUMAX16:
9889     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9890
9891   case X86::ATOMAND8:
9892     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9893                                                X86::AND8ri, X86::MOV8rm,
9894                                                X86::LCMPXCHG8,
9895                                                X86::NOT8r, X86::AL,
9896                                                X86::GR8RegisterClass);
9897   case X86::ATOMOR8:
9898     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9899                                                X86::OR8ri, X86::MOV8rm,
9900                                                X86::LCMPXCHG8,
9901                                                X86::NOT8r, X86::AL,
9902                                                X86::GR8RegisterClass);
9903   case X86::ATOMXOR8:
9904     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9905                                                X86::XOR8ri, X86::MOV8rm,
9906                                                X86::LCMPXCHG8,
9907                                                X86::NOT8r, X86::AL,
9908                                                X86::GR8RegisterClass);
9909   case X86::ATOMNAND8:
9910     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9911                                                X86::AND8ri, X86::MOV8rm,
9912                                                X86::LCMPXCHG8,
9913                                                X86::NOT8r, X86::AL,
9914                                                X86::GR8RegisterClass, true);
9915   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9916   // This group is for 64-bit host.
9917   case X86::ATOMAND64:
9918     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9919                                                X86::AND64ri32, X86::MOV64rm,
9920                                                X86::LCMPXCHG64,
9921                                                X86::NOT64r, X86::RAX,
9922                                                X86::GR64RegisterClass);
9923   case X86::ATOMOR64:
9924     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9925                                                X86::OR64ri32, X86::MOV64rm,
9926                                                X86::LCMPXCHG64,
9927                                                X86::NOT64r, X86::RAX,
9928                                                X86::GR64RegisterClass);
9929   case X86::ATOMXOR64:
9930     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9931                                                X86::XOR64ri32, X86::MOV64rm,
9932                                                X86::LCMPXCHG64,
9933                                                X86::NOT64r, X86::RAX,
9934                                                X86::GR64RegisterClass);
9935   case X86::ATOMNAND64:
9936     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9937                                                X86::AND64ri32, X86::MOV64rm,
9938                                                X86::LCMPXCHG64,
9939                                                X86::NOT64r, X86::RAX,
9940                                                X86::GR64RegisterClass, true);
9941   case X86::ATOMMIN64:
9942     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9943   case X86::ATOMMAX64:
9944     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9945   case X86::ATOMUMIN64:
9946     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9947   case X86::ATOMUMAX64:
9948     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9949
9950   // This group does 64-bit operations on a 32-bit host.
9951   case X86::ATOMAND6432:
9952     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9953                                                X86::AND32rr, X86::AND32rr,
9954                                                X86::AND32ri, X86::AND32ri,
9955                                                false);
9956   case X86::ATOMOR6432:
9957     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9958                                                X86::OR32rr, X86::OR32rr,
9959                                                X86::OR32ri, X86::OR32ri,
9960                                                false);
9961   case X86::ATOMXOR6432:
9962     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9963                                                X86::XOR32rr, X86::XOR32rr,
9964                                                X86::XOR32ri, X86::XOR32ri,
9965                                                false);
9966   case X86::ATOMNAND6432:
9967     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9968                                                X86::AND32rr, X86::AND32rr,
9969                                                X86::AND32ri, X86::AND32ri,
9970                                                true);
9971   case X86::ATOMADD6432:
9972     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9973                                                X86::ADD32rr, X86::ADC32rr,
9974                                                X86::ADD32ri, X86::ADC32ri,
9975                                                false);
9976   case X86::ATOMSUB6432:
9977     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9978                                                X86::SUB32rr, X86::SBB32rr,
9979                                                X86::SUB32ri, X86::SBB32ri,
9980                                                false);
9981   case X86::ATOMSWAP6432:
9982     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9983                                                X86::MOV32rr, X86::MOV32rr,
9984                                                X86::MOV32ri, X86::MOV32ri,
9985                                                false);
9986   case X86::VASTART_SAVE_XMM_REGS:
9987     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9988   }
9989 }
9990
9991 //===----------------------------------------------------------------------===//
9992 //                           X86 Optimization Hooks
9993 //===----------------------------------------------------------------------===//
9994
9995 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9996                                                        const APInt &Mask,
9997                                                        APInt &KnownZero,
9998                                                        APInt &KnownOne,
9999                                                        const SelectionDAG &DAG,
10000                                                        unsigned Depth) const {
10001   unsigned Opc = Op.getOpcode();
10002   assert((Opc >= ISD::BUILTIN_OP_END ||
10003           Opc == ISD::INTRINSIC_WO_CHAIN ||
10004           Opc == ISD::INTRINSIC_W_CHAIN ||
10005           Opc == ISD::INTRINSIC_VOID) &&
10006          "Should use MaskedValueIsZero if you don't know whether Op"
10007          " is a target node!");
10008
10009   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10010   switch (Opc) {
10011   default: break;
10012   case X86ISD::ADD:
10013   case X86ISD::SUB:
10014   case X86ISD::SMUL:
10015   case X86ISD::UMUL:
10016   case X86ISD::INC:
10017   case X86ISD::DEC:
10018   case X86ISD::OR:
10019   case X86ISD::XOR:
10020   case X86ISD::AND:
10021     // These nodes' second result is a boolean.
10022     if (Op.getResNo() == 0)
10023       break;
10024     // Fallthrough
10025   case X86ISD::SETCC:
10026     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10027                                        Mask.getBitWidth() - 1);
10028     break;
10029   }
10030 }
10031
10032 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10033                                                          unsigned Depth) const {
10034   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10035   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10036     return Op.getValueType().getScalarType().getSizeInBits();
10037   
10038   // Fallback case.
10039   return 1;
10040 }
10041
10042 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10043 /// node is a GlobalAddress + offset.
10044 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10045                                        const GlobalValue* &GA,
10046                                        int64_t &Offset) const {
10047   if (N->getOpcode() == X86ISD::Wrapper) {
10048     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10049       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10050       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10051       return true;
10052     }
10053   }
10054   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10055 }
10056
10057 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10058 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10059 /// if the load addresses are consecutive, non-overlapping, and in the right
10060 /// order.
10061 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10062                                      const TargetLowering &TLI) {
10063   DebugLoc dl = N->getDebugLoc();
10064   EVT VT = N->getValueType(0);
10065
10066   if (VT.getSizeInBits() != 128)
10067     return SDValue();
10068
10069   SmallVector<SDValue, 16> Elts;
10070   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10071     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10072
10073   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10074 }
10075
10076 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10077 /// generation and convert it from being a bunch of shuffles and extracts
10078 /// to a simple store and scalar loads to extract the elements.
10079 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10080                                                 const TargetLowering &TLI) {
10081   SDValue InputVector = N->getOperand(0);
10082
10083   // Only operate on vectors of 4 elements, where the alternative shuffling
10084   // gets to be more expensive.
10085   if (InputVector.getValueType() != MVT::v4i32)
10086     return SDValue();
10087
10088   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10089   // single use which is a sign-extend or zero-extend, and all elements are
10090   // used.
10091   SmallVector<SDNode *, 4> Uses;
10092   unsigned ExtractedElements = 0;
10093   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10094        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10095     if (UI.getUse().getResNo() != InputVector.getResNo())
10096       return SDValue();
10097
10098     SDNode *Extract = *UI;
10099     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10100       return SDValue();
10101
10102     if (Extract->getValueType(0) != MVT::i32)
10103       return SDValue();
10104     if (!Extract->hasOneUse())
10105       return SDValue();
10106     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10107         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10108       return SDValue();
10109     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10110       return SDValue();
10111
10112     // Record which element was extracted.
10113     ExtractedElements |=
10114       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10115
10116     Uses.push_back(Extract);
10117   }
10118
10119   // If not all the elements were used, this may not be worthwhile.
10120   if (ExtractedElements != 15)
10121     return SDValue();
10122
10123   // Ok, we've now decided to do the transformation.
10124   DebugLoc dl = InputVector.getDebugLoc();
10125
10126   // Store the value to a temporary stack slot.
10127   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10128   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10129                             MachinePointerInfo(), false, false, 0);
10130
10131   // Replace each use (extract) with a load of the appropriate element.
10132   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10133        UE = Uses.end(); UI != UE; ++UI) {
10134     SDNode *Extract = *UI;
10135
10136     // Compute the element's address.
10137     SDValue Idx = Extract->getOperand(1);
10138     unsigned EltSize =
10139         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10140     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10141     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10142
10143     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10144                                      StackPtr, OffsetVal);
10145
10146     // Load the scalar.
10147     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10148                                      ScalarAddr, MachinePointerInfo(),
10149                                      false, false, 0);
10150
10151     // Replace the exact with the load.
10152     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10153   }
10154
10155   // The replacement was made in place; don't return anything.
10156   return SDValue();
10157 }
10158
10159 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10160 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10161                                     const X86Subtarget *Subtarget) {
10162   DebugLoc DL = N->getDebugLoc();
10163   SDValue Cond = N->getOperand(0);
10164   // Get the LHS/RHS of the select.
10165   SDValue LHS = N->getOperand(1);
10166   SDValue RHS = N->getOperand(2);
10167
10168   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10169   // instructions match the semantics of the common C idiom x<y?x:y but not
10170   // x<=y?x:y, because of how they handle negative zero (which can be
10171   // ignored in unsafe-math mode).
10172   if (Subtarget->hasSSE2() &&
10173       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10174       Cond.getOpcode() == ISD::SETCC) {
10175     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10176
10177     unsigned Opcode = 0;
10178     // Check for x CC y ? x : y.
10179     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10180         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10181       switch (CC) {
10182       default: break;
10183       case ISD::SETULT:
10184         // Converting this to a min would handle NaNs incorrectly, and swapping
10185         // the operands would cause it to handle comparisons between positive
10186         // and negative zero incorrectly.
10187         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10188           if (!UnsafeFPMath &&
10189               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10190             break;
10191           std::swap(LHS, RHS);
10192         }
10193         Opcode = X86ISD::FMIN;
10194         break;
10195       case ISD::SETOLE:
10196         // Converting this to a min would handle comparisons between positive
10197         // and negative zero incorrectly.
10198         if (!UnsafeFPMath &&
10199             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10200           break;
10201         Opcode = X86ISD::FMIN;
10202         break;
10203       case ISD::SETULE:
10204         // Converting this to a min would handle both negative zeros and NaNs
10205         // incorrectly, but we can swap the operands to fix both.
10206         std::swap(LHS, RHS);
10207       case ISD::SETOLT:
10208       case ISD::SETLT:
10209       case ISD::SETLE:
10210         Opcode = X86ISD::FMIN;
10211         break;
10212
10213       case ISD::SETOGE:
10214         // Converting this to a max would handle comparisons between positive
10215         // and negative zero incorrectly.
10216         if (!UnsafeFPMath &&
10217             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10218           break;
10219         Opcode = X86ISD::FMAX;
10220         break;
10221       case ISD::SETUGT:
10222         // Converting this to a max would handle NaNs incorrectly, and swapping
10223         // the operands would cause it to handle comparisons between positive
10224         // and negative zero incorrectly.
10225         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10226           if (!UnsafeFPMath &&
10227               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10228             break;
10229           std::swap(LHS, RHS);
10230         }
10231         Opcode = X86ISD::FMAX;
10232         break;
10233       case ISD::SETUGE:
10234         // Converting this to a max would handle both negative zeros and NaNs
10235         // incorrectly, but we can swap the operands to fix both.
10236         std::swap(LHS, RHS);
10237       case ISD::SETOGT:
10238       case ISD::SETGT:
10239       case ISD::SETGE:
10240         Opcode = X86ISD::FMAX;
10241         break;
10242       }
10243     // Check for x CC y ? y : x -- a min/max with reversed arms.
10244     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10245                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10246       switch (CC) {
10247       default: break;
10248       case ISD::SETOGE:
10249         // Converting this to a min would handle comparisons between positive
10250         // and negative zero incorrectly, and swapping the operands would
10251         // cause it to handle NaNs incorrectly.
10252         if (!UnsafeFPMath &&
10253             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10254           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10255             break;
10256           std::swap(LHS, RHS);
10257         }
10258         Opcode = X86ISD::FMIN;
10259         break;
10260       case ISD::SETUGT:
10261         // Converting this to a min would handle NaNs incorrectly.
10262         if (!UnsafeFPMath &&
10263             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10264           break;
10265         Opcode = X86ISD::FMIN;
10266         break;
10267       case ISD::SETUGE:
10268         // Converting this to a min would handle both negative zeros and NaNs
10269         // incorrectly, but we can swap the operands to fix both.
10270         std::swap(LHS, RHS);
10271       case ISD::SETOGT:
10272       case ISD::SETGT:
10273       case ISD::SETGE:
10274         Opcode = X86ISD::FMIN;
10275         break;
10276
10277       case ISD::SETULT:
10278         // Converting this to a max would handle NaNs incorrectly.
10279         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10280           break;
10281         Opcode = X86ISD::FMAX;
10282         break;
10283       case ISD::SETOLE:
10284         // Converting this to a max would handle comparisons between positive
10285         // and negative zero incorrectly, and swapping the operands would
10286         // cause it to handle NaNs incorrectly.
10287         if (!UnsafeFPMath &&
10288             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10289           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10290             break;
10291           std::swap(LHS, RHS);
10292         }
10293         Opcode = X86ISD::FMAX;
10294         break;
10295       case ISD::SETULE:
10296         // Converting this to a max would handle both negative zeros and NaNs
10297         // incorrectly, but we can swap the operands to fix both.
10298         std::swap(LHS, RHS);
10299       case ISD::SETOLT:
10300       case ISD::SETLT:
10301       case ISD::SETLE:
10302         Opcode = X86ISD::FMAX;
10303         break;
10304       }
10305     }
10306
10307     if (Opcode)
10308       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10309   }
10310
10311   // If this is a select between two integer constants, try to do some
10312   // optimizations.
10313   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10314     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10315       // Don't do this for crazy integer types.
10316       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10317         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10318         // so that TrueC (the true value) is larger than FalseC.
10319         bool NeedsCondInvert = false;
10320
10321         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10322             // Efficiently invertible.
10323             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10324              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10325               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10326           NeedsCondInvert = true;
10327           std::swap(TrueC, FalseC);
10328         }
10329
10330         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10331         if (FalseC->getAPIntValue() == 0 &&
10332             TrueC->getAPIntValue().isPowerOf2()) {
10333           if (NeedsCondInvert) // Invert the condition if needed.
10334             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10335                                DAG.getConstant(1, Cond.getValueType()));
10336
10337           // Zero extend the condition if needed.
10338           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10339
10340           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10341           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10342                              DAG.getConstant(ShAmt, MVT::i8));
10343         }
10344
10345         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10346         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10347           if (NeedsCondInvert) // Invert the condition if needed.
10348             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10349                                DAG.getConstant(1, Cond.getValueType()));
10350
10351           // Zero extend the condition if needed.
10352           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10353                              FalseC->getValueType(0), Cond);
10354           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10355                              SDValue(FalseC, 0));
10356         }
10357
10358         // Optimize cases that will turn into an LEA instruction.  This requires
10359         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10360         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10361           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10362           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10363
10364           bool isFastMultiplier = false;
10365           if (Diff < 10) {
10366             switch ((unsigned char)Diff) {
10367               default: break;
10368               case 1:  // result = add base, cond
10369               case 2:  // result = lea base(    , cond*2)
10370               case 3:  // result = lea base(cond, cond*2)
10371               case 4:  // result = lea base(    , cond*4)
10372               case 5:  // result = lea base(cond, cond*4)
10373               case 8:  // result = lea base(    , cond*8)
10374               case 9:  // result = lea base(cond, cond*8)
10375                 isFastMultiplier = true;
10376                 break;
10377             }
10378           }
10379
10380           if (isFastMultiplier) {
10381             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10382             if (NeedsCondInvert) // Invert the condition if needed.
10383               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10384                                  DAG.getConstant(1, Cond.getValueType()));
10385
10386             // Zero extend the condition if needed.
10387             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10388                                Cond);
10389             // Scale the condition by the difference.
10390             if (Diff != 1)
10391               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10392                                  DAG.getConstant(Diff, Cond.getValueType()));
10393
10394             // Add the base if non-zero.
10395             if (FalseC->getAPIntValue() != 0)
10396               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10397                                  SDValue(FalseC, 0));
10398             return Cond;
10399           }
10400         }
10401       }
10402   }
10403
10404   return SDValue();
10405 }
10406
10407 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10408 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10409                                   TargetLowering::DAGCombinerInfo &DCI) {
10410   DebugLoc DL = N->getDebugLoc();
10411
10412   // If the flag operand isn't dead, don't touch this CMOV.
10413   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10414     return SDValue();
10415
10416   // If this is a select between two integer constants, try to do some
10417   // optimizations.  Note that the operands are ordered the opposite of SELECT
10418   // operands.
10419   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10420     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10421       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10422       // larger than FalseC (the false value).
10423       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10424
10425       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10426         CC = X86::GetOppositeBranchCondition(CC);
10427         std::swap(TrueC, FalseC);
10428       }
10429
10430       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10431       // This is efficient for any integer data type (including i8/i16) and
10432       // shift amount.
10433       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10434         SDValue Cond = N->getOperand(3);
10435         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10436                            DAG.getConstant(CC, MVT::i8), Cond);
10437
10438         // Zero extend the condition if needed.
10439         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10440
10441         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10442         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10443                            DAG.getConstant(ShAmt, MVT::i8));
10444         if (N->getNumValues() == 2)  // Dead flag value?
10445           return DCI.CombineTo(N, Cond, SDValue());
10446         return Cond;
10447       }
10448
10449       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10450       // for any integer data type, including i8/i16.
10451       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10452         SDValue Cond = N->getOperand(3);
10453         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10454                            DAG.getConstant(CC, MVT::i8), Cond);
10455
10456         // Zero extend the condition if needed.
10457         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10458                            FalseC->getValueType(0), Cond);
10459         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10460                            SDValue(FalseC, 0));
10461
10462         if (N->getNumValues() == 2)  // Dead flag value?
10463           return DCI.CombineTo(N, Cond, SDValue());
10464         return Cond;
10465       }
10466
10467       // Optimize cases that will turn into an LEA instruction.  This requires
10468       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10469       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10470         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10471         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10472
10473         bool isFastMultiplier = false;
10474         if (Diff < 10) {
10475           switch ((unsigned char)Diff) {
10476           default: break;
10477           case 1:  // result = add base, cond
10478           case 2:  // result = lea base(    , cond*2)
10479           case 3:  // result = lea base(cond, cond*2)
10480           case 4:  // result = lea base(    , cond*4)
10481           case 5:  // result = lea base(cond, cond*4)
10482           case 8:  // result = lea base(    , cond*8)
10483           case 9:  // result = lea base(cond, cond*8)
10484             isFastMultiplier = true;
10485             break;
10486           }
10487         }
10488
10489         if (isFastMultiplier) {
10490           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10491           SDValue Cond = N->getOperand(3);
10492           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10493                              DAG.getConstant(CC, MVT::i8), Cond);
10494           // Zero extend the condition if needed.
10495           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10496                              Cond);
10497           // Scale the condition by the difference.
10498           if (Diff != 1)
10499             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10500                                DAG.getConstant(Diff, Cond.getValueType()));
10501
10502           // Add the base if non-zero.
10503           if (FalseC->getAPIntValue() != 0)
10504             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10505                                SDValue(FalseC, 0));
10506           if (N->getNumValues() == 2)  // Dead flag value?
10507             return DCI.CombineTo(N, Cond, SDValue());
10508           return Cond;
10509         }
10510       }
10511     }
10512   }
10513   return SDValue();
10514 }
10515
10516
10517 /// PerformMulCombine - Optimize a single multiply with constant into two
10518 /// in order to implement it with two cheaper instructions, e.g.
10519 /// LEA + SHL, LEA + LEA.
10520 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10521                                  TargetLowering::DAGCombinerInfo &DCI) {
10522   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10523     return SDValue();
10524
10525   EVT VT = N->getValueType(0);
10526   if (VT != MVT::i64)
10527     return SDValue();
10528
10529   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10530   if (!C)
10531     return SDValue();
10532   uint64_t MulAmt = C->getZExtValue();
10533   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10534     return SDValue();
10535
10536   uint64_t MulAmt1 = 0;
10537   uint64_t MulAmt2 = 0;
10538   if ((MulAmt % 9) == 0) {
10539     MulAmt1 = 9;
10540     MulAmt2 = MulAmt / 9;
10541   } else if ((MulAmt % 5) == 0) {
10542     MulAmt1 = 5;
10543     MulAmt2 = MulAmt / 5;
10544   } else if ((MulAmt % 3) == 0) {
10545     MulAmt1 = 3;
10546     MulAmt2 = MulAmt / 3;
10547   }
10548   if (MulAmt2 &&
10549       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10550     DebugLoc DL = N->getDebugLoc();
10551
10552     if (isPowerOf2_64(MulAmt2) &&
10553         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10554       // If second multiplifer is pow2, issue it first. We want the multiply by
10555       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10556       // is an add.
10557       std::swap(MulAmt1, MulAmt2);
10558
10559     SDValue NewMul;
10560     if (isPowerOf2_64(MulAmt1))
10561       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10562                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10563     else
10564       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10565                            DAG.getConstant(MulAmt1, VT));
10566
10567     if (isPowerOf2_64(MulAmt2))
10568       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10569                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10570     else
10571       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10572                            DAG.getConstant(MulAmt2, VT));
10573
10574     // Do not add new nodes to DAG combiner worklist.
10575     DCI.CombineTo(N, NewMul, false);
10576   }
10577   return SDValue();
10578 }
10579
10580 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10581   SDValue N0 = N->getOperand(0);
10582   SDValue N1 = N->getOperand(1);
10583   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10584   EVT VT = N0.getValueType();
10585
10586   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10587   // since the result of setcc_c is all zero's or all ones.
10588   if (N1C && N0.getOpcode() == ISD::AND &&
10589       N0.getOperand(1).getOpcode() == ISD::Constant) {
10590     SDValue N00 = N0.getOperand(0);
10591     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10592         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10593           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10594          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10595       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10596       APInt ShAmt = N1C->getAPIntValue();
10597       Mask = Mask.shl(ShAmt);
10598       if (Mask != 0)
10599         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10600                            N00, DAG.getConstant(Mask, VT));
10601     }
10602   }
10603
10604   return SDValue();
10605 }
10606
10607 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10608 ///                       when possible.
10609 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10610                                    const X86Subtarget *Subtarget) {
10611   EVT VT = N->getValueType(0);
10612   if (!VT.isVector() && VT.isInteger() &&
10613       N->getOpcode() == ISD::SHL)
10614     return PerformSHLCombine(N, DAG);
10615
10616   // On X86 with SSE2 support, we can transform this to a vector shift if
10617   // all elements are shifted by the same amount.  We can't do this in legalize
10618   // because the a constant vector is typically transformed to a constant pool
10619   // so we have no knowledge of the shift amount.
10620   if (!Subtarget->hasSSE2())
10621     return SDValue();
10622
10623   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10624     return SDValue();
10625
10626   SDValue ShAmtOp = N->getOperand(1);
10627   EVT EltVT = VT.getVectorElementType();
10628   DebugLoc DL = N->getDebugLoc();
10629   SDValue BaseShAmt = SDValue();
10630   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10631     unsigned NumElts = VT.getVectorNumElements();
10632     unsigned i = 0;
10633     for (; i != NumElts; ++i) {
10634       SDValue Arg = ShAmtOp.getOperand(i);
10635       if (Arg.getOpcode() == ISD::UNDEF) continue;
10636       BaseShAmt = Arg;
10637       break;
10638     }
10639     for (; i != NumElts; ++i) {
10640       SDValue Arg = ShAmtOp.getOperand(i);
10641       if (Arg.getOpcode() == ISD::UNDEF) continue;
10642       if (Arg != BaseShAmt) {
10643         return SDValue();
10644       }
10645     }
10646   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10647              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10648     SDValue InVec = ShAmtOp.getOperand(0);
10649     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10650       unsigned NumElts = InVec.getValueType().getVectorNumElements();
10651       unsigned i = 0;
10652       for (; i != NumElts; ++i) {
10653         SDValue Arg = InVec.getOperand(i);
10654         if (Arg.getOpcode() == ISD::UNDEF) continue;
10655         BaseShAmt = Arg;
10656         break;
10657       }
10658     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10659        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10660          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10661          if (C->getZExtValue() == SplatIdx)
10662            BaseShAmt = InVec.getOperand(1);
10663        }
10664     }
10665     if (BaseShAmt.getNode() == 0)
10666       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10667                               DAG.getIntPtrConstant(0));
10668   } else
10669     return SDValue();
10670
10671   // The shift amount is an i32.
10672   if (EltVT.bitsGT(MVT::i32))
10673     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10674   else if (EltVT.bitsLT(MVT::i32))
10675     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10676
10677   // The shift amount is identical so we can do a vector shift.
10678   SDValue  ValOp = N->getOperand(0);
10679   switch (N->getOpcode()) {
10680   default:
10681     llvm_unreachable("Unknown shift opcode!");
10682     break;
10683   case ISD::SHL:
10684     if (VT == MVT::v2i64)
10685       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10686                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10687                          ValOp, BaseShAmt);
10688     if (VT == MVT::v4i32)
10689       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10690                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10691                          ValOp, BaseShAmt);
10692     if (VT == MVT::v8i16)
10693       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10694                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10695                          ValOp, BaseShAmt);
10696     break;
10697   case ISD::SRA:
10698     if (VT == MVT::v4i32)
10699       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10700                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10701                          ValOp, BaseShAmt);
10702     if (VT == MVT::v8i16)
10703       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10704                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10705                          ValOp, BaseShAmt);
10706     break;
10707   case ISD::SRL:
10708     if (VT == MVT::v2i64)
10709       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10710                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10711                          ValOp, BaseShAmt);
10712     if (VT == MVT::v4i32)
10713       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10714                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10715                          ValOp, BaseShAmt);
10716     if (VT ==  MVT::v8i16)
10717       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10718                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10719                          ValOp, BaseShAmt);
10720     break;
10721   }
10722   return SDValue();
10723 }
10724
10725 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10726                                 TargetLowering::DAGCombinerInfo &DCI,
10727                                 const X86Subtarget *Subtarget) {
10728   if (DCI.isBeforeLegalizeOps())
10729     return SDValue();
10730
10731   EVT VT = N->getValueType(0);
10732   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10733     return SDValue();
10734
10735   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10736   SDValue N0 = N->getOperand(0);
10737   SDValue N1 = N->getOperand(1);
10738   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10739     std::swap(N0, N1);
10740   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10741     return SDValue();
10742   if (!N0.hasOneUse() || !N1.hasOneUse())
10743     return SDValue();
10744
10745   SDValue ShAmt0 = N0.getOperand(1);
10746   if (ShAmt0.getValueType() != MVT::i8)
10747     return SDValue();
10748   SDValue ShAmt1 = N1.getOperand(1);
10749   if (ShAmt1.getValueType() != MVT::i8)
10750     return SDValue();
10751   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10752     ShAmt0 = ShAmt0.getOperand(0);
10753   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10754     ShAmt1 = ShAmt1.getOperand(0);
10755
10756   DebugLoc DL = N->getDebugLoc();
10757   unsigned Opc = X86ISD::SHLD;
10758   SDValue Op0 = N0.getOperand(0);
10759   SDValue Op1 = N1.getOperand(0);
10760   if (ShAmt0.getOpcode() == ISD::SUB) {
10761     Opc = X86ISD::SHRD;
10762     std::swap(Op0, Op1);
10763     std::swap(ShAmt0, ShAmt1);
10764   }
10765
10766   unsigned Bits = VT.getSizeInBits();
10767   if (ShAmt1.getOpcode() == ISD::SUB) {
10768     SDValue Sum = ShAmt1.getOperand(0);
10769     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10770       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10771       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10772         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10773       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10774         return DAG.getNode(Opc, DL, VT,
10775                            Op0, Op1,
10776                            DAG.getNode(ISD::TRUNCATE, DL,
10777                                        MVT::i8, ShAmt0));
10778     }
10779   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10780     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10781     if (ShAmt0C &&
10782         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10783       return DAG.getNode(Opc, DL, VT,
10784                          N0.getOperand(0), N1.getOperand(0),
10785                          DAG.getNode(ISD::TRUNCATE, DL,
10786                                        MVT::i8, ShAmt0));
10787   }
10788
10789   return SDValue();
10790 }
10791
10792 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10793 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10794                                    const X86Subtarget *Subtarget) {
10795   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
10796   // the FP state in cases where an emms may be missing.
10797   // A preferable solution to the general problem is to figure out the right
10798   // places to insert EMMS.  This qualifies as a quick hack.
10799
10800   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10801   StoreSDNode *St = cast<StoreSDNode>(N);
10802   EVT VT = St->getValue().getValueType();
10803   if (VT.getSizeInBits() != 64)
10804     return SDValue();
10805
10806   const Function *F = DAG.getMachineFunction().getFunction();
10807   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10808   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10809     && Subtarget->hasSSE2();
10810   if ((VT.isVector() ||
10811        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10812       isa<LoadSDNode>(St->getValue()) &&
10813       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10814       St->getChain().hasOneUse() && !St->isVolatile()) {
10815     SDNode* LdVal = St->getValue().getNode();
10816     LoadSDNode *Ld = 0;
10817     int TokenFactorIndex = -1;
10818     SmallVector<SDValue, 8> Ops;
10819     SDNode* ChainVal = St->getChain().getNode();
10820     // Must be a store of a load.  We currently handle two cases:  the load
10821     // is a direct child, and it's under an intervening TokenFactor.  It is
10822     // possible to dig deeper under nested TokenFactors.
10823     if (ChainVal == LdVal)
10824       Ld = cast<LoadSDNode>(St->getChain());
10825     else if (St->getValue().hasOneUse() &&
10826              ChainVal->getOpcode() == ISD::TokenFactor) {
10827       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10828         if (ChainVal->getOperand(i).getNode() == LdVal) {
10829           TokenFactorIndex = i;
10830           Ld = cast<LoadSDNode>(St->getValue());
10831         } else
10832           Ops.push_back(ChainVal->getOperand(i));
10833       }
10834     }
10835
10836     if (!Ld || !ISD::isNormalLoad(Ld))
10837       return SDValue();
10838
10839     // If this is not the MMX case, i.e. we are just turning i64 load/store
10840     // into f64 load/store, avoid the transformation if there are multiple
10841     // uses of the loaded value.
10842     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10843       return SDValue();
10844
10845     DebugLoc LdDL = Ld->getDebugLoc();
10846     DebugLoc StDL = N->getDebugLoc();
10847     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10848     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10849     // pair instead.
10850     if (Subtarget->is64Bit() || F64IsLegal) {
10851       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10852       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
10853                                   Ld->getPointerInfo(), Ld->isVolatile(),
10854                                   Ld->isNonTemporal(), Ld->getAlignment());
10855       SDValue NewChain = NewLd.getValue(1);
10856       if (TokenFactorIndex != -1) {
10857         Ops.push_back(NewChain);
10858         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10859                                Ops.size());
10860       }
10861       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10862                           St->getPointerInfo(),
10863                           St->isVolatile(), St->isNonTemporal(),
10864                           St->getAlignment());
10865     }
10866
10867     // Otherwise, lower to two pairs of 32-bit loads / stores.
10868     SDValue LoAddr = Ld->getBasePtr();
10869     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10870                                  DAG.getConstant(4, MVT::i32));
10871
10872     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10873                                Ld->getPointerInfo(),
10874                                Ld->isVolatile(), Ld->isNonTemporal(),
10875                                Ld->getAlignment());
10876     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10877                                Ld->getPointerInfo().getWithOffset(4),
10878                                Ld->isVolatile(), Ld->isNonTemporal(),
10879                                MinAlign(Ld->getAlignment(), 4));
10880
10881     SDValue NewChain = LoLd.getValue(1);
10882     if (TokenFactorIndex != -1) {
10883       Ops.push_back(LoLd);
10884       Ops.push_back(HiLd);
10885       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10886                              Ops.size());
10887     }
10888
10889     LoAddr = St->getBasePtr();
10890     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10891                          DAG.getConstant(4, MVT::i32));
10892
10893     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10894                                 St->getPointerInfo(),
10895                                 St->isVolatile(), St->isNonTemporal(),
10896                                 St->getAlignment());
10897     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10898                                 St->getPointerInfo().getWithOffset(4),
10899                                 St->isVolatile(),
10900                                 St->isNonTemporal(),
10901                                 MinAlign(St->getAlignment(), 4));
10902     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10903   }
10904   return SDValue();
10905 }
10906
10907 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10908 /// X86ISD::FXOR nodes.
10909 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10910   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10911   // F[X]OR(0.0, x) -> x
10912   // F[X]OR(x, 0.0) -> x
10913   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10914     if (C->getValueAPF().isPosZero())
10915       return N->getOperand(1);
10916   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10917     if (C->getValueAPF().isPosZero())
10918       return N->getOperand(0);
10919   return SDValue();
10920 }
10921
10922 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10923 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10924   // FAND(0.0, x) -> 0.0
10925   // FAND(x, 0.0) -> 0.0
10926   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10927     if (C->getValueAPF().isPosZero())
10928       return N->getOperand(0);
10929   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10930     if (C->getValueAPF().isPosZero())
10931       return N->getOperand(1);
10932   return SDValue();
10933 }
10934
10935 static SDValue PerformBTCombine(SDNode *N,
10936                                 SelectionDAG &DAG,
10937                                 TargetLowering::DAGCombinerInfo &DCI) {
10938   // BT ignores high bits in the bit index operand.
10939   SDValue Op1 = N->getOperand(1);
10940   if (Op1.hasOneUse()) {
10941     unsigned BitWidth = Op1.getValueSizeInBits();
10942     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10943     APInt KnownZero, KnownOne;
10944     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10945                                           !DCI.isBeforeLegalizeOps());
10946     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10947     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10948         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10949       DCI.CommitTargetLoweringOpt(TLO);
10950   }
10951   return SDValue();
10952 }
10953
10954 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10955   SDValue Op = N->getOperand(0);
10956   if (Op.getOpcode() == ISD::BIT_CONVERT)
10957     Op = Op.getOperand(0);
10958   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10959   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10960       VT.getVectorElementType().getSizeInBits() ==
10961       OpVT.getVectorElementType().getSizeInBits()) {
10962     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10963   }
10964   return SDValue();
10965 }
10966
10967 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10968   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
10969   //           (and (i32 x86isd::setcc_carry), 1)
10970   // This eliminates the zext. This transformation is necessary because
10971   // ISD::SETCC is always legalized to i8.
10972   DebugLoc dl = N->getDebugLoc();
10973   SDValue N0 = N->getOperand(0);
10974   EVT VT = N->getValueType(0);
10975   if (N0.getOpcode() == ISD::AND &&
10976       N0.hasOneUse() &&
10977       N0.getOperand(0).hasOneUse()) {
10978     SDValue N00 = N0.getOperand(0);
10979     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10980       return SDValue();
10981     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10982     if (!C || C->getZExtValue() != 1)
10983       return SDValue();
10984     return DAG.getNode(ISD::AND, dl, VT,
10985                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10986                                    N00.getOperand(0), N00.getOperand(1)),
10987                        DAG.getConstant(1, VT));
10988   }
10989
10990   return SDValue();
10991 }
10992
10993 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10994                                              DAGCombinerInfo &DCI) const {
10995   SelectionDAG &DAG = DCI.DAG;
10996   switch (N->getOpcode()) {
10997   default: break;
10998   case ISD::EXTRACT_VECTOR_ELT:
10999                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11000   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11001   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11002   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11003   case ISD::SHL:
11004   case ISD::SRA:
11005   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11006   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11007   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11008   case X86ISD::FXOR:
11009   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11010   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11011   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11012   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11013   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11014   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11015   case X86ISD::SHUFPD:
11016   case X86ISD::PALIGN:
11017   case X86ISD::PUNPCKHBW:
11018   case X86ISD::PUNPCKHWD:
11019   case X86ISD::PUNPCKHDQ:
11020   case X86ISD::PUNPCKHQDQ:
11021   case X86ISD::UNPCKHPS:
11022   case X86ISD::UNPCKHPD:
11023   case X86ISD::PUNPCKLBW:
11024   case X86ISD::PUNPCKLWD:
11025   case X86ISD::PUNPCKLDQ:
11026   case X86ISD::PUNPCKLQDQ:
11027   case X86ISD::UNPCKLPS:
11028   case X86ISD::UNPCKLPD:
11029   case X86ISD::MOVHLPS:
11030   case X86ISD::MOVLHPS:
11031   case X86ISD::PSHUFD:
11032   case X86ISD::PSHUFHW:
11033   case X86ISD::PSHUFLW:
11034   case X86ISD::MOVSS:
11035   case X86ISD::MOVSD:
11036   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11037   }
11038
11039   return SDValue();
11040 }
11041
11042 /// isTypeDesirableForOp - Return true if the target has native support for
11043 /// the specified value type and it is 'desirable' to use the type for the
11044 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11045 /// instruction encodings are longer and some i16 instructions are slow.
11046 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11047   if (!isTypeLegal(VT))
11048     return false;
11049   if (VT != MVT::i16)
11050     return true;
11051
11052   switch (Opc) {
11053   default:
11054     return true;
11055   case ISD::LOAD:
11056   case ISD::SIGN_EXTEND:
11057   case ISD::ZERO_EXTEND:
11058   case ISD::ANY_EXTEND:
11059   case ISD::SHL:
11060   case ISD::SRL:
11061   case ISD::SUB:
11062   case ISD::ADD:
11063   case ISD::MUL:
11064   case ISD::AND:
11065   case ISD::OR:
11066   case ISD::XOR:
11067     return false;
11068   }
11069 }
11070
11071 /// IsDesirableToPromoteOp - This method query the target whether it is
11072 /// beneficial for dag combiner to promote the specified node. If true, it
11073 /// should return the desired promotion type by reference.
11074 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11075   EVT VT = Op.getValueType();
11076   if (VT != MVT::i16)
11077     return false;
11078
11079   bool Promote = false;
11080   bool Commute = false;
11081   switch (Op.getOpcode()) {
11082   default: break;
11083   case ISD::LOAD: {
11084     LoadSDNode *LD = cast<LoadSDNode>(Op);
11085     // If the non-extending load has a single use and it's not live out, then it
11086     // might be folded.
11087     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11088                                                      Op.hasOneUse()*/) {
11089       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11090              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11091         // The only case where we'd want to promote LOAD (rather then it being
11092         // promoted as an operand is when it's only use is liveout.
11093         if (UI->getOpcode() != ISD::CopyToReg)
11094           return false;
11095       }
11096     }
11097     Promote = true;
11098     break;
11099   }
11100   case ISD::SIGN_EXTEND:
11101   case ISD::ZERO_EXTEND:
11102   case ISD::ANY_EXTEND:
11103     Promote = true;
11104     break;
11105   case ISD::SHL:
11106   case ISD::SRL: {
11107     SDValue N0 = Op.getOperand(0);
11108     // Look out for (store (shl (load), x)).
11109     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11110       return false;
11111     Promote = true;
11112     break;
11113   }
11114   case ISD::ADD:
11115   case ISD::MUL:
11116   case ISD::AND:
11117   case ISD::OR:
11118   case ISD::XOR:
11119     Commute = true;
11120     // fallthrough
11121   case ISD::SUB: {
11122     SDValue N0 = Op.getOperand(0);
11123     SDValue N1 = Op.getOperand(1);
11124     if (!Commute && MayFoldLoad(N1))
11125       return false;
11126     // Avoid disabling potential load folding opportunities.
11127     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11128       return false;
11129     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11130       return false;
11131     Promote = true;
11132   }
11133   }
11134
11135   PVT = MVT::i32;
11136   return Promote;
11137 }
11138
11139 //===----------------------------------------------------------------------===//
11140 //                           X86 Inline Assembly Support
11141 //===----------------------------------------------------------------------===//
11142
11143 static bool LowerToBSwap(CallInst *CI) {
11144   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11145   // we will turn this bswap into something that will be lowered to logical ops
11146   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11147   // so don't worry about this.
11148
11149   // Verify this is a simple bswap.
11150   if (CI->getNumArgOperands() != 1 ||
11151       CI->getType() != CI->getArgOperand(0)->getType() ||
11152       !CI->getType()->isIntegerTy())
11153     return false;
11154
11155   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11156   if (!Ty || Ty->getBitWidth() % 16 != 0)
11157     return false;
11158
11159   // Okay, we can do this xform, do so now.
11160   const Type *Tys[] = { Ty };
11161   Module *M = CI->getParent()->getParent()->getParent();
11162   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11163
11164   Value *Op = CI->getArgOperand(0);
11165   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11166
11167   CI->replaceAllUsesWith(Op);
11168   CI->eraseFromParent();
11169   return true;
11170 }
11171
11172 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11173   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11174   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11175
11176   std::string AsmStr = IA->getAsmString();
11177
11178   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11179   SmallVector<StringRef, 4> AsmPieces;
11180   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
11181
11182   switch (AsmPieces.size()) {
11183   default: return false;
11184   case 1:
11185     AsmStr = AsmPieces[0];
11186     AsmPieces.clear();
11187     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11188
11189     // bswap $0
11190     if (AsmPieces.size() == 2 &&
11191         (AsmPieces[0] == "bswap" ||
11192          AsmPieces[0] == "bswapq" ||
11193          AsmPieces[0] == "bswapl") &&
11194         (AsmPieces[1] == "$0" ||
11195          AsmPieces[1] == "${0:q}")) {
11196       // No need to check constraints, nothing other than the equivalent of
11197       // "=r,0" would be valid here.
11198       return LowerToBSwap(CI);
11199     }
11200     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11201     if (CI->getType()->isIntegerTy(16) &&
11202         AsmPieces.size() == 3 &&
11203         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11204         AsmPieces[1] == "$$8," &&
11205         AsmPieces[2] == "${0:w}" &&
11206         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11207       AsmPieces.clear();
11208       const std::string &Constraints = IA->getConstraintString();
11209       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11210       std::sort(AsmPieces.begin(), AsmPieces.end());
11211       if (AsmPieces.size() == 4 &&
11212           AsmPieces[0] == "~{cc}" &&
11213           AsmPieces[1] == "~{dirflag}" &&
11214           AsmPieces[2] == "~{flags}" &&
11215           AsmPieces[3] == "~{fpsr}") {
11216         return LowerToBSwap(CI);
11217       }
11218     }
11219     break;
11220   case 3:
11221     if (CI->getType()->isIntegerTy(64) &&
11222         Constraints.size() >= 2 &&
11223         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11224         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11225       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11226       SmallVector<StringRef, 4> Words;
11227       SplitString(AsmPieces[0], Words, " \t");
11228       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11229         Words.clear();
11230         SplitString(AsmPieces[1], Words, " \t");
11231         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11232           Words.clear();
11233           SplitString(AsmPieces[2], Words, " \t,");
11234           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11235               Words[2] == "%edx") {
11236             return LowerToBSwap(CI);
11237           }
11238         }
11239       }
11240     }
11241     break;
11242   }
11243   return false;
11244 }
11245
11246
11247
11248 /// getConstraintType - Given a constraint letter, return the type of
11249 /// constraint it is for this target.
11250 X86TargetLowering::ConstraintType
11251 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11252   if (Constraint.size() == 1) {
11253     switch (Constraint[0]) {
11254     case 'A':
11255       return C_Register;
11256     case 'f':
11257     case 'r':
11258     case 'R':
11259     case 'l':
11260     case 'q':
11261     case 'Q':
11262     case 'x':
11263     case 'y':
11264     case 'Y':
11265       return C_RegisterClass;
11266     case 'e':
11267     case 'Z':
11268       return C_Other;
11269     default:
11270       break;
11271     }
11272   }
11273   return TargetLowering::getConstraintType(Constraint);
11274 }
11275
11276 /// Examine constraint type and operand type and determine a weight value,
11277 /// where: -1 = invalid match, and 0 = so-so match to 3 = good match.
11278 /// This object must already have been set up with the operand type
11279 /// and the current alternative constraint selected.
11280 int X86TargetLowering::getSingleConstraintMatchWeight(
11281     AsmOperandInfo &info, const char *constraint) const {
11282   int weight = -1;
11283   Value *CallOperandVal = info.CallOperandVal;
11284     // If we don't have a value, we can't do a match,
11285     // but allow it at the lowest weight.
11286   if (CallOperandVal == NULL)
11287     return 0;
11288   // Look at the constraint type.
11289   switch (*constraint) {
11290   default:
11291     return TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11292     break;
11293   case 'I':
11294     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11295       if (C->getZExtValue() <= 31)
11296         weight = 3;
11297     }
11298     break;
11299   // etc.
11300   }
11301   return weight;
11302 }
11303
11304 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11305 /// with another that has more specific requirements based on the type of the
11306 /// corresponding operand.
11307 const char *X86TargetLowering::
11308 LowerXConstraint(EVT ConstraintVT) const {
11309   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11310   // 'f' like normal targets.
11311   if (ConstraintVT.isFloatingPoint()) {
11312     if (Subtarget->hasSSE2())
11313       return "Y";
11314     if (Subtarget->hasSSE1())
11315       return "x";
11316   }
11317
11318   return TargetLowering::LowerXConstraint(ConstraintVT);
11319 }
11320
11321 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11322 /// vector.  If it is invalid, don't add anything to Ops.
11323 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11324                                                      char Constraint,
11325                                                      std::vector<SDValue>&Ops,
11326                                                      SelectionDAG &DAG) const {
11327   SDValue Result(0, 0);
11328
11329   switch (Constraint) {
11330   default: break;
11331   case 'I':
11332     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11333       if (C->getZExtValue() <= 31) {
11334         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11335         break;
11336       }
11337     }
11338     return;
11339   case 'J':
11340     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11341       if (C->getZExtValue() <= 63) {
11342         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11343         break;
11344       }
11345     }
11346     return;
11347   case 'K':
11348     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11349       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11350         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11351         break;
11352       }
11353     }
11354     return;
11355   case 'N':
11356     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11357       if (C->getZExtValue() <= 255) {
11358         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11359         break;
11360       }
11361     }
11362     return;
11363   case 'e': {
11364     // 32-bit signed value
11365     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11366       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11367                                            C->getSExtValue())) {
11368         // Widen to 64 bits here to get it sign extended.
11369         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11370         break;
11371       }
11372     // FIXME gcc accepts some relocatable values here too, but only in certain
11373     // memory models; it's complicated.
11374     }
11375     return;
11376   }
11377   case 'Z': {
11378     // 32-bit unsigned value
11379     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11380       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11381                                            C->getZExtValue())) {
11382         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11383         break;
11384       }
11385     }
11386     // FIXME gcc accepts some relocatable values here too, but only in certain
11387     // memory models; it's complicated.
11388     return;
11389   }
11390   case 'i': {
11391     // Literal immediates are always ok.
11392     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11393       // Widen to 64 bits here to get it sign extended.
11394       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11395       break;
11396     }
11397
11398     // In any sort of PIC mode addresses need to be computed at runtime by
11399     // adding in a register or some sort of table lookup.  These can't
11400     // be used as immediates.
11401     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11402       return;
11403
11404     // If we are in non-pic codegen mode, we allow the address of a global (with
11405     // an optional displacement) to be used with 'i'.
11406     GlobalAddressSDNode *GA = 0;
11407     int64_t Offset = 0;
11408
11409     // Match either (GA), (GA+C), (GA+C1+C2), etc.
11410     while (1) {
11411       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11412         Offset += GA->getOffset();
11413         break;
11414       } else if (Op.getOpcode() == ISD::ADD) {
11415         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11416           Offset += C->getZExtValue();
11417           Op = Op.getOperand(0);
11418           continue;
11419         }
11420       } else if (Op.getOpcode() == ISD::SUB) {
11421         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11422           Offset += -C->getZExtValue();
11423           Op = Op.getOperand(0);
11424           continue;
11425         }
11426       }
11427
11428       // Otherwise, this isn't something we can handle, reject it.
11429       return;
11430     }
11431
11432     const GlobalValue *GV = GA->getGlobal();
11433     // If we require an extra load to get this address, as in PIC mode, we
11434     // can't accept it.
11435     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11436                                                         getTargetMachine())))
11437       return;
11438
11439     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11440                                         GA->getValueType(0), Offset);
11441     break;
11442   }
11443   }
11444
11445   if (Result.getNode()) {
11446     Ops.push_back(Result);
11447     return;
11448   }
11449   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11450 }
11451
11452 std::vector<unsigned> X86TargetLowering::
11453 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11454                                   EVT VT) const {
11455   if (Constraint.size() == 1) {
11456     // FIXME: not handling fp-stack yet!
11457     switch (Constraint[0]) {      // GCC X86 Constraint Letters
11458     default: break;  // Unknown constraint letter
11459     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11460       if (Subtarget->is64Bit()) {
11461         if (VT == MVT::i32)
11462           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11463                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11464                                        X86::R10D,X86::R11D,X86::R12D,
11465                                        X86::R13D,X86::R14D,X86::R15D,
11466                                        X86::EBP, X86::ESP, 0);
11467         else if (VT == MVT::i16)
11468           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
11469                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
11470                                        X86::R10W,X86::R11W,X86::R12W,
11471                                        X86::R13W,X86::R14W,X86::R15W,
11472                                        X86::BP,  X86::SP, 0);
11473         else if (VT == MVT::i8)
11474           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
11475                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11476                                        X86::R10B,X86::R11B,X86::R12B,
11477                                        X86::R13B,X86::R14B,X86::R15B,
11478                                        X86::BPL, X86::SPL, 0);
11479
11480         else if (VT == MVT::i64)
11481           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11482                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
11483                                        X86::R10, X86::R11, X86::R12,
11484                                        X86::R13, X86::R14, X86::R15,
11485                                        X86::RBP, X86::RSP, 0);
11486
11487         break;
11488       }
11489       // 32-bit fallthrough
11490     case 'Q':   // Q_REGS
11491       if (VT == MVT::i32)
11492         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11493       else if (VT == MVT::i16)
11494         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11495       else if (VT == MVT::i8)
11496         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11497       else if (VT == MVT::i64)
11498         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11499       break;
11500     }
11501   }
11502
11503   return std::vector<unsigned>();
11504 }
11505
11506 std::pair<unsigned, const TargetRegisterClass*>
11507 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11508                                                 EVT VT) const {
11509   // First, see if this is a constraint that directly corresponds to an LLVM
11510   // register class.
11511   if (Constraint.size() == 1) {
11512     // GCC Constraint Letters
11513     switch (Constraint[0]) {
11514     default: break;
11515     case 'r':   // GENERAL_REGS
11516     case 'l':   // INDEX_REGS
11517       if (VT == MVT::i8)
11518         return std::make_pair(0U, X86::GR8RegisterClass);
11519       if (VT == MVT::i16)
11520         return std::make_pair(0U, X86::GR16RegisterClass);
11521       if (VT == MVT::i32 || !Subtarget->is64Bit())
11522         return std::make_pair(0U, X86::GR32RegisterClass);
11523       return std::make_pair(0U, X86::GR64RegisterClass);
11524     case 'R':   // LEGACY_REGS
11525       if (VT == MVT::i8)
11526         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11527       if (VT == MVT::i16)
11528         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11529       if (VT == MVT::i32 || !Subtarget->is64Bit())
11530         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11531       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11532     case 'f':  // FP Stack registers.
11533       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11534       // value to the correct fpstack register class.
11535       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11536         return std::make_pair(0U, X86::RFP32RegisterClass);
11537       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11538         return std::make_pair(0U, X86::RFP64RegisterClass);
11539       return std::make_pair(0U, X86::RFP80RegisterClass);
11540     case 'y':   // MMX_REGS if MMX allowed.
11541       if (!Subtarget->hasMMX()) break;
11542       return std::make_pair(0U, X86::VR64RegisterClass);
11543     case 'Y':   // SSE_REGS if SSE2 allowed
11544       if (!Subtarget->hasSSE2()) break;
11545       // FALL THROUGH.
11546     case 'x':   // SSE_REGS if SSE1 allowed
11547       if (!Subtarget->hasSSE1()) break;
11548
11549       switch (VT.getSimpleVT().SimpleTy) {
11550       default: break;
11551       // Scalar SSE types.
11552       case MVT::f32:
11553       case MVT::i32:
11554         return std::make_pair(0U, X86::FR32RegisterClass);
11555       case MVT::f64:
11556       case MVT::i64:
11557         return std::make_pair(0U, X86::FR64RegisterClass);
11558       // Vector types.
11559       case MVT::v16i8:
11560       case MVT::v8i16:
11561       case MVT::v4i32:
11562       case MVT::v2i64:
11563       case MVT::v4f32:
11564       case MVT::v2f64:
11565         return std::make_pair(0U, X86::VR128RegisterClass);
11566       }
11567       break;
11568     }
11569   }
11570
11571   // Use the default implementation in TargetLowering to convert the register
11572   // constraint into a member of a register class.
11573   std::pair<unsigned, const TargetRegisterClass*> Res;
11574   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11575
11576   // Not found as a standard register?
11577   if (Res.second == 0) {
11578     // Map st(0) -> st(7) -> ST0
11579     if (Constraint.size() == 7 && Constraint[0] == '{' &&
11580         tolower(Constraint[1]) == 's' &&
11581         tolower(Constraint[2]) == 't' &&
11582         Constraint[3] == '(' &&
11583         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11584         Constraint[5] == ')' &&
11585         Constraint[6] == '}') {
11586
11587       Res.first = X86::ST0+Constraint[4]-'0';
11588       Res.second = X86::RFP80RegisterClass;
11589       return Res;
11590     }
11591
11592     // GCC allows "st(0)" to be called just plain "st".
11593     if (StringRef("{st}").equals_lower(Constraint)) {
11594       Res.first = X86::ST0;
11595       Res.second = X86::RFP80RegisterClass;
11596       return Res;
11597     }
11598
11599     // flags -> EFLAGS
11600     if (StringRef("{flags}").equals_lower(Constraint)) {
11601       Res.first = X86::EFLAGS;
11602       Res.second = X86::CCRRegisterClass;
11603       return Res;
11604     }
11605
11606     // 'A' means EAX + EDX.
11607     if (Constraint == "A") {
11608       Res.first = X86::EAX;
11609       Res.second = X86::GR32_ADRegisterClass;
11610       return Res;
11611     }
11612     return Res;
11613   }
11614
11615   // Otherwise, check to see if this is a register class of the wrong value
11616   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11617   // turn into {ax},{dx}.
11618   if (Res.second->hasType(VT))
11619     return Res;   // Correct type already, nothing to do.
11620
11621   // All of the single-register GCC register classes map their values onto
11622   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
11623   // really want an 8-bit or 32-bit register, map to the appropriate register
11624   // class and return the appropriate register.
11625   if (Res.second == X86::GR16RegisterClass) {
11626     if (VT == MVT::i8) {
11627       unsigned DestReg = 0;
11628       switch (Res.first) {
11629       default: break;
11630       case X86::AX: DestReg = X86::AL; break;
11631       case X86::DX: DestReg = X86::DL; break;
11632       case X86::CX: DestReg = X86::CL; break;
11633       case X86::BX: DestReg = X86::BL; break;
11634       }
11635       if (DestReg) {
11636         Res.first = DestReg;
11637         Res.second = X86::GR8RegisterClass;
11638       }
11639     } else if (VT == MVT::i32) {
11640       unsigned DestReg = 0;
11641       switch (Res.first) {
11642       default: break;
11643       case X86::AX: DestReg = X86::EAX; break;
11644       case X86::DX: DestReg = X86::EDX; break;
11645       case X86::CX: DestReg = X86::ECX; break;
11646       case X86::BX: DestReg = X86::EBX; break;
11647       case X86::SI: DestReg = X86::ESI; break;
11648       case X86::DI: DestReg = X86::EDI; break;
11649       case X86::BP: DestReg = X86::EBP; break;
11650       case X86::SP: DestReg = X86::ESP; break;
11651       }
11652       if (DestReg) {
11653         Res.first = DestReg;
11654         Res.second = X86::GR32RegisterClass;
11655       }
11656     } else if (VT == MVT::i64) {
11657       unsigned DestReg = 0;
11658       switch (Res.first) {
11659       default: break;
11660       case X86::AX: DestReg = X86::RAX; break;
11661       case X86::DX: DestReg = X86::RDX; break;
11662       case X86::CX: DestReg = X86::RCX; break;
11663       case X86::BX: DestReg = X86::RBX; break;
11664       case X86::SI: DestReg = X86::RSI; break;
11665       case X86::DI: DestReg = X86::RDI; break;
11666       case X86::BP: DestReg = X86::RBP; break;
11667       case X86::SP: DestReg = X86::RSP; break;
11668       }
11669       if (DestReg) {
11670         Res.first = DestReg;
11671         Res.second = X86::GR64RegisterClass;
11672       }
11673     }
11674   } else if (Res.second == X86::FR32RegisterClass ||
11675              Res.second == X86::FR64RegisterClass ||
11676              Res.second == X86::VR128RegisterClass) {
11677     // Handle references to XMM physical registers that got mapped into the
11678     // wrong class.  This can happen with constraints like {xmm0} where the
11679     // target independent register mapper will just pick the first match it can
11680     // find, ignoring the required type.
11681     if (VT == MVT::f32)
11682       Res.second = X86::FR32RegisterClass;
11683     else if (VT == MVT::f64)
11684       Res.second = X86::FR64RegisterClass;
11685     else if (X86::VR128RegisterClass->hasType(VT))
11686       Res.second = X86::VR128RegisterClass;
11687   }
11688
11689   return Res;
11690 }