5092d754028d38e1f1344a6f71de645a41c39b1d
[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 "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace llvm;
53 using namespace dwarf;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 static cl::opt<bool>
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65   
66   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
67   
68   if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
69     if (is64Bit) return new X8664_MachoTargetObjectFile();
70     return new TargetLoweringObjectFileMachO();
71   } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
72     if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
73     return new X8632_ELFTargetObjectFile(TM);
74   } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
75     return new TargetLoweringObjectFileCOFF();
76   }  
77   llvm_unreachable("unknown subtarget type");
78 }
79
80 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
81   : TargetLowering(TM, createTLOF(TM)) {
82   Subtarget = &TM.getSubtarget<X86Subtarget>();
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
86
87   RegInfo = TM.getRegisterInfo();
88   TD = getTargetData();
89
90   // Set up the TargetLowering object.
91
92   // X86 is weird, it always uses i8 for shift amounts and setcc results.
93   setShiftAmountType(MVT::i8);
94   setBooleanContents(ZeroOrOneBooleanContent);
95   setSchedulingPreference(Sched::RegPressure);
96   setStackPointerRegisterToSaveRestore(X86StackPtr);
97
98   if (Subtarget->isTargetDarwin()) {
99     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
100     setUseUnderscoreSetJmp(false);
101     setUseUnderscoreLongJmp(false);
102   } else if (Subtarget->isTargetMingw()) {
103     // MS runtime is weird: it exports _setjmp, but longjmp!
104     setUseUnderscoreSetJmp(true);
105     setUseUnderscoreLongJmp(false);
106   } else {
107     setUseUnderscoreSetJmp(true);
108     setUseUnderscoreLongJmp(true);
109   }
110
111   // Set up the register classes.
112   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
113   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
114   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
115   if (Subtarget->is64Bit())
116     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
117
118   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
119
120   // We don't accept any truncstore of integer registers.
121   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
122   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
123   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
124   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
125   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
126   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
127
128   // SETOEQ and SETUNE require checking two conditions.
129   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
130   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
131   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
132   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
133   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
134   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
135
136   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
137   // operation.
138   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
139   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
140   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
141
142   if (Subtarget->is64Bit()) {
143     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
144     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
145   } else if (!UseSoftFloat) {
146     // We have an algorithm for SSE2->double, and we turn this into a
147     // 64-bit FILD followed by conditional FADD for other targets.
148     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
149     // We have an algorithm for SSE2, and we turn this into a 64-bit
150     // FILD for other targets.
151     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
152   }
153
154   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
155   // this operation.
156   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
157   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
158
159   if (!UseSoftFloat) {
160     // SSE has no i16 to fp conversion, only i32
161     if (X86ScalarSSEf32) {
162       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
163       // f32 and f64 cases are Legal, f80 case is not
164       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
165     } else {
166       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
167       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
168     }
169   } else {
170     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
171     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
172   }
173
174   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
175   // are Legal, f80 is custom lowered.
176   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
177   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
178
179   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
180   // this operation.
181   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
182   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
183
184   if (X86ScalarSSEf32) {
185     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
186     // f32 and f64 cases are Legal, f80 case is not
187     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
188   } else {
189     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
190     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
191   }
192
193   // Handle FP_TO_UINT by promoting the destination to a larger signed
194   // conversion.
195   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
196   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
197   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
198
199   if (Subtarget->is64Bit()) {
200     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
201     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
202   } else if (!UseSoftFloat) {
203     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
204       // Expand FP_TO_UINT into a select.
205       // FIXME: We would like to use a Custom expander here eventually to do
206       // the optimal thing for SSE vs. the default expansion in the legalizer.
207       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
208     else
209       // With SSE3 we can use fisttpll to convert to a signed i64; without
210       // SSE, we're stuck with a fistpll.
211       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
212   }
213
214   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
215   if (!X86ScalarSSEf64) { 
216     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
217     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
218     if (Subtarget->is64Bit()) {
219       setOperationAction(ISD::BIT_CONVERT    , MVT::f64  , Expand);
220       // Without SSE, i64->f64 goes through memory; i64->MMX is Legal.
221       if (Subtarget->hasMMX() && !DisableMMX)
222         setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Custom);
223       else 
224         setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Expand);
225     }
226   }
227
228   // Scalar integer divide and remainder are lowered to use operations that
229   // produce two results, to match the available instructions. This exposes
230   // the two-result form to trivial CSE, which is able to combine x/y and x%y
231   // into a single instruction.
232   //
233   // Scalar integer multiply-high is also lowered to use two-result
234   // operations, to match the available instructions. However, plain multiply
235   // (low) operations are left as Legal, as there are single-result
236   // instructions for this in x86. Using the two-result multiply instructions
237   // when both high and low results are needed must be arranged by dagcombine.
238   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
239   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
240   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
241   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
242   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
243   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
244   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
245   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
246   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
247   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
248   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
249   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
250   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
251   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
252   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
253   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
254   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
255   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
256   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
257   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
258   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
259   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
260   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
261   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
262
263   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
264   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
265   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
266   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
267   if (Subtarget->is64Bit())
268     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
269   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
270   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
271   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
272   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
273   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
274   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
275   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
276   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
277
278   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
279   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
280   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
281   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
282   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
283   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
284   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
285   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
286   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
287   if (Subtarget->is64Bit()) {
288     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
289     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
290     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
291   }
292
293   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
294   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
295
296   // These should be promoted to a larger select which is supported.
297   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
298   // X86 wants to expand cmov itself.
299   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
300   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
301   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
302   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
303   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
304   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
305   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
306   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
307   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
308   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
309   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
310   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
313     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
314   }
315   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
316
317   // Darwin ABI issue.
318   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
319   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
320   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
321   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
322   if (Subtarget->is64Bit())
323     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
324   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
325   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
326   if (Subtarget->is64Bit()) {
327     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
328     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
329     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
330     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
331     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
332   }
333   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
334   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
335   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
336   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
337   if (Subtarget->is64Bit()) {
338     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
339     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
340     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
341   }
342
343   if (Subtarget->hasSSE1())
344     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
345
346   if (!Subtarget->hasSSE2())
347     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
348   // On X86 and X86-64, atomic operations are lowered to locked instructions.
349   // Locked instructions, in turn, have implicit fence semantics (all memory
350   // operations are flushed before issuing the locked instruction, and they
351   // are not buffered), so we can fold away the common pattern of
352   // fence-atomic-fence.
353   setShouldFoldAtomicFences(true);
354
355   // Expand certain atomics
356   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
358   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
359   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
360
361   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
362   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
363   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
364   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
365
366   if (!Subtarget->is64Bit()) {
367     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
368     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
369     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
370     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
371     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
372     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
373     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
374   }
375
376   // FIXME - use subtarget debug flags
377   if (!Subtarget->isTargetDarwin() &&
378       !Subtarget->isTargetELF() &&
379       !Subtarget->isTargetCygMing()) {
380     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
381   }
382
383   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
384   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
385   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
386   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
387   if (Subtarget->is64Bit()) {
388     setExceptionPointerRegister(X86::RAX);
389     setExceptionSelectorRegister(X86::RDX);
390   } else {
391     setExceptionPointerRegister(X86::EAX);
392     setExceptionSelectorRegister(X86::EDX);
393   }
394   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
395   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
396
397   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
398
399   setOperationAction(ISD::TRAP, MVT::Other, Legal);
400
401   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
402   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
403   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
404   if (Subtarget->is64Bit()) {
405     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
406     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
407   } else {
408     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
409     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
410   }
411
412   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
413   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
414   if (Subtarget->is64Bit())
415     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
416   if (Subtarget->isTargetCygMing())
417     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
418   else
419     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
420
421   if (!UseSoftFloat && X86ScalarSSEf64) {
422     // f32 and f64 use SSE.
423     // Set up the FP register classes.
424     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
425     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
426
427     // Use ANDPD to simulate FABS.
428     setOperationAction(ISD::FABS , MVT::f64, Custom);
429     setOperationAction(ISD::FABS , MVT::f32, Custom);
430
431     // Use XORP to simulate FNEG.
432     setOperationAction(ISD::FNEG , MVT::f64, Custom);
433     setOperationAction(ISD::FNEG , MVT::f32, Custom);
434
435     // Use ANDPD and ORPD to simulate FCOPYSIGN.
436     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
437     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
438
439     // We don't support sin/cos/fmod
440     setOperationAction(ISD::FSIN , MVT::f64, Expand);
441     setOperationAction(ISD::FCOS , MVT::f64, Expand);
442     setOperationAction(ISD::FSIN , MVT::f32, Expand);
443     setOperationAction(ISD::FCOS , MVT::f32, Expand);
444
445     // Expand FP immediates into loads from the stack, except for the special
446     // cases we handle.
447     addLegalFPImmediate(APFloat(+0.0)); // xorpd
448     addLegalFPImmediate(APFloat(+0.0f)); // xorps
449   } else if (!UseSoftFloat && X86ScalarSSEf32) {
450     // Use SSE for f32, x87 for f64.
451     // Set up the FP register classes.
452     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
453     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
454
455     // Use ANDPS to simulate FABS.
456     setOperationAction(ISD::FABS , MVT::f32, Custom);
457
458     // Use XORP to simulate FNEG.
459     setOperationAction(ISD::FNEG , MVT::f32, Custom);
460
461     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
462
463     // Use ANDPS and ORPS to simulate FCOPYSIGN.
464     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
466
467     // We don't support sin/cos/fmod
468     setOperationAction(ISD::FSIN , MVT::f32, Expand);
469     setOperationAction(ISD::FCOS , MVT::f32, Expand);
470
471     // Special cases we handle for FP constants.
472     addLegalFPImmediate(APFloat(+0.0f)); // xorps
473     addLegalFPImmediate(APFloat(+0.0)); // FLD0
474     addLegalFPImmediate(APFloat(+1.0)); // FLD1
475     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
476     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
477
478     if (!UnsafeFPMath) {
479       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
480       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
481     }
482   } else if (!UseSoftFloat) {
483     // f32 and f64 in x87.
484     // Set up the FP register classes.
485     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
486     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
487
488     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
489     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
490     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
491     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
492
493     if (!UnsafeFPMath) {
494       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
495       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
496     }
497     addLegalFPImmediate(APFloat(+0.0)); // FLD0
498     addLegalFPImmediate(APFloat(+1.0)); // FLD1
499     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
500     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
501     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
502     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
503     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
504     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
505   }
506
507   // Long double always uses X87.
508   if (!UseSoftFloat) {
509     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
510     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
511     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
512     {
513       bool ignored;
514       APFloat TmpFlt(+0.0);
515       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
516                      &ignored);
517       addLegalFPImmediate(TmpFlt);  // FLD0
518       TmpFlt.changeSign();
519       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
520       APFloat TmpFlt2(+1.0);
521       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
522                       &ignored);
523       addLegalFPImmediate(TmpFlt2);  // FLD1
524       TmpFlt2.changeSign();
525       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
526     }
527
528     if (!UnsafeFPMath) {
529       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
530       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
531     }
532   }
533
534   // Always use a library call for pow.
535   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
536   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
537   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
538
539   setOperationAction(ISD::FLOG, MVT::f80, Expand);
540   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
541   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
542   setOperationAction(ISD::FEXP, MVT::f80, Expand);
543   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
544
545   // First set operation action for all vector types to either promote
546   // (for widening) or expand (for scalarization). Then we will selectively
547   // turn on ones that can be effectively codegen'd.
548   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
549        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
550     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
565     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
566     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
599     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
603     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
604          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
605       setTruncStoreAction((MVT::SimpleValueType)VT,
606                           (MVT::SimpleValueType)InnerVT, Expand);
607     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
608     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
609     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
610   }
611
612   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
613   // with -msoft-float, disable use of MMX as well.
614   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
615     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
616     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
617     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
618     
619     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
620
621     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
622     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
623     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
624     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
625
626     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
627     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
628     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
629     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
630
631     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
632     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
633
634     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
635     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
636     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
637     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
638     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
639     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
640     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
641
642     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
643     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
644     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
645     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
646     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
647     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
648     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
649
650     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
651     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
652     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
653     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
654     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
655     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
656     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
657
658     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
659     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
660     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
661     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
662     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
663     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
664     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
665
666     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
667     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
668     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
669     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
670
671     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
672     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
673     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
674     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
675
676     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
677     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
678     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
679
680     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
681
682     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
683     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
684     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
685     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
686     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
687     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
688     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
689
690     if (!X86ScalarSSEf64 && Subtarget->is64Bit()) {
691       setOperationAction(ISD::BIT_CONVERT,        MVT::v8i8,  Custom);
692       setOperationAction(ISD::BIT_CONVERT,        MVT::v4i16, Custom);
693       setOperationAction(ISD::BIT_CONVERT,        MVT::v2i32, Custom);
694       setOperationAction(ISD::BIT_CONVERT,        MVT::v1i64, Custom);
695     }
696   }
697
698   if (!UseSoftFloat && Subtarget->hasSSE1()) {
699     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
700
701     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
702     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
703     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
704     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
705     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
706     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
707     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
708     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
709     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
710     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
711     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
712     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
713   }
714
715   if (!UseSoftFloat && Subtarget->hasSSE2()) {
716     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
717
718     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
719     // registers cannot be used even for integer operations.
720     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
721     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
722     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
723     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
724
725     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
726     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
727     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
728     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
729     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
730     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
731     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
732     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
733     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
734     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
735     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
736     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
737     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
738     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
739     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
740     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
741
742     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
743     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
744     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
745     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
746
747     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
748     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
749     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
750     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
751     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
752
753     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
754     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
755     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
756     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
757     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
758
759     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
760     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
761       EVT VT = (MVT::SimpleValueType)i;
762       // Do not attempt to custom lower non-power-of-2 vectors
763       if (!isPowerOf2_32(VT.getVectorNumElements()))
764         continue;
765       // Do not attempt to custom lower non-128-bit vectors
766       if (!VT.is128BitVector())
767         continue;
768       setOperationAction(ISD::BUILD_VECTOR,
769                          VT.getSimpleVT().SimpleTy, Custom);
770       setOperationAction(ISD::VECTOR_SHUFFLE,
771                          VT.getSimpleVT().SimpleTy, Custom);
772       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
773                          VT.getSimpleVT().SimpleTy, Custom);
774     }
775
776     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
777     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
778     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
779     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
780     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
781     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
782
783     if (Subtarget->is64Bit()) {
784       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
785       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
786     }
787
788     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
789     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
790       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
791       EVT VT = SVT;
792
793       // Do not attempt to promote non-128-bit vectors
794       if (!VT.is128BitVector())
795         continue;
796       
797       setOperationAction(ISD::AND,    SVT, Promote);
798       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
799       setOperationAction(ISD::OR,     SVT, Promote);
800       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
801       setOperationAction(ISD::XOR,    SVT, Promote);
802       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
803       setOperationAction(ISD::LOAD,   SVT, Promote);
804       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
805       setOperationAction(ISD::SELECT, SVT, Promote);
806       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
807     }
808
809     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
810
811     // Custom lower v2i64 and v2f64 selects.
812     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
813     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
814     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
815     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
816
817     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
818     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
819     if (!DisableMMX && Subtarget->hasMMX()) {
820       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
821       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
822     }
823   }
824
825   if (Subtarget->hasSSE41()) {
826     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
827     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
828     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
829     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
830     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
831     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
832     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
833     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
834     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
835     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
836
837     // FIXME: Do we need to handle scalar-to-vector here?
838     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
839
840     // i8 and i16 vectors are custom , because the source register and source
841     // source memory operand types are not the same width.  f32 vectors are
842     // custom since the immediate controlling the insert encodes additional
843     // information.
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
848
849     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
850     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
851     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
852     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
853
854     if (Subtarget->is64Bit()) {
855       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
856       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
857     }
858   }
859
860   if (Subtarget->hasSSE42()) {
861     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
862   }
863
864   if (!UseSoftFloat && Subtarget->hasAVX()) {
865     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
866     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
867     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
868     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
869
870     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
871     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
872     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
873     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
874     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
875     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
876     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
877     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
878     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
879     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
880     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
881     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
882     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
883     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
884     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
885
886     // Operations to consider commented out -v16i16 v32i8
887     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
888     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
889     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
890     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
891     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
892     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
893     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
894     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
895     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
896     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
897     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
898     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
899     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
900     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
901
902     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
903     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
904     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
905     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
906
907     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
908     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
909     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
910     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
911     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
912
913     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
914     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
915     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
916     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
917     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
918     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
919
920 #if 0
921     // Not sure we want to do this since there are no 256-bit integer
922     // operations in AVX
923
924     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
925     // This includes 256-bit vectors
926     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
927       EVT VT = (MVT::SimpleValueType)i;
928
929       // Do not attempt to custom lower non-power-of-2 vectors
930       if (!isPowerOf2_32(VT.getVectorNumElements()))
931         continue;
932
933       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
934       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
935       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
936     }
937
938     if (Subtarget->is64Bit()) {
939       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
940       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
941     }
942 #endif
943
944 #if 0
945     // Not sure we want to do this since there are no 256-bit integer
946     // operations in AVX
947
948     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
949     // Including 256-bit vectors
950     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
951       EVT VT = (MVT::SimpleValueType)i;
952
953       if (!VT.is256BitVector()) {
954         continue;
955       }
956       setOperationAction(ISD::AND,    VT, Promote);
957       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
958       setOperationAction(ISD::OR,     VT, Promote);
959       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
960       setOperationAction(ISD::XOR,    VT, Promote);
961       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
962       setOperationAction(ISD::LOAD,   VT, Promote);
963       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
964       setOperationAction(ISD::SELECT, VT, Promote);
965       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
966     }
967
968     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
969 #endif
970   }
971
972   // We want to custom lower some of our intrinsics.
973   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
974
975   // Add/Sub/Mul with overflow operations are custom lowered.
976   setOperationAction(ISD::SADDO, MVT::i32, Custom);
977   setOperationAction(ISD::UADDO, MVT::i32, Custom);
978   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
979   setOperationAction(ISD::USUBO, MVT::i32, Custom);
980   setOperationAction(ISD::SMULO, MVT::i32, Custom);
981
982   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
983   // handle type legalization for these operations here.
984   //
985   // FIXME: We really should do custom legalization for addition and
986   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
987   // than generic legalization for 64-bit multiplication-with-overflow, though.
988   if (Subtarget->is64Bit()) {
989     setOperationAction(ISD::SADDO, MVT::i64, Custom);
990     setOperationAction(ISD::UADDO, MVT::i64, Custom);
991     setOperationAction(ISD::SSUBO, MVT::i64, Custom);
992     setOperationAction(ISD::USUBO, MVT::i64, Custom);
993     setOperationAction(ISD::SMULO, MVT::i64, Custom);
994   }
995
996   if (!Subtarget->is64Bit()) {
997     // These libcalls are not available in 32-bit.
998     setLibcallName(RTLIB::SHL_I128, 0);
999     setLibcallName(RTLIB::SRL_I128, 0);
1000     setLibcallName(RTLIB::SRA_I128, 0);
1001   }
1002
1003   // We have target-specific dag combine patterns for the following nodes:
1004   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1005   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1006   setTargetDAGCombine(ISD::BUILD_VECTOR);
1007   setTargetDAGCombine(ISD::SELECT);
1008   setTargetDAGCombine(ISD::SHL);
1009   setTargetDAGCombine(ISD::SRA);
1010   setTargetDAGCombine(ISD::SRL);
1011   setTargetDAGCombine(ISD::OR);
1012   setTargetDAGCombine(ISD::STORE);
1013   setTargetDAGCombine(ISD::ZERO_EXTEND);
1014   if (Subtarget->is64Bit())
1015     setTargetDAGCombine(ISD::MUL);
1016
1017   computeRegisterProperties();
1018
1019   // FIXME: These should be based on subtarget info. Plus, the values should
1020   // be smaller when we are in optimizing for size mode.
1021   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1022   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1023   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1024   setPrefLoopAlignment(16);
1025   benefitFromCodePlacementOpt = true;
1026 }
1027
1028
1029 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1030   return MVT::i8;
1031 }
1032
1033
1034 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1035 /// the desired ByVal argument alignment.
1036 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1037   if (MaxAlign == 16)
1038     return;
1039   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1040     if (VTy->getBitWidth() == 128)
1041       MaxAlign = 16;
1042   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1043     unsigned EltAlign = 0;
1044     getMaxByValAlign(ATy->getElementType(), EltAlign);
1045     if (EltAlign > MaxAlign)
1046       MaxAlign = EltAlign;
1047   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1048     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1049       unsigned EltAlign = 0;
1050       getMaxByValAlign(STy->getElementType(i), EltAlign);
1051       if (EltAlign > MaxAlign)
1052         MaxAlign = EltAlign;
1053       if (MaxAlign == 16)
1054         break;
1055     }
1056   }
1057   return;
1058 }
1059
1060 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1061 /// function arguments in the caller parameter area. For X86, aggregates
1062 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1063 /// are at 4-byte boundaries.
1064 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1065   if (Subtarget->is64Bit()) {
1066     // Max of 8 and alignment of type.
1067     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1068     if (TyAlign > 8)
1069       return TyAlign;
1070     return 8;
1071   }
1072
1073   unsigned Align = 4;
1074   if (Subtarget->hasSSE1())
1075     getMaxByValAlign(Ty, Align);
1076   return Align;
1077 }
1078
1079 /// getOptimalMemOpType - Returns the target specific optimal type for load
1080 /// and store operations as a result of memset, memcpy, and memmove
1081 /// lowering. If DstAlign is zero that means it's safe to destination
1082 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1083 /// means there isn't a need to check it against alignment requirement,
1084 /// probably because the source does not need to be loaded. If
1085 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1086 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1087 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1088 /// constant so it does not need to be loaded.
1089 /// It returns EVT::Other if the type should be determined using generic
1090 /// target-independent logic.
1091 EVT
1092 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1093                                        unsigned DstAlign, unsigned SrcAlign,
1094                                        bool NonScalarIntSafe,
1095                                        bool MemcpyStrSrc,
1096                                        MachineFunction &MF) const {
1097   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1098   // linux.  This is because the stack realignment code can't handle certain
1099   // cases like PR2962.  This should be removed when PR2962 is fixed.
1100   const Function *F = MF.getFunction();
1101   if (NonScalarIntSafe &&
1102       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1103     if (Size >= 16 &&
1104         (Subtarget->isUnalignedMemAccessFast() ||
1105          ((DstAlign == 0 || DstAlign >= 16) &&
1106           (SrcAlign == 0 || SrcAlign >= 16))) &&
1107         Subtarget->getStackAlignment() >= 16) {
1108       if (Subtarget->hasSSE2())
1109         return MVT::v4i32;
1110       if (Subtarget->hasSSE1())
1111         return MVT::v4f32;
1112     } else if (!MemcpyStrSrc && Size >= 8 &&
1113                !Subtarget->is64Bit() &&
1114                Subtarget->getStackAlignment() >= 8 &&
1115                Subtarget->hasSSE2()) {
1116       // Do not use f64 to lower memcpy if source is string constant. It's
1117       // better to use i32 to avoid the loads.
1118       return MVT::f64;
1119     }
1120   }
1121   if (Subtarget->is64Bit() && Size >= 8)
1122     return MVT::i64;
1123   return MVT::i32;
1124 }
1125
1126 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1127 /// current function.  The returned value is a member of the
1128 /// MachineJumpTableInfo::JTEntryKind enum.
1129 unsigned X86TargetLowering::getJumpTableEncoding() const {
1130   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1131   // symbol.
1132   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1133       Subtarget->isPICStyleGOT())
1134     return MachineJumpTableInfo::EK_Custom32;
1135   
1136   // Otherwise, use the normal jump table encoding heuristics.
1137   return TargetLowering::getJumpTableEncoding();
1138 }
1139
1140 /// getPICBaseSymbol - Return the X86-32 PIC base.
1141 MCSymbol *
1142 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1143                                     MCContext &Ctx) const {
1144   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1145   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1146                                Twine(MF->getFunctionNumber())+"$pb");
1147 }
1148
1149
1150 const MCExpr *
1151 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1152                                              const MachineBasicBlock *MBB,
1153                                              unsigned uid,MCContext &Ctx) const{
1154   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1155          Subtarget->isPICStyleGOT());
1156   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1157   // entries.
1158   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1159                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1160 }
1161
1162 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1163 /// jumptable.
1164 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1165                                                     SelectionDAG &DAG) const {
1166   if (!Subtarget->is64Bit())
1167     // This doesn't have DebugLoc associated with it, but is not really the
1168     // same as a Register.
1169     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1170   return Table;
1171 }
1172
1173 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1174 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1175 /// MCExpr.
1176 const MCExpr *X86TargetLowering::
1177 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1178                              MCContext &Ctx) const {
1179   // X86-64 uses RIP relative addressing based on the jump table label.
1180   if (Subtarget->isPICStyleRIPRel())
1181     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1182
1183   // Otherwise, the reference is relative to the PIC base.
1184   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1185 }
1186
1187 /// getFunctionAlignment - Return the Log2 alignment of this function.
1188 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1189   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1190 }
1191
1192 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1193                                                unsigned &Offset) const {
1194   if (!Subtarget->isTargetLinux())
1195     return false;
1196
1197   if (Subtarget->is64Bit()) {
1198     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1199     Offset = 0x28;
1200     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1201       AddressSpace = 256;
1202     else
1203       AddressSpace = 257;
1204   } else {
1205     // %gs:0x14 on i386
1206     Offset = 0x14;
1207     AddressSpace = 256;
1208   }
1209   return true;
1210 }
1211
1212
1213 //===----------------------------------------------------------------------===//
1214 //               Return Value Calling Convention Implementation
1215 //===----------------------------------------------------------------------===//
1216
1217 #include "X86GenCallingConv.inc"
1218
1219 bool 
1220 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1221                         const SmallVectorImpl<EVT> &OutTys,
1222                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1223                         LLVMContext &Context) const {
1224   SmallVector<CCValAssign, 16> RVLocs;
1225   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1226                  RVLocs, Context);
1227   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1228 }
1229
1230 SDValue
1231 X86TargetLowering::LowerReturn(SDValue Chain,
1232                                CallingConv::ID CallConv, bool isVarArg,
1233                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1234                                const SmallVectorImpl<SDValue> &OutVals,
1235                                DebugLoc dl, SelectionDAG &DAG) const {
1236   MachineFunction &MF = DAG.getMachineFunction();
1237   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1238
1239   SmallVector<CCValAssign, 16> RVLocs;
1240   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1241                  RVLocs, *DAG.getContext());
1242   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1243
1244   // Add the regs to the liveout set for the function.
1245   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1246   for (unsigned i = 0; i != RVLocs.size(); ++i)
1247     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1248       MRI.addLiveOut(RVLocs[i].getLocReg());
1249
1250   SDValue Flag;
1251
1252   SmallVector<SDValue, 6> RetOps;
1253   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1254   // Operand #1 = Bytes To Pop
1255   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1256                    MVT::i16));
1257
1258   // Copy the result values into the output registers.
1259   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1260     CCValAssign &VA = RVLocs[i];
1261     assert(VA.isRegLoc() && "Can only return in registers!");
1262     SDValue ValToCopy = OutVals[i];
1263
1264     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1265     // the RET instruction and handled by the FP Stackifier.
1266     if (VA.getLocReg() == X86::ST0 ||
1267         VA.getLocReg() == X86::ST1) {
1268       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1269       // change the value to the FP stack register class.
1270       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1271         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1272       RetOps.push_back(ValToCopy);
1273       // Don't emit a copytoreg.
1274       continue;
1275     }
1276
1277     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1278     // which is returned in RAX / RDX.
1279     if (Subtarget->is64Bit()) {
1280       EVT ValVT = ValToCopy.getValueType();
1281       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1282         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1283         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1284           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1285       }
1286     }
1287
1288     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1289     Flag = Chain.getValue(1);
1290   }
1291
1292   // The x86-64 ABI for returning structs by value requires that we copy
1293   // the sret argument into %rax for the return. We saved the argument into
1294   // a virtual register in the entry block, so now we copy the value out
1295   // and into %rax.
1296   if (Subtarget->is64Bit() &&
1297       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1298     MachineFunction &MF = DAG.getMachineFunction();
1299     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1300     unsigned Reg = FuncInfo->getSRetReturnReg();
1301     assert(Reg && 
1302            "SRetReturnReg should have been set in LowerFormalArguments().");
1303     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1304
1305     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1306     Flag = Chain.getValue(1);
1307
1308     // RAX now acts like a return value.
1309     MRI.addLiveOut(X86::RAX);
1310   }
1311
1312   RetOps[0] = Chain;  // Update chain.
1313
1314   // Add the flag if we have it.
1315   if (Flag.getNode())
1316     RetOps.push_back(Flag);
1317
1318   return DAG.getNode(X86ISD::RET_FLAG, dl,
1319                      MVT::Other, &RetOps[0], RetOps.size());
1320 }
1321
1322 /// LowerCallResult - Lower the result values of a call into the
1323 /// appropriate copies out of appropriate physical registers.
1324 ///
1325 SDValue
1326 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1327                                    CallingConv::ID CallConv, bool isVarArg,
1328                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1329                                    DebugLoc dl, SelectionDAG &DAG,
1330                                    SmallVectorImpl<SDValue> &InVals) const {
1331
1332   // Assign locations to each value returned by this call.
1333   SmallVector<CCValAssign, 16> RVLocs;
1334   bool Is64Bit = Subtarget->is64Bit();
1335   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1336                  RVLocs, *DAG.getContext());
1337   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1338
1339   // Copy all of the result registers out of their specified physreg.
1340   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1341     CCValAssign &VA = RVLocs[i];
1342     EVT CopyVT = VA.getValVT();
1343
1344     // If this is x86-64, and we disabled SSE, we can't return FP values
1345     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1346         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1347       report_fatal_error("SSE register return with SSE disabled");
1348     }
1349
1350     // If this is a call to a function that returns an fp value on the floating
1351     // point stack, but where we prefer to use the value in xmm registers, copy
1352     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1353     if ((VA.getLocReg() == X86::ST0 ||
1354          VA.getLocReg() == X86::ST1) &&
1355         isScalarFPTypeInSSEReg(VA.getValVT())) {
1356       CopyVT = MVT::f80;
1357     }
1358
1359     SDValue Val;
1360     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1361       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1362       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1363         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1364                                    MVT::v2i64, InFlag).getValue(1);
1365         Val = Chain.getValue(0);
1366         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1367                           Val, DAG.getConstant(0, MVT::i64));
1368       } else {
1369         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1370                                    MVT::i64, InFlag).getValue(1);
1371         Val = Chain.getValue(0);
1372       }
1373       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1374     } else {
1375       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1376                                  CopyVT, InFlag).getValue(1);
1377       Val = Chain.getValue(0);
1378     }
1379     InFlag = Chain.getValue(2);
1380
1381     if (CopyVT != VA.getValVT()) {
1382       // Round the F80 the right size, which also moves to the appropriate xmm
1383       // register.
1384       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1385                         // This truncation won't change the value.
1386                         DAG.getIntPtrConstant(1));
1387     }
1388
1389     InVals.push_back(Val);
1390   }
1391
1392   return Chain;
1393 }
1394
1395
1396 //===----------------------------------------------------------------------===//
1397 //                C & StdCall & Fast Calling Convention implementation
1398 //===----------------------------------------------------------------------===//
1399 //  StdCall calling convention seems to be standard for many Windows' API
1400 //  routines and around. It differs from C calling convention just a little:
1401 //  callee should clean up the stack, not caller. Symbols should be also
1402 //  decorated in some fancy way :) It doesn't support any vector arguments.
1403 //  For info on fast calling convention see Fast Calling Convention (tail call)
1404 //  implementation LowerX86_32FastCCCallTo.
1405
1406 /// CallIsStructReturn - Determines whether a call uses struct return
1407 /// semantics.
1408 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1409   if (Outs.empty())
1410     return false;
1411
1412   return Outs[0].Flags.isSRet();
1413 }
1414
1415 /// ArgsAreStructReturn - Determines whether a function uses struct
1416 /// return semantics.
1417 static bool
1418 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1419   if (Ins.empty())
1420     return false;
1421
1422   return Ins[0].Flags.isSRet();
1423 }
1424
1425 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1426 /// given CallingConvention value.
1427 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1428   if (Subtarget->is64Bit()) {
1429     if (CC == CallingConv::GHC)
1430       return CC_X86_64_GHC;
1431     else if (Subtarget->isTargetWin64())
1432       return CC_X86_Win64_C;
1433     else
1434       return CC_X86_64_C;
1435   }
1436
1437   if (CC == CallingConv::X86_FastCall)
1438     return CC_X86_32_FastCall;
1439   else if (CC == CallingConv::X86_ThisCall)
1440     return CC_X86_32_ThisCall;
1441   else if (CC == CallingConv::Fast)
1442     return CC_X86_32_FastCC;
1443   else if (CC == CallingConv::GHC)
1444     return CC_X86_32_GHC;
1445   else
1446     return CC_X86_32_C;
1447 }
1448
1449 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1450 /// by "Src" to address "Dst" with size and alignment information specified by
1451 /// the specific parameter attribute. The copy will be passed as a byval
1452 /// function parameter.
1453 static SDValue
1454 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1455                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1456                           DebugLoc dl) {
1457   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1458   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1459                        /*isVolatile*/false, /*AlwaysInline=*/true,
1460                        NULL, 0, NULL, 0);
1461 }
1462
1463 /// IsTailCallConvention - Return true if the calling convention is one that
1464 /// supports tail call optimization.
1465 static bool IsTailCallConvention(CallingConv::ID CC) {
1466   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1467 }
1468
1469 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1470 /// a tailcall target by changing its ABI.
1471 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1472   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1473 }
1474
1475 SDValue
1476 X86TargetLowering::LowerMemArgument(SDValue Chain,
1477                                     CallingConv::ID CallConv,
1478                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1479                                     DebugLoc dl, SelectionDAG &DAG,
1480                                     const CCValAssign &VA,
1481                                     MachineFrameInfo *MFI,
1482                                     unsigned i) const {
1483   // Create the nodes corresponding to a load from this parameter slot.
1484   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1485   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1486   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1487   EVT ValVT;
1488
1489   // If value is passed by pointer we have address passed instead of the value
1490   // itself.
1491   if (VA.getLocInfo() == CCValAssign::Indirect)
1492     ValVT = VA.getLocVT();
1493   else
1494     ValVT = VA.getValVT();
1495
1496   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1497   // changed with more analysis.
1498   // In case of tail call optimization mark all arguments mutable. Since they
1499   // could be overwritten by lowering of arguments in case of a tail call.
1500   if (Flags.isByVal()) {
1501     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1502                                     VA.getLocMemOffset(), isImmutable);
1503     return DAG.getFrameIndex(FI, getPointerTy());
1504   } else {
1505     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1506                                     VA.getLocMemOffset(), isImmutable);
1507     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1508     return DAG.getLoad(ValVT, dl, Chain, FIN,
1509                        PseudoSourceValue::getFixedStack(FI), 0,
1510                        false, false, 0);
1511   }
1512 }
1513
1514 SDValue
1515 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1516                                         CallingConv::ID CallConv,
1517                                         bool isVarArg,
1518                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1519                                         DebugLoc dl,
1520                                         SelectionDAG &DAG,
1521                                         SmallVectorImpl<SDValue> &InVals)
1522                                           const {
1523   MachineFunction &MF = DAG.getMachineFunction();
1524   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1525
1526   const Function* Fn = MF.getFunction();
1527   if (Fn->hasExternalLinkage() &&
1528       Subtarget->isTargetCygMing() &&
1529       Fn->getName() == "main")
1530     FuncInfo->setForceFramePointer(true);
1531
1532   MachineFrameInfo *MFI = MF.getFrameInfo();
1533   bool Is64Bit = Subtarget->is64Bit();
1534   bool IsWin64 = Subtarget->isTargetWin64();
1535
1536   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1537          "Var args not supported with calling convention fastcc or ghc");
1538
1539   // Assign locations to all of the incoming arguments.
1540   SmallVector<CCValAssign, 16> ArgLocs;
1541   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1542                  ArgLocs, *DAG.getContext());
1543   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1544
1545   unsigned LastVal = ~0U;
1546   SDValue ArgValue;
1547   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1548     CCValAssign &VA = ArgLocs[i];
1549     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1550     // places.
1551     assert(VA.getValNo() != LastVal &&
1552            "Don't support value assigned to multiple locs yet");
1553     LastVal = VA.getValNo();
1554
1555     if (VA.isRegLoc()) {
1556       EVT RegVT = VA.getLocVT();
1557       TargetRegisterClass *RC = NULL;
1558       if (RegVT == MVT::i32)
1559         RC = X86::GR32RegisterClass;
1560       else if (Is64Bit && RegVT == MVT::i64)
1561         RC = X86::GR64RegisterClass;
1562       else if (RegVT == MVT::f32)
1563         RC = X86::FR32RegisterClass;
1564       else if (RegVT == MVT::f64)
1565         RC = X86::FR64RegisterClass;
1566       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1567         RC = X86::VR128RegisterClass;
1568       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1569         RC = X86::VR64RegisterClass;
1570       else
1571         llvm_unreachable("Unknown argument type!");
1572
1573       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1574       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1575
1576       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1577       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1578       // right size.
1579       if (VA.getLocInfo() == CCValAssign::SExt)
1580         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1581                                DAG.getValueType(VA.getValVT()));
1582       else if (VA.getLocInfo() == CCValAssign::ZExt)
1583         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1584                                DAG.getValueType(VA.getValVT()));
1585       else if (VA.getLocInfo() == CCValAssign::BCvt)
1586         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1587
1588       if (VA.isExtInLoc()) {
1589         // Handle MMX values passed in XMM regs.
1590         if (RegVT.isVector()) {
1591           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1592                                  ArgValue, DAG.getConstant(0, MVT::i64));
1593           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1594         } else
1595           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1596       }
1597     } else {
1598       assert(VA.isMemLoc());
1599       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1600     }
1601
1602     // If value is passed via pointer - do a load.
1603     if (VA.getLocInfo() == CCValAssign::Indirect)
1604       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1605                              false, false, 0);
1606
1607     InVals.push_back(ArgValue);
1608   }
1609
1610   // The x86-64 ABI for returning structs by value requires that we copy
1611   // the sret argument into %rax for the return. Save the argument into
1612   // a virtual register so that we can access it from the return points.
1613   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1614     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1615     unsigned Reg = FuncInfo->getSRetReturnReg();
1616     if (!Reg) {
1617       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1618       FuncInfo->setSRetReturnReg(Reg);
1619     }
1620     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1621     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1622   }
1623
1624   unsigned StackSize = CCInfo.getNextStackOffset();
1625   // Align stack specially for tail calls.
1626   if (FuncIsMadeTailCallSafe(CallConv))
1627     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1628
1629   // If the function takes variable number of arguments, make a frame index for
1630   // the start of the first vararg value... for expansion of llvm.va_start.
1631   if (isVarArg) {
1632     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1633                     CallConv != CallingConv::X86_ThisCall)) {
1634       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1635     }
1636     if (Is64Bit) {
1637       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1638
1639       // FIXME: We should really autogenerate these arrays
1640       static const unsigned GPR64ArgRegsWin64[] = {
1641         X86::RCX, X86::RDX, X86::R8,  X86::R9
1642       };
1643       static const unsigned XMMArgRegsWin64[] = {
1644         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1645       };
1646       static const unsigned GPR64ArgRegs64Bit[] = {
1647         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1648       };
1649       static const unsigned XMMArgRegs64Bit[] = {
1650         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1651         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1652       };
1653       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1654
1655       if (IsWin64) {
1656         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1657         GPR64ArgRegs = GPR64ArgRegsWin64;
1658         XMMArgRegs = XMMArgRegsWin64;
1659       } else {
1660         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1661         GPR64ArgRegs = GPR64ArgRegs64Bit;
1662         XMMArgRegs = XMMArgRegs64Bit;
1663       }
1664       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1665                                                        TotalNumIntRegs);
1666       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1667                                                        TotalNumXMMRegs);
1668
1669       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1670       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1671              "SSE register cannot be used when SSE is disabled!");
1672       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1673              "SSE register cannot be used when SSE is disabled!");
1674       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1675         // Kernel mode asks for SSE to be disabled, so don't push them
1676         // on the stack.
1677         TotalNumXMMRegs = 0;
1678
1679       // For X86-64, if there are vararg parameters that are passed via
1680       // registers, then we must store them to their spots on the stack so they
1681       // may be loaded by deferencing the result of va_next.
1682       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1683       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1684       FuncInfo->setRegSaveFrameIndex(
1685         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1686                                false));
1687
1688       // Store the integer parameter registers.
1689       SmallVector<SDValue, 8> MemOps;
1690       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1691                                         getPointerTy());
1692       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1693       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1694         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1695                                   DAG.getIntPtrConstant(Offset));
1696         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1697                                      X86::GR64RegisterClass);
1698         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1699         SDValue Store =
1700           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1701                        PseudoSourceValue::getFixedStack(
1702                          FuncInfo->getRegSaveFrameIndex()),
1703                        Offset, false, false, 0);
1704         MemOps.push_back(Store);
1705         Offset += 8;
1706       }
1707
1708       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1709         // Now store the XMM (fp + vector) parameter registers.
1710         SmallVector<SDValue, 11> SaveXMMOps;
1711         SaveXMMOps.push_back(Chain);
1712
1713         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1714         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1715         SaveXMMOps.push_back(ALVal);
1716
1717         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1718                                FuncInfo->getRegSaveFrameIndex()));
1719         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1720                                FuncInfo->getVarArgsFPOffset()));
1721
1722         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1723           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1724                                        X86::VR128RegisterClass);
1725           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1726           SaveXMMOps.push_back(Val);
1727         }
1728         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1729                                      MVT::Other,
1730                                      &SaveXMMOps[0], SaveXMMOps.size()));
1731       }
1732
1733       if (!MemOps.empty())
1734         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1735                             &MemOps[0], MemOps.size());
1736     }
1737   }
1738
1739   // Some CCs need callee pop.
1740   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1741     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1742   } else {
1743     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1744     // If this is an sret function, the return should pop the hidden pointer.
1745     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1746       FuncInfo->setBytesToPopOnReturn(4);
1747   }
1748
1749   if (!Is64Bit) {
1750     // RegSaveFrameIndex is X86-64 only.
1751     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1752     if (CallConv == CallingConv::X86_FastCall ||
1753         CallConv == CallingConv::X86_ThisCall)
1754       // fastcc functions can't have varargs.
1755       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1756   }
1757
1758   return Chain;
1759 }
1760
1761 SDValue
1762 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1763                                     SDValue StackPtr, SDValue Arg,
1764                                     DebugLoc dl, SelectionDAG &DAG,
1765                                     const CCValAssign &VA,
1766                                     ISD::ArgFlagsTy Flags) const {
1767   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1768   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1769   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1770   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1771   if (Flags.isByVal()) {
1772     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1773   }
1774   return DAG.getStore(Chain, dl, Arg, PtrOff,
1775                       PseudoSourceValue::getStack(), LocMemOffset,
1776                       false, false, 0);
1777 }
1778
1779 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1780 /// optimization is performed and it is required.
1781 SDValue
1782 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1783                                            SDValue &OutRetAddr, SDValue Chain,
1784                                            bool IsTailCall, bool Is64Bit,
1785                                            int FPDiff, DebugLoc dl) const {
1786   // Adjust the Return address stack slot.
1787   EVT VT = getPointerTy();
1788   OutRetAddr = getReturnAddressFrameIndex(DAG);
1789
1790   // Load the "old" Return address.
1791   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1792   return SDValue(OutRetAddr.getNode(), 1);
1793 }
1794
1795 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1796 /// optimization is performed and it is required (FPDiff!=0).
1797 static SDValue
1798 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1799                          SDValue Chain, SDValue RetAddrFrIdx,
1800                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1801   // Store the return address to the appropriate stack slot.
1802   if (!FPDiff) return Chain;
1803   // Calculate the new stack slot for the return address.
1804   int SlotSize = Is64Bit ? 8 : 4;
1805   int NewReturnAddrFI =
1806     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1807   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1808   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1809   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1810                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1811                        false, false, 0);
1812   return Chain;
1813 }
1814
1815 SDValue
1816 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1817                              CallingConv::ID CallConv, bool isVarArg,
1818                              bool &isTailCall,
1819                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1820                              const SmallVectorImpl<SDValue> &OutVals,
1821                              const SmallVectorImpl<ISD::InputArg> &Ins,
1822                              DebugLoc dl, SelectionDAG &DAG,
1823                              SmallVectorImpl<SDValue> &InVals) const {
1824   MachineFunction &MF = DAG.getMachineFunction();
1825   bool Is64Bit        = Subtarget->is64Bit();
1826   bool IsStructRet    = CallIsStructReturn(Outs);
1827   bool IsSibcall      = false;
1828
1829   if (isTailCall) {
1830     // Check if it's really possible to do a tail call.
1831     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1832                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1833                                                    Outs, OutVals, Ins, DAG);
1834
1835     // Sibcalls are automatically detected tailcalls which do not require
1836     // ABI changes.
1837     if (!GuaranteedTailCallOpt && isTailCall)
1838       IsSibcall = true;
1839
1840     if (isTailCall)
1841       ++NumTailCalls;
1842   }
1843
1844   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1845          "Var args not supported with calling convention fastcc or ghc");
1846
1847   // Analyze operands of the call, assigning locations to each operand.
1848   SmallVector<CCValAssign, 16> ArgLocs;
1849   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1850                  ArgLocs, *DAG.getContext());
1851   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1852
1853   // Get a count of how many bytes are to be pushed on the stack.
1854   unsigned NumBytes = CCInfo.getNextStackOffset();
1855   if (IsSibcall)
1856     // This is a sibcall. The memory operands are available in caller's
1857     // own caller's stack.
1858     NumBytes = 0;
1859   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1860     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1861
1862   int FPDiff = 0;
1863   if (isTailCall && !IsSibcall) {
1864     // Lower arguments at fp - stackoffset + fpdiff.
1865     unsigned NumBytesCallerPushed =
1866       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1867     FPDiff = NumBytesCallerPushed - NumBytes;
1868
1869     // Set the delta of movement of the returnaddr stackslot.
1870     // But only set if delta is greater than previous delta.
1871     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1872       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1873   }
1874
1875   if (!IsSibcall)
1876     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1877
1878   SDValue RetAddrFrIdx;
1879   // Load return adress for tail calls.
1880   if (isTailCall && FPDiff)
1881     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1882                                     Is64Bit, FPDiff, dl);
1883
1884   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1885   SmallVector<SDValue, 8> MemOpChains;
1886   SDValue StackPtr;
1887
1888   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1889   // of tail call optimization arguments are handle later.
1890   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1891     CCValAssign &VA = ArgLocs[i];
1892     EVT RegVT = VA.getLocVT();
1893     SDValue Arg = OutVals[i];
1894     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1895     bool isByVal = Flags.isByVal();
1896
1897     // Promote the value if needed.
1898     switch (VA.getLocInfo()) {
1899     default: llvm_unreachable("Unknown loc info!");
1900     case CCValAssign::Full: break;
1901     case CCValAssign::SExt:
1902       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1903       break;
1904     case CCValAssign::ZExt:
1905       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1906       break;
1907     case CCValAssign::AExt:
1908       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1909         // Special case: passing MMX values in XMM registers.
1910         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1911         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1912         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1913       } else
1914         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1915       break;
1916     case CCValAssign::BCvt:
1917       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1918       break;
1919     case CCValAssign::Indirect: {
1920       // Store the argument.
1921       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1922       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1923       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1924                            PseudoSourceValue::getFixedStack(FI), 0,
1925                            false, false, 0);
1926       Arg = SpillSlot;
1927       break;
1928     }
1929     }
1930
1931     if (VA.isRegLoc()) {
1932       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1933     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1934       assert(VA.isMemLoc());
1935       if (StackPtr.getNode() == 0)
1936         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1937       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1938                                              dl, DAG, VA, Flags));
1939     }
1940   }
1941
1942   if (!MemOpChains.empty())
1943     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1944                         &MemOpChains[0], MemOpChains.size());
1945
1946   // Build a sequence of copy-to-reg nodes chained together with token chain
1947   // and flag operands which copy the outgoing args into registers.
1948   SDValue InFlag;
1949   // Tail call byval lowering might overwrite argument registers so in case of
1950   // tail call optimization the copies to registers are lowered later.
1951   if (!isTailCall)
1952     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1953       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1954                                RegsToPass[i].second, InFlag);
1955       InFlag = Chain.getValue(1);
1956     }
1957
1958   if (Subtarget->isPICStyleGOT()) {
1959     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1960     // GOT pointer.
1961     if (!isTailCall) {
1962       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1963                                DAG.getNode(X86ISD::GlobalBaseReg,
1964                                            DebugLoc(), getPointerTy()),
1965                                InFlag);
1966       InFlag = Chain.getValue(1);
1967     } else {
1968       // If we are tail calling and generating PIC/GOT style code load the
1969       // address of the callee into ECX. The value in ecx is used as target of
1970       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1971       // for tail calls on PIC/GOT architectures. Normally we would just put the
1972       // address of GOT into ebx and then call target@PLT. But for tail calls
1973       // ebx would be restored (since ebx is callee saved) before jumping to the
1974       // target@PLT.
1975
1976       // Note: The actual moving to ECX is done further down.
1977       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1978       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1979           !G->getGlobal()->hasProtectedVisibility())
1980         Callee = LowerGlobalAddress(Callee, DAG);
1981       else if (isa<ExternalSymbolSDNode>(Callee))
1982         Callee = LowerExternalSymbol(Callee, DAG);
1983     }
1984   }
1985
1986   if (Is64Bit && isVarArg) {
1987     // From AMD64 ABI document:
1988     // For calls that may call functions that use varargs or stdargs
1989     // (prototype-less calls or calls to functions containing ellipsis (...) in
1990     // the declaration) %al is used as hidden argument to specify the number
1991     // of SSE registers used. The contents of %al do not need to match exactly
1992     // the number of registers, but must be an ubound on the number of SSE
1993     // registers used and is in the range 0 - 8 inclusive.
1994
1995     // FIXME: Verify this on Win64
1996     // Count the number of XMM registers allocated.
1997     static const unsigned XMMArgRegs[] = {
1998       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1999       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2000     };
2001     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2002     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2003            && "SSE registers cannot be used when SSE is disabled");
2004
2005     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2006                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2007     InFlag = Chain.getValue(1);
2008   }
2009
2010
2011   // For tail calls lower the arguments to the 'real' stack slot.
2012   if (isTailCall) {
2013     // Force all the incoming stack arguments to be loaded from the stack
2014     // before any new outgoing arguments are stored to the stack, because the
2015     // outgoing stack slots may alias the incoming argument stack slots, and
2016     // the alias isn't otherwise explicit. This is slightly more conservative
2017     // than necessary, because it means that each store effectively depends
2018     // on every argument instead of just those arguments it would clobber.
2019     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2020
2021     SmallVector<SDValue, 8> MemOpChains2;
2022     SDValue FIN;
2023     int FI = 0;
2024     // Do not flag preceeding copytoreg stuff together with the following stuff.
2025     InFlag = SDValue();
2026     if (GuaranteedTailCallOpt) {
2027       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2028         CCValAssign &VA = ArgLocs[i];
2029         if (VA.isRegLoc())
2030           continue;
2031         assert(VA.isMemLoc());
2032         SDValue Arg = OutVals[i];
2033         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2034         // Create frame index.
2035         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2036         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2037         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2038         FIN = DAG.getFrameIndex(FI, getPointerTy());
2039
2040         if (Flags.isByVal()) {
2041           // Copy relative to framepointer.
2042           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2043           if (StackPtr.getNode() == 0)
2044             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2045                                           getPointerTy());
2046           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2047
2048           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2049                                                            ArgChain,
2050                                                            Flags, DAG, dl));
2051         } else {
2052           // Store relative to framepointer.
2053           MemOpChains2.push_back(
2054             DAG.getStore(ArgChain, dl, Arg, FIN,
2055                          PseudoSourceValue::getFixedStack(FI), 0,
2056                          false, false, 0));
2057         }
2058       }
2059     }
2060
2061     if (!MemOpChains2.empty())
2062       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2063                           &MemOpChains2[0], MemOpChains2.size());
2064
2065     // Copy arguments to their registers.
2066     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2067       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2068                                RegsToPass[i].second, InFlag);
2069       InFlag = Chain.getValue(1);
2070     }
2071     InFlag =SDValue();
2072
2073     // Store the return address to the appropriate stack slot.
2074     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2075                                      FPDiff, dl);
2076   }
2077
2078   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2079     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2080     // In the 64-bit large code model, we have to make all calls
2081     // through a register, since the call instruction's 32-bit
2082     // pc-relative offset may not be large enough to hold the whole
2083     // address.
2084   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2085     // If the callee is a GlobalAddress node (quite common, every direct call
2086     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2087     // it.
2088
2089     // We should use extra load for direct calls to dllimported functions in
2090     // non-JIT mode.
2091     const GlobalValue *GV = G->getGlobal();
2092     if (!GV->hasDLLImportLinkage()) {
2093       unsigned char OpFlags = 0;
2094
2095       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2096       // external symbols most go through the PLT in PIC mode.  If the symbol
2097       // has hidden or protected visibility, or if it is static or local, then
2098       // we don't need to use the PLT - we can directly call it.
2099       if (Subtarget->isTargetELF() &&
2100           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2101           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2102         OpFlags = X86II::MO_PLT;
2103       } else if (Subtarget->isPICStyleStubAny() &&
2104                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2105                Subtarget->getDarwinVers() < 9) {
2106         // PC-relative references to external symbols should go through $stub,
2107         // unless we're building with the leopard linker or later, which
2108         // automatically synthesizes these stubs.
2109         OpFlags = X86II::MO_DARWIN_STUB;
2110       }
2111
2112       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2113                                           G->getOffset(), OpFlags);
2114     }
2115   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2116     unsigned char OpFlags = 0;
2117
2118     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2119     // symbols should go through the PLT.
2120     if (Subtarget->isTargetELF() &&
2121         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2122       OpFlags = X86II::MO_PLT;
2123     } else if (Subtarget->isPICStyleStubAny() &&
2124              Subtarget->getDarwinVers() < 9) {
2125       // PC-relative references to external symbols should go through $stub,
2126       // unless we're building with the leopard linker or later, which
2127       // automatically synthesizes these stubs.
2128       OpFlags = X86II::MO_DARWIN_STUB;
2129     }
2130
2131     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2132                                          OpFlags);
2133   }
2134
2135   // Returns a chain & a flag for retval copy to use.
2136   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2137   SmallVector<SDValue, 8> Ops;
2138
2139   if (!IsSibcall && isTailCall) {
2140     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2141                            DAG.getIntPtrConstant(0, true), InFlag);
2142     InFlag = Chain.getValue(1);
2143   }
2144
2145   Ops.push_back(Chain);
2146   Ops.push_back(Callee);
2147
2148   if (isTailCall)
2149     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2150
2151   // Add argument registers to the end of the list so that they are known live
2152   // into the call.
2153   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2154     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2155                                   RegsToPass[i].second.getValueType()));
2156
2157   // Add an implicit use GOT pointer in EBX.
2158   if (!isTailCall && Subtarget->isPICStyleGOT())
2159     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2160
2161   // Add an implicit use of AL for x86 vararg functions.
2162   if (Is64Bit && isVarArg)
2163     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2164
2165   if (InFlag.getNode())
2166     Ops.push_back(InFlag);
2167
2168   if (isTailCall) {
2169     // We used to do:
2170     //// If this is the first return lowered for this function, add the regs
2171     //// to the liveout set for the function.
2172     // This isn't right, although it's probably harmless on x86; liveouts
2173     // should be computed from returns not tail calls.  Consider a void
2174     // function making a tail call to a function returning int.
2175     return DAG.getNode(X86ISD::TC_RETURN, dl,
2176                        NodeTys, &Ops[0], Ops.size());
2177   }
2178
2179   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2180   InFlag = Chain.getValue(1);
2181
2182   // Create the CALLSEQ_END node.
2183   unsigned NumBytesForCalleeToPush;
2184   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2185     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2186   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2187     // If this is a call to a struct-return function, the callee
2188     // pops the hidden struct pointer, so we have to push it back.
2189     // This is common for Darwin/X86, Linux & Mingw32 targets.
2190     NumBytesForCalleeToPush = 4;
2191   else
2192     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2193
2194   // Returns a flag for retval copy to use.
2195   if (!IsSibcall) {
2196     Chain = DAG.getCALLSEQ_END(Chain,
2197                                DAG.getIntPtrConstant(NumBytes, true),
2198                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2199                                                      true),
2200                                InFlag);
2201     InFlag = Chain.getValue(1);
2202   }
2203
2204   // Handle result values, copying them out of physregs into vregs that we
2205   // return.
2206   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2207                          Ins, dl, DAG, InVals);
2208 }
2209
2210
2211 //===----------------------------------------------------------------------===//
2212 //                Fast Calling Convention (tail call) implementation
2213 //===----------------------------------------------------------------------===//
2214
2215 //  Like std call, callee cleans arguments, convention except that ECX is
2216 //  reserved for storing the tail called function address. Only 2 registers are
2217 //  free for argument passing (inreg). Tail call optimization is performed
2218 //  provided:
2219 //                * tailcallopt is enabled
2220 //                * caller/callee are fastcc
2221 //  On X86_64 architecture with GOT-style position independent code only local
2222 //  (within module) calls are supported at the moment.
2223 //  To keep the stack aligned according to platform abi the function
2224 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2225 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2226 //  If a tail called function callee has more arguments than the caller the
2227 //  caller needs to make sure that there is room to move the RETADDR to. This is
2228 //  achieved by reserving an area the size of the argument delta right after the
2229 //  original REtADDR, but before the saved framepointer or the spilled registers
2230 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2231 //  stack layout:
2232 //    arg1
2233 //    arg2
2234 //    RETADDR
2235 //    [ new RETADDR
2236 //      move area ]
2237 //    (possible EBP)
2238 //    ESI
2239 //    EDI
2240 //    local1 ..
2241
2242 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2243 /// for a 16 byte align requirement.
2244 unsigned
2245 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2246                                                SelectionDAG& DAG) const {
2247   MachineFunction &MF = DAG.getMachineFunction();
2248   const TargetMachine &TM = MF.getTarget();
2249   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2250   unsigned StackAlignment = TFI.getStackAlignment();
2251   uint64_t AlignMask = StackAlignment - 1;
2252   int64_t Offset = StackSize;
2253   uint64_t SlotSize = TD->getPointerSize();
2254   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2255     // Number smaller than 12 so just add the difference.
2256     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2257   } else {
2258     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2259     Offset = ((~AlignMask) & Offset) + StackAlignment +
2260       (StackAlignment-SlotSize);
2261   }
2262   return Offset;
2263 }
2264
2265 /// MatchingStackOffset - Return true if the given stack call argument is
2266 /// already available in the same position (relatively) of the caller's
2267 /// incoming argument stack.
2268 static
2269 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2270                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2271                          const X86InstrInfo *TII) {
2272   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2273   int FI = INT_MAX;
2274   if (Arg.getOpcode() == ISD::CopyFromReg) {
2275     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2276     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2277       return false;
2278     MachineInstr *Def = MRI->getVRegDef(VR);
2279     if (!Def)
2280       return false;
2281     if (!Flags.isByVal()) {
2282       if (!TII->isLoadFromStackSlot(Def, FI))
2283         return false;
2284     } else {
2285       unsigned Opcode = Def->getOpcode();
2286       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2287           Def->getOperand(1).isFI()) {
2288         FI = Def->getOperand(1).getIndex();
2289         Bytes = Flags.getByValSize();
2290       } else
2291         return false;
2292     }
2293   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2294     if (Flags.isByVal())
2295       // ByVal argument is passed in as a pointer but it's now being
2296       // dereferenced. e.g.
2297       // define @foo(%struct.X* %A) {
2298       //   tail call @bar(%struct.X* byval %A)
2299       // }
2300       return false;
2301     SDValue Ptr = Ld->getBasePtr();
2302     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2303     if (!FINode)
2304       return false;
2305     FI = FINode->getIndex();
2306   } else
2307     return false;
2308
2309   assert(FI != INT_MAX);
2310   if (!MFI->isFixedObjectIndex(FI))
2311     return false;
2312   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2313 }
2314
2315 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2316 /// for tail call optimization. Targets which want to do tail call
2317 /// optimization should implement this function.
2318 bool
2319 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2320                                                      CallingConv::ID CalleeCC,
2321                                                      bool isVarArg,
2322                                                      bool isCalleeStructRet,
2323                                                      bool isCallerStructRet,
2324                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2325                                     const SmallVectorImpl<SDValue> &OutVals,
2326                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2327                                                      SelectionDAG& DAG) const {
2328   if (!IsTailCallConvention(CalleeCC) &&
2329       CalleeCC != CallingConv::C)
2330     return false;
2331
2332   // If -tailcallopt is specified, make fastcc functions tail-callable.
2333   const MachineFunction &MF = DAG.getMachineFunction();
2334   const Function *CallerF = DAG.getMachineFunction().getFunction();
2335   CallingConv::ID CallerCC = CallerF->getCallingConv();
2336   bool CCMatch = CallerCC == CalleeCC;
2337
2338   if (GuaranteedTailCallOpt) {
2339     if (IsTailCallConvention(CalleeCC) && CCMatch)
2340       return true;
2341     return false;
2342   }
2343
2344   // Look for obvious safe cases to perform tail call optimization that do not
2345   // require ABI changes. This is what gcc calls sibcall.
2346
2347   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2348   // emit a special epilogue.
2349   if (RegInfo->needsStackRealignment(MF))
2350     return false;
2351
2352   // Do not sibcall optimize vararg calls unless the call site is not passing any
2353   // arguments.
2354   if (isVarArg && !Outs.empty())
2355     return false;
2356
2357   // Also avoid sibcall optimization if either caller or callee uses struct
2358   // return semantics.
2359   if (isCalleeStructRet || isCallerStructRet)
2360     return false;
2361
2362   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2363   // Therefore if it's not used by the call it is not safe to optimize this into
2364   // a sibcall.
2365   bool Unused = false;
2366   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2367     if (!Ins[i].Used) {
2368       Unused = true;
2369       break;
2370     }
2371   }
2372   if (Unused) {
2373     SmallVector<CCValAssign, 16> RVLocs;
2374     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2375                    RVLocs, *DAG.getContext());
2376     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2377     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2378       CCValAssign &VA = RVLocs[i];
2379       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2380         return false;
2381     }
2382   }
2383
2384   // If the calling conventions do not match, then we'd better make sure the
2385   // results are returned in the same way as what the caller expects.
2386   if (!CCMatch) {
2387     SmallVector<CCValAssign, 16> RVLocs1;
2388     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2389                     RVLocs1, *DAG.getContext());
2390     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2391
2392     SmallVector<CCValAssign, 16> RVLocs2;
2393     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2394                     RVLocs2, *DAG.getContext());
2395     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2396
2397     if (RVLocs1.size() != RVLocs2.size())
2398       return false;
2399     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2400       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2401         return false;
2402       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2403         return false;
2404       if (RVLocs1[i].isRegLoc()) {
2405         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2406           return false;
2407       } else {
2408         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2409           return false;
2410       }
2411     }
2412   }
2413
2414   // If the callee takes no arguments then go on to check the results of the
2415   // call.
2416   if (!Outs.empty()) {
2417     // Check if stack adjustment is needed. For now, do not do this if any
2418     // argument is passed on the stack.
2419     SmallVector<CCValAssign, 16> ArgLocs;
2420     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2421                    ArgLocs, *DAG.getContext());
2422     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2423     if (CCInfo.getNextStackOffset()) {
2424       MachineFunction &MF = DAG.getMachineFunction();
2425       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2426         return false;
2427       if (Subtarget->isTargetWin64())
2428         // Win64 ABI has additional complications.
2429         return false;
2430
2431       // Check if the arguments are already laid out in the right way as
2432       // the caller's fixed stack objects.
2433       MachineFrameInfo *MFI = MF.getFrameInfo();
2434       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2435       const X86InstrInfo *TII =
2436         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2437       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2438         CCValAssign &VA = ArgLocs[i];
2439         SDValue Arg = OutVals[i];
2440         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2441         if (VA.getLocInfo() == CCValAssign::Indirect)
2442           return false;
2443         if (!VA.isRegLoc()) {
2444           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2445                                    MFI, MRI, TII))
2446             return false;
2447         }
2448       }
2449     }
2450
2451     // If the tailcall address may be in a register, then make sure it's
2452     // possible to register allocate for it. In 32-bit, the call address can
2453     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2454     // callee-saved registers are restored. In 64-bit, it's RAX, RCX, RDX, RSI,
2455     // RDI, R8, R9, R11.
2456     if (!isa<GlobalAddressSDNode>(Callee) &&
2457         !isa<ExternalSymbolSDNode>(Callee)) {
2458       unsigned Limit = Subtarget->is64Bit() ? 8 : 3;
2459       unsigned NumInRegs = 0;
2460       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2461         CCValAssign &VA = ArgLocs[i];
2462         if (VA.isRegLoc()) {
2463           if (++NumInRegs == Limit)
2464             return false;
2465         }
2466       }
2467     }
2468   }
2469
2470   return true;
2471 }
2472
2473 FastISel *
2474 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2475   return X86::createFastISel(funcInfo);
2476 }
2477
2478
2479 //===----------------------------------------------------------------------===//
2480 //                           Other Lowering Hooks
2481 //===----------------------------------------------------------------------===//
2482
2483
2484 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2485   MachineFunction &MF = DAG.getMachineFunction();
2486   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2487   int ReturnAddrIndex = FuncInfo->getRAIndex();
2488
2489   if (ReturnAddrIndex == 0) {
2490     // Set up a frame object for the return address.
2491     uint64_t SlotSize = TD->getPointerSize();
2492     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2493                                                            false);
2494     FuncInfo->setRAIndex(ReturnAddrIndex);
2495   }
2496
2497   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2498 }
2499
2500
2501 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2502                                        bool hasSymbolicDisplacement) {
2503   // Offset should fit into 32 bit immediate field.
2504   if (!isInt<32>(Offset))
2505     return false;
2506
2507   // If we don't have a symbolic displacement - we don't have any extra
2508   // restrictions.
2509   if (!hasSymbolicDisplacement)
2510     return true;
2511
2512   // FIXME: Some tweaks might be needed for medium code model.
2513   if (M != CodeModel::Small && M != CodeModel::Kernel)
2514     return false;
2515
2516   // For small code model we assume that latest object is 16MB before end of 31
2517   // bits boundary. We may also accept pretty large negative constants knowing
2518   // that all objects are in the positive half of address space.
2519   if (M == CodeModel::Small && Offset < 16*1024*1024)
2520     return true;
2521
2522   // For kernel code model we know that all object resist in the negative half
2523   // of 32bits address space. We may not accept negative offsets, since they may
2524   // be just off and we may accept pretty large positive ones.
2525   if (M == CodeModel::Kernel && Offset > 0)
2526     return true;
2527
2528   return false;
2529 }
2530
2531 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2532 /// specific condition code, returning the condition code and the LHS/RHS of the
2533 /// comparison to make.
2534 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2535                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2536   if (!isFP) {
2537     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2538       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2539         // X > -1   -> X == 0, jump !sign.
2540         RHS = DAG.getConstant(0, RHS.getValueType());
2541         return X86::COND_NS;
2542       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2543         // X < 0   -> X == 0, jump on sign.
2544         return X86::COND_S;
2545       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2546         // X < 1   -> X <= 0
2547         RHS = DAG.getConstant(0, RHS.getValueType());
2548         return X86::COND_LE;
2549       }
2550     }
2551
2552     switch (SetCCOpcode) {
2553     default: llvm_unreachable("Invalid integer condition!");
2554     case ISD::SETEQ:  return X86::COND_E;
2555     case ISD::SETGT:  return X86::COND_G;
2556     case ISD::SETGE:  return X86::COND_GE;
2557     case ISD::SETLT:  return X86::COND_L;
2558     case ISD::SETLE:  return X86::COND_LE;
2559     case ISD::SETNE:  return X86::COND_NE;
2560     case ISD::SETULT: return X86::COND_B;
2561     case ISD::SETUGT: return X86::COND_A;
2562     case ISD::SETULE: return X86::COND_BE;
2563     case ISD::SETUGE: return X86::COND_AE;
2564     }
2565   }
2566
2567   // First determine if it is required or is profitable to flip the operands.
2568
2569   // If LHS is a foldable load, but RHS is not, flip the condition.
2570   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2571       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2572     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2573     std::swap(LHS, RHS);
2574   }
2575
2576   switch (SetCCOpcode) {
2577   default: break;
2578   case ISD::SETOLT:
2579   case ISD::SETOLE:
2580   case ISD::SETUGT:
2581   case ISD::SETUGE:
2582     std::swap(LHS, RHS);
2583     break;
2584   }
2585
2586   // On a floating point condition, the flags are set as follows:
2587   // ZF  PF  CF   op
2588   //  0 | 0 | 0 | X > Y
2589   //  0 | 0 | 1 | X < Y
2590   //  1 | 0 | 0 | X == Y
2591   //  1 | 1 | 1 | unordered
2592   switch (SetCCOpcode) {
2593   default: llvm_unreachable("Condcode should be pre-legalized away");
2594   case ISD::SETUEQ:
2595   case ISD::SETEQ:   return X86::COND_E;
2596   case ISD::SETOLT:              // flipped
2597   case ISD::SETOGT:
2598   case ISD::SETGT:   return X86::COND_A;
2599   case ISD::SETOLE:              // flipped
2600   case ISD::SETOGE:
2601   case ISD::SETGE:   return X86::COND_AE;
2602   case ISD::SETUGT:              // flipped
2603   case ISD::SETULT:
2604   case ISD::SETLT:   return X86::COND_B;
2605   case ISD::SETUGE:              // flipped
2606   case ISD::SETULE:
2607   case ISD::SETLE:   return X86::COND_BE;
2608   case ISD::SETONE:
2609   case ISD::SETNE:   return X86::COND_NE;
2610   case ISD::SETUO:   return X86::COND_P;
2611   case ISD::SETO:    return X86::COND_NP;
2612   case ISD::SETOEQ:
2613   case ISD::SETUNE:  return X86::COND_INVALID;
2614   }
2615 }
2616
2617 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2618 /// code. Current x86 isa includes the following FP cmov instructions:
2619 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2620 static bool hasFPCMov(unsigned X86CC) {
2621   switch (X86CC) {
2622   default:
2623     return false;
2624   case X86::COND_B:
2625   case X86::COND_BE:
2626   case X86::COND_E:
2627   case X86::COND_P:
2628   case X86::COND_A:
2629   case X86::COND_AE:
2630   case X86::COND_NE:
2631   case X86::COND_NP:
2632     return true;
2633   }
2634 }
2635
2636 /// isFPImmLegal - Returns true if the target can instruction select the
2637 /// specified FP immediate natively. If false, the legalizer will
2638 /// materialize the FP immediate as a load from a constant pool.
2639 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2640   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2641     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2642       return true;
2643   }
2644   return false;
2645 }
2646
2647 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2648 /// the specified range (L, H].
2649 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2650   return (Val < 0) || (Val >= Low && Val < Hi);
2651 }
2652
2653 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2654 /// specified value.
2655 static bool isUndefOrEqual(int Val, int CmpVal) {
2656   if (Val < 0 || Val == CmpVal)
2657     return true;
2658   return false;
2659 }
2660
2661 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2662 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2663 /// the second operand.
2664 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2665   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2666     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2667   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2668     return (Mask[0] < 2 && Mask[1] < 2);
2669   return false;
2670 }
2671
2672 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2673   SmallVector<int, 8> M;
2674   N->getMask(M);
2675   return ::isPSHUFDMask(M, N->getValueType(0));
2676 }
2677
2678 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2679 /// is suitable for input to PSHUFHW.
2680 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2681   if (VT != MVT::v8i16)
2682     return false;
2683
2684   // Lower quadword copied in order or undef.
2685   for (int i = 0; i != 4; ++i)
2686     if (Mask[i] >= 0 && Mask[i] != i)
2687       return false;
2688
2689   // Upper quadword shuffled.
2690   for (int i = 4; i != 8; ++i)
2691     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2692       return false;
2693
2694   return true;
2695 }
2696
2697 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2698   SmallVector<int, 8> M;
2699   N->getMask(M);
2700   return ::isPSHUFHWMask(M, N->getValueType(0));
2701 }
2702
2703 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2704 /// is suitable for input to PSHUFLW.
2705 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2706   if (VT != MVT::v8i16)
2707     return false;
2708
2709   // Upper quadword copied in order.
2710   for (int i = 4; i != 8; ++i)
2711     if (Mask[i] >= 0 && Mask[i] != i)
2712       return false;
2713
2714   // Lower quadword shuffled.
2715   for (int i = 0; i != 4; ++i)
2716     if (Mask[i] >= 4)
2717       return false;
2718
2719   return true;
2720 }
2721
2722 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2723   SmallVector<int, 8> M;
2724   N->getMask(M);
2725   return ::isPSHUFLWMask(M, N->getValueType(0));
2726 }
2727
2728 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2729 /// is suitable for input to PALIGNR.
2730 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2731                           bool hasSSSE3) {
2732   int i, e = VT.getVectorNumElements();
2733   
2734   // Do not handle v2i64 / v2f64 shuffles with palignr.
2735   if (e < 4 || !hasSSSE3)
2736     return false;
2737   
2738   for (i = 0; i != e; ++i)
2739     if (Mask[i] >= 0)
2740       break;
2741   
2742   // All undef, not a palignr.
2743   if (i == e)
2744     return false;
2745
2746   // Determine if it's ok to perform a palignr with only the LHS, since we
2747   // don't have access to the actual shuffle elements to see if RHS is undef.
2748   bool Unary = Mask[i] < (int)e;
2749   bool NeedsUnary = false;
2750
2751   int s = Mask[i] - i;
2752   
2753   // Check the rest of the elements to see if they are consecutive.
2754   for (++i; i != e; ++i) {
2755     int m = Mask[i];
2756     if (m < 0) 
2757       continue;
2758     
2759     Unary = Unary && (m < (int)e);
2760     NeedsUnary = NeedsUnary || (m < s);
2761
2762     if (NeedsUnary && !Unary)
2763       return false;
2764     if (Unary && m != ((s+i) & (e-1)))
2765       return false;
2766     if (!Unary && m != (s+i))
2767       return false;
2768   }
2769   return true;
2770 }
2771
2772 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2773   SmallVector<int, 8> M;
2774   N->getMask(M);
2775   return ::isPALIGNRMask(M, N->getValueType(0), true);
2776 }
2777
2778 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2779 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2780 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2781   int NumElems = VT.getVectorNumElements();
2782   if (NumElems != 2 && NumElems != 4)
2783     return false;
2784
2785   int Half = NumElems / 2;
2786   for (int i = 0; i < Half; ++i)
2787     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2788       return false;
2789   for (int i = Half; i < NumElems; ++i)
2790     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2791       return false;
2792
2793   return true;
2794 }
2795
2796 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2797   SmallVector<int, 8> M;
2798   N->getMask(M);
2799   return ::isSHUFPMask(M, N->getValueType(0));
2800 }
2801
2802 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2803 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2804 /// half elements to come from vector 1 (which would equal the dest.) and
2805 /// the upper half to come from vector 2.
2806 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2807   int NumElems = VT.getVectorNumElements();
2808
2809   if (NumElems != 2 && NumElems != 4)
2810     return false;
2811
2812   int Half = NumElems / 2;
2813   for (int i = 0; i < Half; ++i)
2814     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2815       return false;
2816   for (int i = Half; i < NumElems; ++i)
2817     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2818       return false;
2819   return true;
2820 }
2821
2822 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2823   SmallVector<int, 8> M;
2824   N->getMask(M);
2825   return isCommutedSHUFPMask(M, N->getValueType(0));
2826 }
2827
2828 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2829 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2830 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2831   if (N->getValueType(0).getVectorNumElements() != 4)
2832     return false;
2833
2834   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2835   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2836          isUndefOrEqual(N->getMaskElt(1), 7) &&
2837          isUndefOrEqual(N->getMaskElt(2), 2) &&
2838          isUndefOrEqual(N->getMaskElt(3), 3);
2839 }
2840
2841 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2842 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2843 /// <2, 3, 2, 3>
2844 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2845   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2846   
2847   if (NumElems != 4)
2848     return false;
2849   
2850   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2851   isUndefOrEqual(N->getMaskElt(1), 3) &&
2852   isUndefOrEqual(N->getMaskElt(2), 2) &&
2853   isUndefOrEqual(N->getMaskElt(3), 3);
2854 }
2855
2856 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2857 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2858 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2859   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2860
2861   if (NumElems != 2 && NumElems != 4)
2862     return false;
2863
2864   for (unsigned i = 0; i < NumElems/2; ++i)
2865     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2866       return false;
2867
2868   for (unsigned i = NumElems/2; i < NumElems; ++i)
2869     if (!isUndefOrEqual(N->getMaskElt(i), i))
2870       return false;
2871
2872   return true;
2873 }
2874
2875 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2876 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2877 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2878   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2879
2880   if (NumElems != 2 && NumElems != 4)
2881     return false;
2882
2883   for (unsigned i = 0; i < NumElems/2; ++i)
2884     if (!isUndefOrEqual(N->getMaskElt(i), i))
2885       return false;
2886
2887   for (unsigned i = 0; i < NumElems/2; ++i)
2888     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2889       return false;
2890
2891   return true;
2892 }
2893
2894 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2895 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2896 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2897                          bool V2IsSplat = false) {
2898   int NumElts = VT.getVectorNumElements();
2899   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2900     return false;
2901
2902   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2903     int BitI  = Mask[i];
2904     int BitI1 = Mask[i+1];
2905     if (!isUndefOrEqual(BitI, j))
2906       return false;
2907     if (V2IsSplat) {
2908       if (!isUndefOrEqual(BitI1, NumElts))
2909         return false;
2910     } else {
2911       if (!isUndefOrEqual(BitI1, j + NumElts))
2912         return false;
2913     }
2914   }
2915   return true;
2916 }
2917
2918 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2919   SmallVector<int, 8> M;
2920   N->getMask(M);
2921   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2922 }
2923
2924 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2925 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2926 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2927                          bool V2IsSplat = false) {
2928   int NumElts = VT.getVectorNumElements();
2929   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2930     return false;
2931
2932   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2933     int BitI  = Mask[i];
2934     int BitI1 = Mask[i+1];
2935     if (!isUndefOrEqual(BitI, j + NumElts/2))
2936       return false;
2937     if (V2IsSplat) {
2938       if (isUndefOrEqual(BitI1, NumElts))
2939         return false;
2940     } else {
2941       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2942         return false;
2943     }
2944   }
2945   return true;
2946 }
2947
2948 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2949   SmallVector<int, 8> M;
2950   N->getMask(M);
2951   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2952 }
2953
2954 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2955 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2956 /// <0, 0, 1, 1>
2957 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2958   int NumElems = VT.getVectorNumElements();
2959   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2960     return false;
2961
2962   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2963     int BitI  = Mask[i];
2964     int BitI1 = Mask[i+1];
2965     if (!isUndefOrEqual(BitI, j))
2966       return false;
2967     if (!isUndefOrEqual(BitI1, j))
2968       return false;
2969   }
2970   return true;
2971 }
2972
2973 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2974   SmallVector<int, 8> M;
2975   N->getMask(M);
2976   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2977 }
2978
2979 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2980 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2981 /// <2, 2, 3, 3>
2982 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2983   int NumElems = VT.getVectorNumElements();
2984   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2985     return false;
2986
2987   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2988     int BitI  = Mask[i];
2989     int BitI1 = Mask[i+1];
2990     if (!isUndefOrEqual(BitI, j))
2991       return false;
2992     if (!isUndefOrEqual(BitI1, j))
2993       return false;
2994   }
2995   return true;
2996 }
2997
2998 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2999   SmallVector<int, 8> M;
3000   N->getMask(M);
3001   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3002 }
3003
3004 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3005 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3006 /// MOVSD, and MOVD, i.e. setting the lowest element.
3007 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3008   if (VT.getVectorElementType().getSizeInBits() < 32)
3009     return false;
3010
3011   int NumElts = VT.getVectorNumElements();
3012
3013   if (!isUndefOrEqual(Mask[0], NumElts))
3014     return false;
3015
3016   for (int i = 1; i < NumElts; ++i)
3017     if (!isUndefOrEqual(Mask[i], i))
3018       return false;
3019
3020   return true;
3021 }
3022
3023 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3024   SmallVector<int, 8> M;
3025   N->getMask(M);
3026   return ::isMOVLMask(M, N->getValueType(0));
3027 }
3028
3029 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3030 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3031 /// element of vector 2 and the other elements to come from vector 1 in order.
3032 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3033                                bool V2IsSplat = false, bool V2IsUndef = false) {
3034   int NumOps = VT.getVectorNumElements();
3035   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3036     return false;
3037
3038   if (!isUndefOrEqual(Mask[0], 0))
3039     return false;
3040
3041   for (int i = 1; i < NumOps; ++i)
3042     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3043           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3044           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3045       return false;
3046
3047   return true;
3048 }
3049
3050 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3051                            bool V2IsUndef = false) {
3052   SmallVector<int, 8> M;
3053   N->getMask(M);
3054   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3055 }
3056
3057 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3058 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3059 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3060   if (N->getValueType(0).getVectorNumElements() != 4)
3061     return false;
3062
3063   // Expect 1, 1, 3, 3
3064   for (unsigned i = 0; i < 2; ++i) {
3065     int Elt = N->getMaskElt(i);
3066     if (Elt >= 0 && Elt != 1)
3067       return false;
3068   }
3069
3070   bool HasHi = false;
3071   for (unsigned i = 2; i < 4; ++i) {
3072     int Elt = N->getMaskElt(i);
3073     if (Elt >= 0 && Elt != 3)
3074       return false;
3075     if (Elt == 3)
3076       HasHi = true;
3077   }
3078   // Don't use movshdup if it can be done with a shufps.
3079   // FIXME: verify that matching u, u, 3, 3 is what we want.
3080   return HasHi;
3081 }
3082
3083 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3084 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3085 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3086   if (N->getValueType(0).getVectorNumElements() != 4)
3087     return false;
3088
3089   // Expect 0, 0, 2, 2
3090   for (unsigned i = 0; i < 2; ++i)
3091     if (N->getMaskElt(i) > 0)
3092       return false;
3093
3094   bool HasHi = false;
3095   for (unsigned i = 2; i < 4; ++i) {
3096     int Elt = N->getMaskElt(i);
3097     if (Elt >= 0 && Elt != 2)
3098       return false;
3099     if (Elt == 2)
3100       HasHi = true;
3101   }
3102   // Don't use movsldup if it can be done with a shufps.
3103   return HasHi;
3104 }
3105
3106 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3107 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3108 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3109   int e = N->getValueType(0).getVectorNumElements() / 2;
3110
3111   for (int i = 0; i < e; ++i)
3112     if (!isUndefOrEqual(N->getMaskElt(i), i))
3113       return false;
3114   for (int i = 0; i < e; ++i)
3115     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3116       return false;
3117   return true;
3118 }
3119
3120 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3121 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3122 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3123   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3124   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3125
3126   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3127   unsigned Mask = 0;
3128   for (int i = 0; i < NumOperands; ++i) {
3129     int Val = SVOp->getMaskElt(NumOperands-i-1);
3130     if (Val < 0) Val = 0;
3131     if (Val >= NumOperands) Val -= NumOperands;
3132     Mask |= Val;
3133     if (i != NumOperands - 1)
3134       Mask <<= Shift;
3135   }
3136   return Mask;
3137 }
3138
3139 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3140 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3141 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3142   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3143   unsigned Mask = 0;
3144   // 8 nodes, but we only care about the last 4.
3145   for (unsigned i = 7; i >= 4; --i) {
3146     int Val = SVOp->getMaskElt(i);
3147     if (Val >= 0)
3148       Mask |= (Val - 4);
3149     if (i != 4)
3150       Mask <<= 2;
3151   }
3152   return Mask;
3153 }
3154
3155 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3156 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3157 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3158   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3159   unsigned Mask = 0;
3160   // 8 nodes, but we only care about the first 4.
3161   for (int i = 3; i >= 0; --i) {
3162     int Val = SVOp->getMaskElt(i);
3163     if (Val >= 0)
3164       Mask |= Val;
3165     if (i != 0)
3166       Mask <<= 2;
3167   }
3168   return Mask;
3169 }
3170
3171 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3172 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3173 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3174   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3175   EVT VVT = N->getValueType(0);
3176   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3177   int Val = 0;
3178
3179   unsigned i, e;
3180   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3181     Val = SVOp->getMaskElt(i);
3182     if (Val >= 0)
3183       break;
3184   }
3185   return (Val - i) * EltSize;
3186 }
3187
3188 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3189 /// constant +0.0.
3190 bool X86::isZeroNode(SDValue Elt) {
3191   return ((isa<ConstantSDNode>(Elt) &&
3192            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3193           (isa<ConstantFPSDNode>(Elt) &&
3194            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3195 }
3196
3197 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3198 /// their permute mask.
3199 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3200                                     SelectionDAG &DAG) {
3201   EVT VT = SVOp->getValueType(0);
3202   unsigned NumElems = VT.getVectorNumElements();
3203   SmallVector<int, 8> MaskVec;
3204
3205   for (unsigned i = 0; i != NumElems; ++i) {
3206     int idx = SVOp->getMaskElt(i);
3207     if (idx < 0)
3208       MaskVec.push_back(idx);
3209     else if (idx < (int)NumElems)
3210       MaskVec.push_back(idx + NumElems);
3211     else
3212       MaskVec.push_back(idx - NumElems);
3213   }
3214   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3215                               SVOp->getOperand(0), &MaskVec[0]);
3216 }
3217
3218 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3219 /// the two vector operands have swapped position.
3220 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3221   unsigned NumElems = VT.getVectorNumElements();
3222   for (unsigned i = 0; i != NumElems; ++i) {
3223     int idx = Mask[i];
3224     if (idx < 0)
3225       continue;
3226     else if (idx < (int)NumElems)
3227       Mask[i] = idx + NumElems;
3228     else
3229       Mask[i] = idx - NumElems;
3230   }
3231 }
3232
3233 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3234 /// match movhlps. The lower half elements should come from upper half of
3235 /// V1 (and in order), and the upper half elements should come from the upper
3236 /// half of V2 (and in order).
3237 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3238   if (Op->getValueType(0).getVectorNumElements() != 4)
3239     return false;
3240   for (unsigned i = 0, e = 2; i != e; ++i)
3241     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3242       return false;
3243   for (unsigned i = 2; i != 4; ++i)
3244     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3245       return false;
3246   return true;
3247 }
3248
3249 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3250 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3251 /// required.
3252 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3253   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3254     return false;
3255   N = N->getOperand(0).getNode();
3256   if (!ISD::isNON_EXTLoad(N))
3257     return false;
3258   if (LD)
3259     *LD = cast<LoadSDNode>(N);
3260   return true;
3261 }
3262
3263 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3264 /// match movlp{s|d}. The lower half elements should come from lower half of
3265 /// V1 (and in order), and the upper half elements should come from the upper
3266 /// half of V2 (and in order). And since V1 will become the source of the
3267 /// MOVLP, it must be either a vector load or a scalar load to vector.
3268 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3269                                ShuffleVectorSDNode *Op) {
3270   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3271     return false;
3272   // Is V2 is a vector load, don't do this transformation. We will try to use
3273   // load folding shufps op.
3274   if (ISD::isNON_EXTLoad(V2))
3275     return false;
3276
3277   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3278
3279   if (NumElems != 2 && NumElems != 4)
3280     return false;
3281   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3282     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3283       return false;
3284   for (unsigned i = NumElems/2; i != NumElems; ++i)
3285     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3286       return false;
3287   return true;
3288 }
3289
3290 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3291 /// all the same.
3292 static bool isSplatVector(SDNode *N) {
3293   if (N->getOpcode() != ISD::BUILD_VECTOR)
3294     return false;
3295
3296   SDValue SplatValue = N->getOperand(0);
3297   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3298     if (N->getOperand(i) != SplatValue)
3299       return false;
3300   return true;
3301 }
3302
3303 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3304 /// to an zero vector.
3305 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3306 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3307   SDValue V1 = N->getOperand(0);
3308   SDValue V2 = N->getOperand(1);
3309   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3310   for (unsigned i = 0; i != NumElems; ++i) {
3311     int Idx = N->getMaskElt(i);
3312     if (Idx >= (int)NumElems) {
3313       unsigned Opc = V2.getOpcode();
3314       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3315         continue;
3316       if (Opc != ISD::BUILD_VECTOR ||
3317           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3318         return false;
3319     } else if (Idx >= 0) {
3320       unsigned Opc = V1.getOpcode();
3321       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3322         continue;
3323       if (Opc != ISD::BUILD_VECTOR ||
3324           !X86::isZeroNode(V1.getOperand(Idx)))
3325         return false;
3326     }
3327   }
3328   return true;
3329 }
3330
3331 /// getZeroVector - Returns a vector of specified type with all zero elements.
3332 ///
3333 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3334                              DebugLoc dl) {
3335   assert(VT.isVector() && "Expected a vector type");
3336
3337   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3338   // type.  This ensures they get CSE'd.
3339   SDValue Vec;
3340   if (VT.getSizeInBits() == 64) { // MMX
3341     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3342     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3343   } else if (HasSSE2) {  // SSE2
3344     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3345     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3346   } else { // SSE1
3347     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3348     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3349   }
3350   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3351 }
3352
3353 /// getOnesVector - Returns a vector of specified type with all bits set.
3354 ///
3355 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3356   assert(VT.isVector() && "Expected a vector type");
3357
3358   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3359   // type.  This ensures they get CSE'd.
3360   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3361   SDValue Vec;
3362   if (VT.getSizeInBits() == 64)  // MMX
3363     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3364   else                                              // SSE
3365     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3366   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3367 }
3368
3369
3370 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3371 /// that point to V2 points to its first element.
3372 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3373   EVT VT = SVOp->getValueType(0);
3374   unsigned NumElems = VT.getVectorNumElements();
3375
3376   bool Changed = false;
3377   SmallVector<int, 8> MaskVec;
3378   SVOp->getMask(MaskVec);
3379
3380   for (unsigned i = 0; i != NumElems; ++i) {
3381     if (MaskVec[i] > (int)NumElems) {
3382       MaskVec[i] = NumElems;
3383       Changed = true;
3384     }
3385   }
3386   if (Changed)
3387     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3388                                 SVOp->getOperand(1), &MaskVec[0]);
3389   return SDValue(SVOp, 0);
3390 }
3391
3392 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3393 /// operation of specified width.
3394 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3395                        SDValue V2) {
3396   unsigned NumElems = VT.getVectorNumElements();
3397   SmallVector<int, 8> Mask;
3398   Mask.push_back(NumElems);
3399   for (unsigned i = 1; i != NumElems; ++i)
3400     Mask.push_back(i);
3401   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3402 }
3403
3404 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3405 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3406                           SDValue V2) {
3407   unsigned NumElems = VT.getVectorNumElements();
3408   SmallVector<int, 8> Mask;
3409   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3410     Mask.push_back(i);
3411     Mask.push_back(i + NumElems);
3412   }
3413   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3414 }
3415
3416 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3417 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3418                           SDValue V2) {
3419   unsigned NumElems = VT.getVectorNumElements();
3420   unsigned Half = NumElems/2;
3421   SmallVector<int, 8> Mask;
3422   for (unsigned i = 0; i != Half; ++i) {
3423     Mask.push_back(i + Half);
3424     Mask.push_back(i + NumElems + Half);
3425   }
3426   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3427 }
3428
3429 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3430 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3431                             bool HasSSE2) {
3432   if (SV->getValueType(0).getVectorNumElements() <= 4)
3433     return SDValue(SV, 0);
3434
3435   EVT PVT = MVT::v4f32;
3436   EVT VT = SV->getValueType(0);
3437   DebugLoc dl = SV->getDebugLoc();
3438   SDValue V1 = SV->getOperand(0);
3439   int NumElems = VT.getVectorNumElements();
3440   int EltNo = SV->getSplatIndex();
3441
3442   // unpack elements to the correct location
3443   while (NumElems > 4) {
3444     if (EltNo < NumElems/2) {
3445       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3446     } else {
3447       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3448       EltNo -= NumElems/2;
3449     }
3450     NumElems >>= 1;
3451   }
3452
3453   // Perform the splat.
3454   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3455   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3456   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3457   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3458 }
3459
3460 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3461 /// vector of zero or undef vector.  This produces a shuffle where the low
3462 /// element of V2 is swizzled into the zero/undef vector, landing at element
3463 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3464 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3465                                              bool isZero, bool HasSSE2,
3466                                              SelectionDAG &DAG) {
3467   EVT VT = V2.getValueType();
3468   SDValue V1 = isZero
3469     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3470   unsigned NumElems = VT.getVectorNumElements();
3471   SmallVector<int, 16> MaskVec;
3472   for (unsigned i = 0; i != NumElems; ++i)
3473     // If this is the insertion idx, put the low elt of V2 here.
3474     MaskVec.push_back(i == Idx ? NumElems : i);
3475   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3476 }
3477
3478 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3479 /// a shuffle that is zero.
3480 static
3481 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3482                                   bool Low, SelectionDAG &DAG) {
3483   unsigned NumZeros = 0;
3484   for (int i = 0; i < NumElems; ++i) {
3485     unsigned Index = Low ? i : NumElems-i-1;
3486     int Idx = SVOp->getMaskElt(Index);
3487     if (Idx < 0) {
3488       ++NumZeros;
3489       continue;
3490     }
3491     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3492     if (Elt.getNode() && X86::isZeroNode(Elt))
3493       ++NumZeros;
3494     else
3495       break;
3496   }
3497   return NumZeros;
3498 }
3499
3500 /// isVectorShift - Returns true if the shuffle can be implemented as a
3501 /// logical left or right shift of a vector.
3502 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3503 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3504                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3505   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3506
3507   isLeft = true;
3508   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3509   if (!NumZeros) {
3510     isLeft = false;
3511     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3512     if (!NumZeros)
3513       return false;
3514   }
3515   bool SeenV1 = false;
3516   bool SeenV2 = false;
3517   for (unsigned i = NumZeros; i < NumElems; ++i) {
3518     unsigned Val = isLeft ? (i - NumZeros) : i;
3519     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3520     if (Idx_ < 0)
3521       continue;
3522     unsigned Idx = (unsigned) Idx_;
3523     if (Idx < NumElems)
3524       SeenV1 = true;
3525     else {
3526       Idx -= NumElems;
3527       SeenV2 = true;
3528     }
3529     if (Idx != Val)
3530       return false;
3531   }
3532   if (SeenV1 && SeenV2)
3533     return false;
3534
3535   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3536   ShAmt = NumZeros;
3537   return true;
3538 }
3539
3540
3541 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3542 ///
3543 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3544                                        unsigned NumNonZero, unsigned NumZero,
3545                                        SelectionDAG &DAG,
3546                                        const TargetLowering &TLI) {
3547   if (NumNonZero > 8)
3548     return SDValue();
3549
3550   DebugLoc dl = Op.getDebugLoc();
3551   SDValue V(0, 0);
3552   bool First = true;
3553   for (unsigned i = 0; i < 16; ++i) {
3554     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3555     if (ThisIsNonZero && First) {
3556       if (NumZero)
3557         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3558       else
3559         V = DAG.getUNDEF(MVT::v8i16);
3560       First = false;
3561     }
3562
3563     if ((i & 1) != 0) {
3564       SDValue ThisElt(0, 0), LastElt(0, 0);
3565       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3566       if (LastIsNonZero) {
3567         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3568                               MVT::i16, Op.getOperand(i-1));
3569       }
3570       if (ThisIsNonZero) {
3571         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3572         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3573                               ThisElt, DAG.getConstant(8, MVT::i8));
3574         if (LastIsNonZero)
3575           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3576       } else
3577         ThisElt = LastElt;
3578
3579       if (ThisElt.getNode())
3580         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3581                         DAG.getIntPtrConstant(i/2));
3582     }
3583   }
3584
3585   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3586 }
3587
3588 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3589 ///
3590 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3591                                      unsigned NumNonZero, unsigned NumZero,
3592                                      SelectionDAG &DAG,
3593                                      const TargetLowering &TLI) {
3594   if (NumNonZero > 4)
3595     return SDValue();
3596
3597   DebugLoc dl = Op.getDebugLoc();
3598   SDValue V(0, 0);
3599   bool First = true;
3600   for (unsigned i = 0; i < 8; ++i) {
3601     bool isNonZero = (NonZeros & (1 << i)) != 0;
3602     if (isNonZero) {
3603       if (First) {
3604         if (NumZero)
3605           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3606         else
3607           V = DAG.getUNDEF(MVT::v8i16);
3608         First = false;
3609       }
3610       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3611                       MVT::v8i16, V, Op.getOperand(i),
3612                       DAG.getIntPtrConstant(i));
3613     }
3614   }
3615
3616   return V;
3617 }
3618
3619 /// getVShift - Return a vector logical shift node.
3620 ///
3621 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3622                          unsigned NumBits, SelectionDAG &DAG,
3623                          const TargetLowering &TLI, DebugLoc dl) {
3624   bool isMMX = VT.getSizeInBits() == 64;
3625   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3626   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3627   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3628   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3629                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3630                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3631 }
3632
3633 SDValue
3634 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3635                                           SelectionDAG &DAG) const {
3636   
3637   // Check if the scalar load can be widened into a vector load. And if
3638   // the address is "base + cst" see if the cst can be "absorbed" into
3639   // the shuffle mask.
3640   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3641     SDValue Ptr = LD->getBasePtr();
3642     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3643       return SDValue();
3644     EVT PVT = LD->getValueType(0);
3645     if (PVT != MVT::i32 && PVT != MVT::f32)
3646       return SDValue();
3647
3648     int FI = -1;
3649     int64_t Offset = 0;
3650     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3651       FI = FINode->getIndex();
3652       Offset = 0;
3653     } else if (Ptr.getOpcode() == ISD::ADD &&
3654                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3655                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3656       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3657       Offset = Ptr.getConstantOperandVal(1);
3658       Ptr = Ptr.getOperand(0);
3659     } else {
3660       return SDValue();
3661     }
3662
3663     SDValue Chain = LD->getChain();
3664     // Make sure the stack object alignment is at least 16.
3665     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3666     if (DAG.InferPtrAlignment(Ptr) < 16) {
3667       if (MFI->isFixedObjectIndex(FI)) {
3668         // Can't change the alignment. FIXME: It's possible to compute
3669         // the exact stack offset and reference FI + adjust offset instead.
3670         // If someone *really* cares about this. That's the way to implement it.
3671         return SDValue();
3672       } else {
3673         MFI->setObjectAlignment(FI, 16);
3674       }
3675     }
3676
3677     // (Offset % 16) must be multiple of 4. Then address is then
3678     // Ptr + (Offset & ~15).
3679     if (Offset < 0)
3680       return SDValue();
3681     if ((Offset % 16) & 3)
3682       return SDValue();
3683     int64_t StartOffset = Offset & ~15;
3684     if (StartOffset)
3685       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3686                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3687
3688     int EltNo = (Offset - StartOffset) >> 2;
3689     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3690     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3691     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3692                              false, false, 0);
3693     // Canonicalize it to a v4i32 shuffle.
3694     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3695     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3696                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3697                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3698   }
3699
3700   return SDValue();
3701 }
3702
3703 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3704 /// vector of type 'VT', see if the elements can be replaced by a single large 
3705 /// load which has the same value as a build_vector whose operands are 'elts'.
3706 ///
3707 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3708 /// 
3709 /// FIXME: we'd also like to handle the case where the last elements are zero
3710 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3711 /// There's even a handy isZeroNode for that purpose.
3712 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3713                                         DebugLoc &dl, SelectionDAG &DAG) {
3714   EVT EltVT = VT.getVectorElementType();
3715   unsigned NumElems = Elts.size();
3716   
3717   LoadSDNode *LDBase = NULL;
3718   unsigned LastLoadedElt = -1U;
3719   
3720   // For each element in the initializer, see if we've found a load or an undef.
3721   // If we don't find an initial load element, or later load elements are 
3722   // non-consecutive, bail out.
3723   for (unsigned i = 0; i < NumElems; ++i) {
3724     SDValue Elt = Elts[i];
3725     
3726     if (!Elt.getNode() ||
3727         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3728       return SDValue();
3729     if (!LDBase) {
3730       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3731         return SDValue();
3732       LDBase = cast<LoadSDNode>(Elt.getNode());
3733       LastLoadedElt = i;
3734       continue;
3735     }
3736     if (Elt.getOpcode() == ISD::UNDEF)
3737       continue;
3738
3739     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3740     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3741       return SDValue();
3742     LastLoadedElt = i;
3743   }
3744
3745   // If we have found an entire vector of loads and undefs, then return a large
3746   // load of the entire vector width starting at the base pointer.  If we found
3747   // consecutive loads for the low half, generate a vzext_load node.
3748   if (LastLoadedElt == NumElems - 1) {
3749     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3750       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3751                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3752                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3753     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3754                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3755                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3756                        LDBase->getAlignment());
3757   } else if (NumElems == 4 && LastLoadedElt == 1) {
3758     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3759     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3760     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3761     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3762   }
3763   return SDValue();
3764 }
3765
3766 SDValue
3767 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3768   DebugLoc dl = Op.getDebugLoc();
3769   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3770   if (ISD::isBuildVectorAllZeros(Op.getNode())
3771       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3772     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3773     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3774     // eliminated on x86-32 hosts.
3775     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3776       return Op;
3777
3778     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3779       return getOnesVector(Op.getValueType(), DAG, dl);
3780     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3781   }
3782
3783   EVT VT = Op.getValueType();
3784   EVT ExtVT = VT.getVectorElementType();
3785   unsigned EVTBits = ExtVT.getSizeInBits();
3786
3787   unsigned NumElems = Op.getNumOperands();
3788   unsigned NumZero  = 0;
3789   unsigned NumNonZero = 0;
3790   unsigned NonZeros = 0;
3791   bool IsAllConstants = true;
3792   SmallSet<SDValue, 8> Values;
3793   for (unsigned i = 0; i < NumElems; ++i) {
3794     SDValue Elt = Op.getOperand(i);
3795     if (Elt.getOpcode() == ISD::UNDEF)
3796       continue;
3797     Values.insert(Elt);
3798     if (Elt.getOpcode() != ISD::Constant &&
3799         Elt.getOpcode() != ISD::ConstantFP)
3800       IsAllConstants = false;
3801     if (X86::isZeroNode(Elt))
3802       NumZero++;
3803     else {
3804       NonZeros |= (1 << i);
3805       NumNonZero++;
3806     }
3807   }
3808
3809   if (NumNonZero == 0) {
3810     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3811     return DAG.getUNDEF(VT);
3812   }
3813
3814   // Special case for single non-zero, non-undef, element.
3815   if (NumNonZero == 1) {
3816     unsigned Idx = CountTrailingZeros_32(NonZeros);
3817     SDValue Item = Op.getOperand(Idx);
3818
3819     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3820     // the value are obviously zero, truncate the value to i32 and do the
3821     // insertion that way.  Only do this if the value is non-constant or if the
3822     // value is a constant being inserted into element 0.  It is cheaper to do
3823     // a constant pool load than it is to do a movd + shuffle.
3824     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3825         (!IsAllConstants || Idx == 0)) {
3826       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3827         // Handle MMX and SSE both.
3828         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3829         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3830
3831         // Truncate the value (which may itself be a constant) to i32, and
3832         // convert it to a vector with movd (S2V+shuffle to zero extend).
3833         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3834         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3835         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3836                                            Subtarget->hasSSE2(), DAG);
3837
3838         // Now we have our 32-bit value zero extended in the low element of
3839         // a vector.  If Idx != 0, swizzle it into place.
3840         if (Idx != 0) {
3841           SmallVector<int, 4> Mask;
3842           Mask.push_back(Idx);
3843           for (unsigned i = 1; i != VecElts; ++i)
3844             Mask.push_back(i);
3845           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3846                                       DAG.getUNDEF(Item.getValueType()),
3847                                       &Mask[0]);
3848         }
3849         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3850       }
3851     }
3852
3853     // If we have a constant or non-constant insertion into the low element of
3854     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3855     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3856     // depending on what the source datatype is.
3857     if (Idx == 0) {
3858       if (NumZero == 0) {
3859         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3860       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3861           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3862         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3863         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3864         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3865                                            DAG);
3866       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3867         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3868         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3869         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3870         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3871                                            Subtarget->hasSSE2(), DAG);
3872         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3873       }
3874     }
3875
3876     // Is it a vector logical left shift?
3877     if (NumElems == 2 && Idx == 1 &&
3878         X86::isZeroNode(Op.getOperand(0)) &&
3879         !X86::isZeroNode(Op.getOperand(1))) {
3880       unsigned NumBits = VT.getSizeInBits();
3881       return getVShift(true, VT,
3882                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3883                                    VT, Op.getOperand(1)),
3884                        NumBits/2, DAG, *this, dl);
3885     }
3886
3887     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3888       return SDValue();
3889
3890     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3891     // is a non-constant being inserted into an element other than the low one,
3892     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3893     // movd/movss) to move this into the low element, then shuffle it into
3894     // place.
3895     if (EVTBits == 32) {
3896       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3897
3898       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3899       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3900                                          Subtarget->hasSSE2(), DAG);
3901       SmallVector<int, 8> MaskVec;
3902       for (unsigned i = 0; i < NumElems; i++)
3903         MaskVec.push_back(i == Idx ? 0 : 1);
3904       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3905     }
3906   }
3907
3908   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3909   if (Values.size() == 1) {
3910     if (EVTBits == 32) {
3911       // Instead of a shuffle like this:
3912       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3913       // Check if it's possible to issue this instead.
3914       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3915       unsigned Idx = CountTrailingZeros_32(NonZeros);
3916       SDValue Item = Op.getOperand(Idx);
3917       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3918         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3919     }
3920     return SDValue();
3921   }
3922
3923   // A vector full of immediates; various special cases are already
3924   // handled, so this is best done with a single constant-pool load.
3925   if (IsAllConstants)
3926     return SDValue();
3927
3928   // Let legalizer expand 2-wide build_vectors.
3929   if (EVTBits == 64) {
3930     if (NumNonZero == 1) {
3931       // One half is zero or undef.
3932       unsigned Idx = CountTrailingZeros_32(NonZeros);
3933       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3934                                  Op.getOperand(Idx));
3935       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3936                                          Subtarget->hasSSE2(), DAG);
3937     }
3938     return SDValue();
3939   }
3940
3941   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3942   if (EVTBits == 8 && NumElems == 16) {
3943     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3944                                         *this);
3945     if (V.getNode()) return V;
3946   }
3947
3948   if (EVTBits == 16 && NumElems == 8) {
3949     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3950                                         *this);
3951     if (V.getNode()) return V;
3952   }
3953
3954   // If element VT is == 32 bits, turn it into a number of shuffles.
3955   SmallVector<SDValue, 8> V;
3956   V.resize(NumElems);
3957   if (NumElems == 4 && NumZero > 0) {
3958     for (unsigned i = 0; i < 4; ++i) {
3959       bool isZero = !(NonZeros & (1 << i));
3960       if (isZero)
3961         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3962       else
3963         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3964     }
3965
3966     for (unsigned i = 0; i < 2; ++i) {
3967       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3968         default: break;
3969         case 0:
3970           V[i] = V[i*2];  // Must be a zero vector.
3971           break;
3972         case 1:
3973           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3974           break;
3975         case 2:
3976           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3977           break;
3978         case 3:
3979           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3980           break;
3981       }
3982     }
3983
3984     SmallVector<int, 8> MaskVec;
3985     bool Reverse = (NonZeros & 0x3) == 2;
3986     for (unsigned i = 0; i < 2; ++i)
3987       MaskVec.push_back(Reverse ? 1-i : i);
3988     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3989     for (unsigned i = 0; i < 2; ++i)
3990       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3991     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3992   }
3993
3994   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3995     // Check for a build vector of consecutive loads.
3996     for (unsigned i = 0; i < NumElems; ++i)
3997       V[i] = Op.getOperand(i);
3998     
3999     // Check for elements which are consecutive loads.
4000     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4001     if (LD.getNode())
4002       return LD;
4003     
4004     // For SSE 4.1, use inserts into undef.  
4005     if (getSubtarget()->hasSSE41()) {
4006       V[0] = DAG.getUNDEF(VT);
4007       for (unsigned i = 0; i < NumElems; ++i)
4008         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4009           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
4010                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4011       return V[0];
4012     }
4013     
4014     // Otherwise, expand into a number of unpckl*
4015     // e.g. for v4f32
4016     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4017     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4018     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4019     for (unsigned i = 0; i < NumElems; ++i)
4020       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4021     NumElems >>= 1;
4022     while (NumElems != 0) {
4023       for (unsigned i = 0; i < NumElems; ++i)
4024         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4025       NumElems >>= 1;
4026     }
4027     return V[0];
4028   }
4029   return SDValue();
4030 }
4031
4032 SDValue
4033 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4034   // We support concatenate two MMX registers and place them in a MMX
4035   // register.  This is better than doing a stack convert.
4036   DebugLoc dl = Op.getDebugLoc();
4037   EVT ResVT = Op.getValueType();
4038   assert(Op.getNumOperands() == 2);
4039   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4040          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4041   int Mask[2];
4042   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4043   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4044   InVec = Op.getOperand(1);
4045   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4046     unsigned NumElts = ResVT.getVectorNumElements();
4047     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4048     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4049                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4050   } else {
4051     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4052     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4053     Mask[0] = 0; Mask[1] = 2;
4054     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4055   }
4056   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4057 }
4058
4059 // v8i16 shuffles - Prefer shuffles in the following order:
4060 // 1. [all]   pshuflw, pshufhw, optional move
4061 // 2. [ssse3] 1 x pshufb
4062 // 3. [ssse3] 2 x pshufb + 1 x por
4063 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4064 static
4065 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4066                                  SelectionDAG &DAG,
4067                                  const X86TargetLowering &TLI) {
4068   SDValue V1 = SVOp->getOperand(0);
4069   SDValue V2 = SVOp->getOperand(1);
4070   DebugLoc dl = SVOp->getDebugLoc();
4071   SmallVector<int, 8> MaskVals;
4072
4073   // Determine if more than 1 of the words in each of the low and high quadwords
4074   // of the result come from the same quadword of one of the two inputs.  Undef
4075   // mask values count as coming from any quadword, for better codegen.
4076   SmallVector<unsigned, 4> LoQuad(4);
4077   SmallVector<unsigned, 4> HiQuad(4);
4078   BitVector InputQuads(4);
4079   for (unsigned i = 0; i < 8; ++i) {
4080     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4081     int EltIdx = SVOp->getMaskElt(i);
4082     MaskVals.push_back(EltIdx);
4083     if (EltIdx < 0) {
4084       ++Quad[0];
4085       ++Quad[1];
4086       ++Quad[2];
4087       ++Quad[3];
4088       continue;
4089     }
4090     ++Quad[EltIdx / 4];
4091     InputQuads.set(EltIdx / 4);
4092   }
4093
4094   int BestLoQuad = -1;
4095   unsigned MaxQuad = 1;
4096   for (unsigned i = 0; i < 4; ++i) {
4097     if (LoQuad[i] > MaxQuad) {
4098       BestLoQuad = i;
4099       MaxQuad = LoQuad[i];
4100     }
4101   }
4102
4103   int BestHiQuad = -1;
4104   MaxQuad = 1;
4105   for (unsigned i = 0; i < 4; ++i) {
4106     if (HiQuad[i] > MaxQuad) {
4107       BestHiQuad = i;
4108       MaxQuad = HiQuad[i];
4109     }
4110   }
4111
4112   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4113   // of the two input vectors, shuffle them into one input vector so only a
4114   // single pshufb instruction is necessary. If There are more than 2 input
4115   // quads, disable the next transformation since it does not help SSSE3.
4116   bool V1Used = InputQuads[0] || InputQuads[1];
4117   bool V2Used = InputQuads[2] || InputQuads[3];
4118   if (TLI.getSubtarget()->hasSSSE3()) {
4119     if (InputQuads.count() == 2 && V1Used && V2Used) {
4120       BestLoQuad = InputQuads.find_first();
4121       BestHiQuad = InputQuads.find_next(BestLoQuad);
4122     }
4123     if (InputQuads.count() > 2) {
4124       BestLoQuad = -1;
4125       BestHiQuad = -1;
4126     }
4127   }
4128
4129   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4130   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4131   // words from all 4 input quadwords.
4132   SDValue NewV;
4133   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4134     SmallVector<int, 8> MaskV;
4135     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4136     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4137     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4138                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4139                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4140     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4141
4142     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4143     // source words for the shuffle, to aid later transformations.
4144     bool AllWordsInNewV = true;
4145     bool InOrder[2] = { true, true };
4146     for (unsigned i = 0; i != 8; ++i) {
4147       int idx = MaskVals[i];
4148       if (idx != (int)i)
4149         InOrder[i/4] = false;
4150       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4151         continue;
4152       AllWordsInNewV = false;
4153       break;
4154     }
4155
4156     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4157     if (AllWordsInNewV) {
4158       for (int i = 0; i != 8; ++i) {
4159         int idx = MaskVals[i];
4160         if (idx < 0)
4161           continue;
4162         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4163         if ((idx != i) && idx < 4)
4164           pshufhw = false;
4165         if ((idx != i) && idx > 3)
4166           pshuflw = false;
4167       }
4168       V1 = NewV;
4169       V2Used = false;
4170       BestLoQuad = 0;
4171       BestHiQuad = 1;
4172     }
4173
4174     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4175     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4176     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4177       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4178                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4179     }
4180   }
4181
4182   // If we have SSSE3, and all words of the result are from 1 input vector,
4183   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4184   // is present, fall back to case 4.
4185   if (TLI.getSubtarget()->hasSSSE3()) {
4186     SmallVector<SDValue,16> pshufbMask;
4187
4188     // If we have elements from both input vectors, set the high bit of the
4189     // shuffle mask element to zero out elements that come from V2 in the V1
4190     // mask, and elements that come from V1 in the V2 mask, so that the two
4191     // results can be OR'd together.
4192     bool TwoInputs = V1Used && V2Used;
4193     for (unsigned i = 0; i != 8; ++i) {
4194       int EltIdx = MaskVals[i] * 2;
4195       if (TwoInputs && (EltIdx >= 16)) {
4196         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4197         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4198         continue;
4199       }
4200       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4201       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4202     }
4203     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4204     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4205                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4206                                  MVT::v16i8, &pshufbMask[0], 16));
4207     if (!TwoInputs)
4208       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4209
4210     // Calculate the shuffle mask for the second input, shuffle it, and
4211     // OR it with the first shuffled input.
4212     pshufbMask.clear();
4213     for (unsigned i = 0; i != 8; ++i) {
4214       int EltIdx = MaskVals[i] * 2;
4215       if (EltIdx < 16) {
4216         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4217         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4218         continue;
4219       }
4220       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4221       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4222     }
4223     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4224     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4225                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4226                                  MVT::v16i8, &pshufbMask[0], 16));
4227     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4228     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4229   }
4230
4231   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4232   // and update MaskVals with new element order.
4233   BitVector InOrder(8);
4234   if (BestLoQuad >= 0) {
4235     SmallVector<int, 8> MaskV;
4236     for (int i = 0; i != 4; ++i) {
4237       int idx = MaskVals[i];
4238       if (idx < 0) {
4239         MaskV.push_back(-1);
4240         InOrder.set(i);
4241       } else if ((idx / 4) == BestLoQuad) {
4242         MaskV.push_back(idx & 3);
4243         InOrder.set(i);
4244       } else {
4245         MaskV.push_back(-1);
4246       }
4247     }
4248     for (unsigned i = 4; i != 8; ++i)
4249       MaskV.push_back(i);
4250     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4251                                 &MaskV[0]);
4252   }
4253
4254   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4255   // and update MaskVals with the new element order.
4256   if (BestHiQuad >= 0) {
4257     SmallVector<int, 8> MaskV;
4258     for (unsigned i = 0; i != 4; ++i)
4259       MaskV.push_back(i);
4260     for (unsigned i = 4; i != 8; ++i) {
4261       int idx = MaskVals[i];
4262       if (idx < 0) {
4263         MaskV.push_back(-1);
4264         InOrder.set(i);
4265       } else if ((idx / 4) == BestHiQuad) {
4266         MaskV.push_back((idx & 3) + 4);
4267         InOrder.set(i);
4268       } else {
4269         MaskV.push_back(-1);
4270       }
4271     }
4272     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4273                                 &MaskV[0]);
4274   }
4275
4276   // In case BestHi & BestLo were both -1, which means each quadword has a word
4277   // from each of the four input quadwords, calculate the InOrder bitvector now
4278   // before falling through to the insert/extract cleanup.
4279   if (BestLoQuad == -1 && BestHiQuad == -1) {
4280     NewV = V1;
4281     for (int i = 0; i != 8; ++i)
4282       if (MaskVals[i] < 0 || MaskVals[i] == i)
4283         InOrder.set(i);
4284   }
4285
4286   // The other elements are put in the right place using pextrw and pinsrw.
4287   for (unsigned i = 0; i != 8; ++i) {
4288     if (InOrder[i])
4289       continue;
4290     int EltIdx = MaskVals[i];
4291     if (EltIdx < 0)
4292       continue;
4293     SDValue ExtOp = (EltIdx < 8)
4294     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4295                   DAG.getIntPtrConstant(EltIdx))
4296     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4297                   DAG.getIntPtrConstant(EltIdx - 8));
4298     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4299                        DAG.getIntPtrConstant(i));
4300   }
4301   return NewV;
4302 }
4303
4304 // v16i8 shuffles - Prefer shuffles in the following order:
4305 // 1. [ssse3] 1 x pshufb
4306 // 2. [ssse3] 2 x pshufb + 1 x por
4307 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4308 static
4309 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4310                                  SelectionDAG &DAG,
4311                                  const X86TargetLowering &TLI) {
4312   SDValue V1 = SVOp->getOperand(0);
4313   SDValue V2 = SVOp->getOperand(1);
4314   DebugLoc dl = SVOp->getDebugLoc();
4315   SmallVector<int, 16> MaskVals;
4316   SVOp->getMask(MaskVals);
4317
4318   // If we have SSSE3, case 1 is generated when all result bytes come from
4319   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4320   // present, fall back to case 3.
4321   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4322   bool V1Only = true;
4323   bool V2Only = true;
4324   for (unsigned i = 0; i < 16; ++i) {
4325     int EltIdx = MaskVals[i];
4326     if (EltIdx < 0)
4327       continue;
4328     if (EltIdx < 16)
4329       V2Only = false;
4330     else
4331       V1Only = false;
4332   }
4333
4334   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4335   if (TLI.getSubtarget()->hasSSSE3()) {
4336     SmallVector<SDValue,16> pshufbMask;
4337
4338     // If all result elements are from one input vector, then only translate
4339     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4340     //
4341     // Otherwise, we have elements from both input vectors, and must zero out
4342     // elements that come from V2 in the first mask, and V1 in the second mask
4343     // so that we can OR them together.
4344     bool TwoInputs = !(V1Only || V2Only);
4345     for (unsigned i = 0; i != 16; ++i) {
4346       int EltIdx = MaskVals[i];
4347       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4348         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4349         continue;
4350       }
4351       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4352     }
4353     // If all the elements are from V2, assign it to V1 and return after
4354     // building the first pshufb.
4355     if (V2Only)
4356       V1 = V2;
4357     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4358                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4359                                  MVT::v16i8, &pshufbMask[0], 16));
4360     if (!TwoInputs)
4361       return V1;
4362
4363     // Calculate the shuffle mask for the second input, shuffle it, and
4364     // OR it with the first shuffled input.
4365     pshufbMask.clear();
4366     for (unsigned i = 0; i != 16; ++i) {
4367       int EltIdx = MaskVals[i];
4368       if (EltIdx < 16) {
4369         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4370         continue;
4371       }
4372       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4373     }
4374     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4375                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4376                                  MVT::v16i8, &pshufbMask[0], 16));
4377     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4378   }
4379
4380   // No SSSE3 - Calculate in place words and then fix all out of place words
4381   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4382   // the 16 different words that comprise the two doublequadword input vectors.
4383   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4384   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4385   SDValue NewV = V2Only ? V2 : V1;
4386   for (int i = 0; i != 8; ++i) {
4387     int Elt0 = MaskVals[i*2];
4388     int Elt1 = MaskVals[i*2+1];
4389
4390     // This word of the result is all undef, skip it.
4391     if (Elt0 < 0 && Elt1 < 0)
4392       continue;
4393
4394     // This word of the result is already in the correct place, skip it.
4395     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4396       continue;
4397     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4398       continue;
4399
4400     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4401     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4402     SDValue InsElt;
4403
4404     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4405     // using a single extract together, load it and store it.
4406     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4407       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4408                            DAG.getIntPtrConstant(Elt1 / 2));
4409       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4410                         DAG.getIntPtrConstant(i));
4411       continue;
4412     }
4413
4414     // If Elt1 is defined, extract it from the appropriate source.  If the
4415     // source byte is not also odd, shift the extracted word left 8 bits
4416     // otherwise clear the bottom 8 bits if we need to do an or.
4417     if (Elt1 >= 0) {
4418       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4419                            DAG.getIntPtrConstant(Elt1 / 2));
4420       if ((Elt1 & 1) == 0)
4421         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4422                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4423       else if (Elt0 >= 0)
4424         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4425                              DAG.getConstant(0xFF00, MVT::i16));
4426     }
4427     // If Elt0 is defined, extract it from the appropriate source.  If the
4428     // source byte is not also even, shift the extracted word right 8 bits. If
4429     // Elt1 was also defined, OR the extracted values together before
4430     // inserting them in the result.
4431     if (Elt0 >= 0) {
4432       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4433                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4434       if ((Elt0 & 1) != 0)
4435         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4436                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4437       else if (Elt1 >= 0)
4438         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4439                              DAG.getConstant(0x00FF, MVT::i16));
4440       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4441                          : InsElt0;
4442     }
4443     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4444                        DAG.getIntPtrConstant(i));
4445   }
4446   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4447 }
4448
4449 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4450 /// ones, or rewriting v4i32 / v2i32 as 2 wide ones if possible. This can be
4451 /// done when every pair / quad of shuffle mask elements point to elements in
4452 /// the right sequence. e.g.
4453 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4454 static
4455 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4456                                  SelectionDAG &DAG,
4457                                  const TargetLowering &TLI, DebugLoc dl) {
4458   EVT VT = SVOp->getValueType(0);
4459   SDValue V1 = SVOp->getOperand(0);
4460   SDValue V2 = SVOp->getOperand(1);
4461   unsigned NumElems = VT.getVectorNumElements();
4462   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4463   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4464   EVT NewVT = MaskVT;
4465   switch (VT.getSimpleVT().SimpleTy) {
4466   default: assert(false && "Unexpected!");
4467   case MVT::v4f32: NewVT = MVT::v2f64; break;
4468   case MVT::v4i32: NewVT = MVT::v2i64; break;
4469   case MVT::v8i16: NewVT = MVT::v4i32; break;
4470   case MVT::v16i8: NewVT = MVT::v4i32; break;
4471   }
4472
4473   if (NewWidth == 2) {
4474     if (VT.isInteger())
4475       NewVT = MVT::v2i64;
4476     else
4477       NewVT = MVT::v2f64;
4478   }
4479   int Scale = NumElems / NewWidth;
4480   SmallVector<int, 8> MaskVec;
4481   for (unsigned i = 0; i < NumElems; i += Scale) {
4482     int StartIdx = -1;
4483     for (int j = 0; j < Scale; ++j) {
4484       int EltIdx = SVOp->getMaskElt(i+j);
4485       if (EltIdx < 0)
4486         continue;
4487       if (StartIdx == -1)
4488         StartIdx = EltIdx - (EltIdx % Scale);
4489       if (EltIdx != StartIdx + j)
4490         return SDValue();
4491     }
4492     if (StartIdx == -1)
4493       MaskVec.push_back(-1);
4494     else
4495       MaskVec.push_back(StartIdx / Scale);
4496   }
4497
4498   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4499   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4500   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4501 }
4502
4503 /// getVZextMovL - Return a zero-extending vector move low node.
4504 ///
4505 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4506                             SDValue SrcOp, SelectionDAG &DAG,
4507                             const X86Subtarget *Subtarget, DebugLoc dl) {
4508   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4509     LoadSDNode *LD = NULL;
4510     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4511       LD = dyn_cast<LoadSDNode>(SrcOp);
4512     if (!LD) {
4513       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4514       // instead.
4515       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4516       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4517           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4518           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4519           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4520         // PR2108
4521         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4522         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4523                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4524                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4525                                                    OpVT,
4526                                                    SrcOp.getOperand(0)
4527                                                           .getOperand(0))));
4528       }
4529     }
4530   }
4531
4532   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4533                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4534                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4535                                              OpVT, SrcOp)));
4536 }
4537
4538 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4539 /// shuffles.
4540 static SDValue
4541 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4542   SDValue V1 = SVOp->getOperand(0);
4543   SDValue V2 = SVOp->getOperand(1);
4544   DebugLoc dl = SVOp->getDebugLoc();
4545   EVT VT = SVOp->getValueType(0);
4546
4547   SmallVector<std::pair<int, int>, 8> Locs;
4548   Locs.resize(4);
4549   SmallVector<int, 8> Mask1(4U, -1);
4550   SmallVector<int, 8> PermMask;
4551   SVOp->getMask(PermMask);
4552
4553   unsigned NumHi = 0;
4554   unsigned NumLo = 0;
4555   for (unsigned i = 0; i != 4; ++i) {
4556     int Idx = PermMask[i];
4557     if (Idx < 0) {
4558       Locs[i] = std::make_pair(-1, -1);
4559     } else {
4560       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4561       if (Idx < 4) {
4562         Locs[i] = std::make_pair(0, NumLo);
4563         Mask1[NumLo] = Idx;
4564         NumLo++;
4565       } else {
4566         Locs[i] = std::make_pair(1, NumHi);
4567         if (2+NumHi < 4)
4568           Mask1[2+NumHi] = Idx;
4569         NumHi++;
4570       }
4571     }
4572   }
4573
4574   if (NumLo <= 2 && NumHi <= 2) {
4575     // If no more than two elements come from either vector. This can be
4576     // implemented with two shuffles. First shuffle gather the elements.
4577     // The second shuffle, which takes the first shuffle as both of its
4578     // vector operands, put the elements into the right order.
4579     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4580
4581     SmallVector<int, 8> Mask2(4U, -1);
4582
4583     for (unsigned i = 0; i != 4; ++i) {
4584       if (Locs[i].first == -1)
4585         continue;
4586       else {
4587         unsigned Idx = (i < 2) ? 0 : 4;
4588         Idx += Locs[i].first * 2 + Locs[i].second;
4589         Mask2[i] = Idx;
4590       }
4591     }
4592
4593     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4594   } else if (NumLo == 3 || NumHi == 3) {
4595     // Otherwise, we must have three elements from one vector, call it X, and
4596     // one element from the other, call it Y.  First, use a shufps to build an
4597     // intermediate vector with the one element from Y and the element from X
4598     // that will be in the same half in the final destination (the indexes don't
4599     // matter). Then, use a shufps to build the final vector, taking the half
4600     // containing the element from Y from the intermediate, and the other half
4601     // from X.
4602     if (NumHi == 3) {
4603       // Normalize it so the 3 elements come from V1.
4604       CommuteVectorShuffleMask(PermMask, VT);
4605       std::swap(V1, V2);
4606     }
4607
4608     // Find the element from V2.
4609     unsigned HiIndex;
4610     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4611       int Val = PermMask[HiIndex];
4612       if (Val < 0)
4613         continue;
4614       if (Val >= 4)
4615         break;
4616     }
4617
4618     Mask1[0] = PermMask[HiIndex];
4619     Mask1[1] = -1;
4620     Mask1[2] = PermMask[HiIndex^1];
4621     Mask1[3] = -1;
4622     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4623
4624     if (HiIndex >= 2) {
4625       Mask1[0] = PermMask[0];
4626       Mask1[1] = PermMask[1];
4627       Mask1[2] = HiIndex & 1 ? 6 : 4;
4628       Mask1[3] = HiIndex & 1 ? 4 : 6;
4629       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4630     } else {
4631       Mask1[0] = HiIndex & 1 ? 2 : 0;
4632       Mask1[1] = HiIndex & 1 ? 0 : 2;
4633       Mask1[2] = PermMask[2];
4634       Mask1[3] = PermMask[3];
4635       if (Mask1[2] >= 0)
4636         Mask1[2] += 4;
4637       if (Mask1[3] >= 0)
4638         Mask1[3] += 4;
4639       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4640     }
4641   }
4642
4643   // Break it into (shuffle shuffle_hi, shuffle_lo).
4644   Locs.clear();
4645   SmallVector<int,8> LoMask(4U, -1);
4646   SmallVector<int,8> HiMask(4U, -1);
4647
4648   SmallVector<int,8> *MaskPtr = &LoMask;
4649   unsigned MaskIdx = 0;
4650   unsigned LoIdx = 0;
4651   unsigned HiIdx = 2;
4652   for (unsigned i = 0; i != 4; ++i) {
4653     if (i == 2) {
4654       MaskPtr = &HiMask;
4655       MaskIdx = 1;
4656       LoIdx = 0;
4657       HiIdx = 2;
4658     }
4659     int Idx = PermMask[i];
4660     if (Idx < 0) {
4661       Locs[i] = std::make_pair(-1, -1);
4662     } else if (Idx < 4) {
4663       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4664       (*MaskPtr)[LoIdx] = Idx;
4665       LoIdx++;
4666     } else {
4667       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4668       (*MaskPtr)[HiIdx] = Idx;
4669       HiIdx++;
4670     }
4671   }
4672
4673   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4674   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4675   SmallVector<int, 8> MaskOps;
4676   for (unsigned i = 0; i != 4; ++i) {
4677     if (Locs[i].first == -1) {
4678       MaskOps.push_back(-1);
4679     } else {
4680       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4681       MaskOps.push_back(Idx);
4682     }
4683   }
4684   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4685 }
4686
4687 SDValue
4688 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4689   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4690   SDValue V1 = Op.getOperand(0);
4691   SDValue V2 = Op.getOperand(1);
4692   EVT VT = Op.getValueType();
4693   DebugLoc dl = Op.getDebugLoc();
4694   unsigned NumElems = VT.getVectorNumElements();
4695   bool isMMX = VT.getSizeInBits() == 64;
4696   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4697   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4698   bool V1IsSplat = false;
4699   bool V2IsSplat = false;
4700
4701   if (isZeroShuffle(SVOp))
4702     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4703
4704   // Promote splats to v4f32.
4705   if (SVOp->isSplat()) {
4706     if (isMMX || NumElems < 4)
4707       return Op;
4708     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4709   }
4710
4711   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4712   // do it!
4713   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4714     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4715     if (NewOp.getNode())
4716       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4717                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4718   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4719     // FIXME: Figure out a cleaner way to do this.
4720     // Try to make use of movq to zero out the top part.
4721     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4722       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4723       if (NewOp.getNode()) {
4724         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4725           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4726                               DAG, Subtarget, dl);
4727       }
4728     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4729       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4730       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4731         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4732                             DAG, Subtarget, dl);
4733     }
4734   }
4735
4736   if (X86::isPSHUFDMask(SVOp))
4737     return Op;
4738
4739   // Check if this can be converted into a logical shift.
4740   bool isLeft = false;
4741   unsigned ShAmt = 0;
4742   SDValue ShVal;
4743   bool isShift = getSubtarget()->hasSSE2() &&
4744     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4745   if (isShift && ShVal.hasOneUse()) {
4746     // If the shifted value has multiple uses, it may be cheaper to use
4747     // v_set0 + movlhps or movhlps, etc.
4748     EVT EltVT = VT.getVectorElementType();
4749     ShAmt *= EltVT.getSizeInBits();
4750     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4751   }
4752
4753   if (X86::isMOVLMask(SVOp)) {
4754     if (V1IsUndef)
4755       return V2;
4756     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4757       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4758     if (!isMMX)
4759       return Op;
4760   }
4761
4762   // FIXME: fold these into legal mask.
4763   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4764                  X86::isMOVSLDUPMask(SVOp) ||
4765                  X86::isMOVHLPSMask(SVOp) ||
4766                  X86::isMOVLHPSMask(SVOp) ||
4767                  X86::isMOVLPMask(SVOp)))
4768     return Op;
4769
4770   if (ShouldXformToMOVHLPS(SVOp) ||
4771       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4772     return CommuteVectorShuffle(SVOp, DAG);
4773
4774   if (isShift) {
4775     // No better options. Use a vshl / vsrl.
4776     EVT EltVT = VT.getVectorElementType();
4777     ShAmt *= EltVT.getSizeInBits();
4778     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4779   }
4780
4781   bool Commuted = false;
4782   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4783   // 1,1,1,1 -> v8i16 though.
4784   V1IsSplat = isSplatVector(V1.getNode());
4785   V2IsSplat = isSplatVector(V2.getNode());
4786
4787   // Canonicalize the splat or undef, if present, to be on the RHS.
4788   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4789     Op = CommuteVectorShuffle(SVOp, DAG);
4790     SVOp = cast<ShuffleVectorSDNode>(Op);
4791     V1 = SVOp->getOperand(0);
4792     V2 = SVOp->getOperand(1);
4793     std::swap(V1IsSplat, V2IsSplat);
4794     std::swap(V1IsUndef, V2IsUndef);
4795     Commuted = true;
4796   }
4797
4798   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4799     // Shuffling low element of v1 into undef, just return v1.
4800     if (V2IsUndef)
4801       return V1;
4802     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4803     // the instruction selector will not match, so get a canonical MOVL with
4804     // swapped operands to undo the commute.
4805     return getMOVL(DAG, dl, VT, V2, V1);
4806   }
4807
4808   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4809       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4810       X86::isUNPCKLMask(SVOp) ||
4811       X86::isUNPCKHMask(SVOp))
4812     return Op;
4813
4814   if (V2IsSplat) {
4815     // Normalize mask so all entries that point to V2 points to its first
4816     // element then try to match unpck{h|l} again. If match, return a
4817     // new vector_shuffle with the corrected mask.
4818     SDValue NewMask = NormalizeMask(SVOp, DAG);
4819     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4820     if (NSVOp != SVOp) {
4821       if (X86::isUNPCKLMask(NSVOp, true)) {
4822         return NewMask;
4823       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4824         return NewMask;
4825       }
4826     }
4827   }
4828
4829   if (Commuted) {
4830     // Commute is back and try unpck* again.
4831     // FIXME: this seems wrong.
4832     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4833     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4834     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4835         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4836         X86::isUNPCKLMask(NewSVOp) ||
4837         X86::isUNPCKHMask(NewSVOp))
4838       return NewOp;
4839   }
4840
4841   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4842
4843   // Normalize the node to match x86 shuffle ops if needed
4844   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4845     return CommuteVectorShuffle(SVOp, DAG);
4846
4847   // Check for legal shuffle and return?
4848   SmallVector<int, 16> PermMask;
4849   SVOp->getMask(PermMask);
4850   if (isShuffleMaskLegal(PermMask, VT))
4851     return Op;
4852
4853   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4854   if (VT == MVT::v8i16) {
4855     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4856     if (NewOp.getNode())
4857       return NewOp;
4858   }
4859
4860   if (VT == MVT::v16i8) {
4861     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4862     if (NewOp.getNode())
4863       return NewOp;
4864   }
4865
4866   // Handle all 4 wide cases with a number of shuffles except for MMX.
4867   if (NumElems == 4 && !isMMX)
4868     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4869
4870   return SDValue();
4871 }
4872
4873 SDValue
4874 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4875                                                 SelectionDAG &DAG) const {
4876   EVT VT = Op.getValueType();
4877   DebugLoc dl = Op.getDebugLoc();
4878   if (VT.getSizeInBits() == 8) {
4879     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4880                                     Op.getOperand(0), Op.getOperand(1));
4881     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4882                                     DAG.getValueType(VT));
4883     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4884   } else if (VT.getSizeInBits() == 16) {
4885     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4886     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4887     if (Idx == 0)
4888       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4889                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4890                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4891                                                  MVT::v4i32,
4892                                                  Op.getOperand(0)),
4893                                      Op.getOperand(1)));
4894     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4895                                     Op.getOperand(0), Op.getOperand(1));
4896     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4897                                     DAG.getValueType(VT));
4898     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4899   } else if (VT == MVT::f32) {
4900     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4901     // the result back to FR32 register. It's only worth matching if the
4902     // result has a single use which is a store or a bitcast to i32.  And in
4903     // the case of a store, it's not worth it if the index is a constant 0,
4904     // because a MOVSSmr can be used instead, which is smaller and faster.
4905     if (!Op.hasOneUse())
4906       return SDValue();
4907     SDNode *User = *Op.getNode()->use_begin();
4908     if ((User->getOpcode() != ISD::STORE ||
4909          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4910           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4911         (User->getOpcode() != ISD::BIT_CONVERT ||
4912          User->getValueType(0) != MVT::i32))
4913       return SDValue();
4914     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4915                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4916                                               Op.getOperand(0)),
4917                                               Op.getOperand(1));
4918     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4919   } else if (VT == MVT::i32) {
4920     // ExtractPS works with constant index.
4921     if (isa<ConstantSDNode>(Op.getOperand(1)))
4922       return Op;
4923   }
4924   return SDValue();
4925 }
4926
4927
4928 SDValue
4929 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4930                                            SelectionDAG &DAG) const {
4931   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4932     return SDValue();
4933
4934   if (Subtarget->hasSSE41()) {
4935     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4936     if (Res.getNode())
4937       return Res;
4938   }
4939
4940   EVT VT = Op.getValueType();
4941   DebugLoc dl = Op.getDebugLoc();
4942   // TODO: handle v16i8.
4943   if (VT.getSizeInBits() == 16) {
4944     SDValue Vec = Op.getOperand(0);
4945     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4946     if (Idx == 0)
4947       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4948                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4949                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4950                                                  MVT::v4i32, Vec),
4951                                      Op.getOperand(1)));
4952     // Transform it so it match pextrw which produces a 32-bit result.
4953     EVT EltVT = MVT::i32;
4954     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4955                                     Op.getOperand(0), Op.getOperand(1));
4956     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4957                                     DAG.getValueType(VT));
4958     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4959   } else if (VT.getSizeInBits() == 32) {
4960     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4961     if (Idx == 0)
4962       return Op;
4963
4964     // SHUFPS the element to the lowest double word, then movss.
4965     int Mask[4] = { Idx, -1, -1, -1 };
4966     EVT VVT = Op.getOperand(0).getValueType();
4967     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4968                                        DAG.getUNDEF(VVT), Mask);
4969     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4970                        DAG.getIntPtrConstant(0));
4971   } else if (VT.getSizeInBits() == 64) {
4972     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4973     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4974     //        to match extract_elt for f64.
4975     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4976     if (Idx == 0)
4977       return Op;
4978
4979     // UNPCKHPD the element to the lowest double word, then movsd.
4980     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4981     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4982     int Mask[2] = { 1, -1 };
4983     EVT VVT = Op.getOperand(0).getValueType();
4984     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4985                                        DAG.getUNDEF(VVT), Mask);
4986     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4987                        DAG.getIntPtrConstant(0));
4988   }
4989
4990   return SDValue();
4991 }
4992
4993 SDValue
4994 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4995                                                SelectionDAG &DAG) const {
4996   EVT VT = Op.getValueType();
4997   EVT EltVT = VT.getVectorElementType();
4998   DebugLoc dl = Op.getDebugLoc();
4999
5000   SDValue N0 = Op.getOperand(0);
5001   SDValue N1 = Op.getOperand(1);
5002   SDValue N2 = Op.getOperand(2);
5003
5004   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5005       isa<ConstantSDNode>(N2)) {
5006     unsigned Opc;
5007     if (VT == MVT::v8i16)
5008       Opc = X86ISD::PINSRW;
5009     else if (VT == MVT::v4i16)
5010       Opc = X86ISD::MMX_PINSRW;
5011     else if (VT == MVT::v16i8)
5012       Opc = X86ISD::PINSRB;
5013     else
5014       Opc = X86ISD::PINSRB;
5015
5016     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5017     // argument.
5018     if (N1.getValueType() != MVT::i32)
5019       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5020     if (N2.getValueType() != MVT::i32)
5021       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5022     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5023   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5024     // Bits [7:6] of the constant are the source select.  This will always be
5025     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5026     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5027     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5028     // Bits [5:4] of the constant are the destination select.  This is the
5029     //  value of the incoming immediate.
5030     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5031     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5032     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5033     // Create this as a scalar to vector..
5034     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5035     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5036   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5037     // PINSR* works with constant index.
5038     return Op;
5039   }
5040   return SDValue();
5041 }
5042
5043 SDValue
5044 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5045   EVT VT = Op.getValueType();
5046   EVT EltVT = VT.getVectorElementType();
5047
5048   if (Subtarget->hasSSE41())
5049     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5050
5051   if (EltVT == MVT::i8)
5052     return SDValue();
5053
5054   DebugLoc dl = Op.getDebugLoc();
5055   SDValue N0 = Op.getOperand(0);
5056   SDValue N1 = Op.getOperand(1);
5057   SDValue N2 = Op.getOperand(2);
5058
5059   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5060     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5061     // as its second argument.
5062     if (N1.getValueType() != MVT::i32)
5063       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5064     if (N2.getValueType() != MVT::i32)
5065       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5066     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5067                        dl, VT, N0, N1, N2);
5068   }
5069   return SDValue();
5070 }
5071
5072 SDValue
5073 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5074   DebugLoc dl = Op.getDebugLoc();
5075   
5076   if (Op.getValueType() == MVT::v1i64 &&
5077       Op.getOperand(0).getValueType() == MVT::i64)
5078     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5079
5080   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5081   EVT VT = MVT::v2i32;
5082   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5083   default: break;
5084   case MVT::v16i8:
5085   case MVT::v8i16:
5086     VT = MVT::v4i32;
5087     break;
5088   }
5089   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5090                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5091 }
5092
5093 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5094 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5095 // one of the above mentioned nodes. It has to be wrapped because otherwise
5096 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5097 // be used to form addressing mode. These wrapped nodes will be selected
5098 // into MOV32ri.
5099 SDValue
5100 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5101   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5102
5103   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5104   // global base reg.
5105   unsigned char OpFlag = 0;
5106   unsigned WrapperKind = X86ISD::Wrapper;
5107   CodeModel::Model M = getTargetMachine().getCodeModel();
5108
5109   if (Subtarget->isPICStyleRIPRel() &&
5110       (M == CodeModel::Small || M == CodeModel::Kernel))
5111     WrapperKind = X86ISD::WrapperRIP;
5112   else if (Subtarget->isPICStyleGOT())
5113     OpFlag = X86II::MO_GOTOFF;
5114   else if (Subtarget->isPICStyleStubPIC())
5115     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5116
5117   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5118                                              CP->getAlignment(),
5119                                              CP->getOffset(), OpFlag);
5120   DebugLoc DL = CP->getDebugLoc();
5121   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5122   // With PIC, the address is actually $g + Offset.
5123   if (OpFlag) {
5124     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5125                          DAG.getNode(X86ISD::GlobalBaseReg,
5126                                      DebugLoc(), getPointerTy()),
5127                          Result);
5128   }
5129
5130   return Result;
5131 }
5132
5133 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5134   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5135
5136   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5137   // global base reg.
5138   unsigned char OpFlag = 0;
5139   unsigned WrapperKind = X86ISD::Wrapper;
5140   CodeModel::Model M = getTargetMachine().getCodeModel();
5141
5142   if (Subtarget->isPICStyleRIPRel() &&
5143       (M == CodeModel::Small || M == CodeModel::Kernel))
5144     WrapperKind = X86ISD::WrapperRIP;
5145   else if (Subtarget->isPICStyleGOT())
5146     OpFlag = X86II::MO_GOTOFF;
5147   else if (Subtarget->isPICStyleStubPIC())
5148     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5149
5150   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5151                                           OpFlag);
5152   DebugLoc DL = JT->getDebugLoc();
5153   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5154
5155   // With PIC, the address is actually $g + Offset.
5156   if (OpFlag) {
5157     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5158                          DAG.getNode(X86ISD::GlobalBaseReg,
5159                                      DebugLoc(), getPointerTy()),
5160                          Result);
5161   }
5162
5163   return Result;
5164 }
5165
5166 SDValue
5167 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5168   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5169
5170   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5171   // global base reg.
5172   unsigned char OpFlag = 0;
5173   unsigned WrapperKind = X86ISD::Wrapper;
5174   CodeModel::Model M = getTargetMachine().getCodeModel();
5175
5176   if (Subtarget->isPICStyleRIPRel() &&
5177       (M == CodeModel::Small || M == CodeModel::Kernel))
5178     WrapperKind = X86ISD::WrapperRIP;
5179   else if (Subtarget->isPICStyleGOT())
5180     OpFlag = X86II::MO_GOTOFF;
5181   else if (Subtarget->isPICStyleStubPIC())
5182     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5183
5184   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5185
5186   DebugLoc DL = Op.getDebugLoc();
5187   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5188
5189
5190   // With PIC, the address is actually $g + Offset.
5191   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5192       !Subtarget->is64Bit()) {
5193     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5194                          DAG.getNode(X86ISD::GlobalBaseReg,
5195                                      DebugLoc(), getPointerTy()),
5196                          Result);
5197   }
5198
5199   return Result;
5200 }
5201
5202 SDValue
5203 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5204   // Create the TargetBlockAddressAddress node.
5205   unsigned char OpFlags =
5206     Subtarget->ClassifyBlockAddressReference();
5207   CodeModel::Model M = getTargetMachine().getCodeModel();
5208   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5209   DebugLoc dl = Op.getDebugLoc();
5210   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5211                                        /*isTarget=*/true, OpFlags);
5212
5213   if (Subtarget->isPICStyleRIPRel() &&
5214       (M == CodeModel::Small || M == CodeModel::Kernel))
5215     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5216   else
5217     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5218
5219   // With PIC, the address is actually $g + Offset.
5220   if (isGlobalRelativeToPICBase(OpFlags)) {
5221     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5222                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5223                          Result);
5224   }
5225
5226   return Result;
5227 }
5228
5229 SDValue
5230 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5231                                       int64_t Offset,
5232                                       SelectionDAG &DAG) const {
5233   // Create the TargetGlobalAddress node, folding in the constant
5234   // offset if it is legal.
5235   unsigned char OpFlags =
5236     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5237   CodeModel::Model M = getTargetMachine().getCodeModel();
5238   SDValue Result;
5239   if (OpFlags == X86II::MO_NO_FLAG &&
5240       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5241     // A direct static reference to a global.
5242     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5243     Offset = 0;
5244   } else {
5245     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5246   }
5247
5248   if (Subtarget->isPICStyleRIPRel() &&
5249       (M == CodeModel::Small || M == CodeModel::Kernel))
5250     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5251   else
5252     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5253
5254   // With PIC, the address is actually $g + Offset.
5255   if (isGlobalRelativeToPICBase(OpFlags)) {
5256     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5257                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5258                          Result);
5259   }
5260
5261   // For globals that require a load from a stub to get the address, emit the
5262   // load.
5263   if (isGlobalStubReference(OpFlags))
5264     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5265                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5266
5267   // If there was a non-zero offset that we didn't fold, create an explicit
5268   // addition for it.
5269   if (Offset != 0)
5270     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5271                          DAG.getConstant(Offset, getPointerTy()));
5272
5273   return Result;
5274 }
5275
5276 SDValue
5277 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5278   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5279   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5280   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5281 }
5282
5283 static SDValue
5284 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5285            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5286            unsigned char OperandFlags) {
5287   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5288   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5289   DebugLoc dl = GA->getDebugLoc();
5290   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
5291                                            GA->getValueType(0),
5292                                            GA->getOffset(),
5293                                            OperandFlags);
5294   if (InFlag) {
5295     SDValue Ops[] = { Chain,  TGA, *InFlag };
5296     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5297   } else {
5298     SDValue Ops[]  = { Chain, TGA };
5299     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5300   }
5301
5302   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5303   MFI->setAdjustsStack(true);
5304
5305   SDValue Flag = Chain.getValue(1);
5306   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5307 }
5308
5309 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5310 static SDValue
5311 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5312                                 const EVT PtrVT) {
5313   SDValue InFlag;
5314   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5315   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5316                                      DAG.getNode(X86ISD::GlobalBaseReg,
5317                                                  DebugLoc(), PtrVT), InFlag);
5318   InFlag = Chain.getValue(1);
5319
5320   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5321 }
5322
5323 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5324 static SDValue
5325 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5326                                 const EVT PtrVT) {
5327   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5328                     X86::RAX, X86II::MO_TLSGD);
5329 }
5330
5331 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5332 // "local exec" model.
5333 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5334                                    const EVT PtrVT, TLSModel::Model model,
5335                                    bool is64Bit) {
5336   DebugLoc dl = GA->getDebugLoc();
5337   // Get the Thread Pointer
5338   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5339                              DebugLoc(), PtrVT,
5340                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5341                                              MVT::i32));
5342
5343   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5344                                       NULL, 0, false, false, 0);
5345
5346   unsigned char OperandFlags = 0;
5347   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5348   // initialexec.
5349   unsigned WrapperKind = X86ISD::Wrapper;
5350   if (model == TLSModel::LocalExec) {
5351     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5352   } else if (is64Bit) {
5353     assert(model == TLSModel::InitialExec);
5354     OperandFlags = X86II::MO_GOTTPOFF;
5355     WrapperKind = X86ISD::WrapperRIP;
5356   } else {
5357     assert(model == TLSModel::InitialExec);
5358     OperandFlags = X86II::MO_INDNTPOFF;
5359   }
5360
5361   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5362   // exec)
5363   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 
5364                                            GA->getValueType(0),
5365                                            GA->getOffset(), OperandFlags);
5366   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5367
5368   if (model == TLSModel::InitialExec)
5369     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5370                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5371
5372   // The address of the thread local variable is the add of the thread
5373   // pointer with the offset of the variable.
5374   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5375 }
5376
5377 SDValue
5378 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5379   
5380   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5381   const GlobalValue *GV = GA->getGlobal();
5382
5383   if (Subtarget->isTargetELF()) {
5384     // TODO: implement the "local dynamic" model
5385     // TODO: implement the "initial exec"model for pic executables
5386     
5387     // If GV is an alias then use the aliasee for determining
5388     // thread-localness.
5389     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5390       GV = GA->resolveAliasedGlobal(false);
5391     
5392     TLSModel::Model model 
5393       = getTLSModel(GV, getTargetMachine().getRelocationModel());
5394     
5395     switch (model) {
5396       case TLSModel::GeneralDynamic:
5397       case TLSModel::LocalDynamic: // not implemented
5398         if (Subtarget->is64Bit())
5399           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5400         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5401         
5402       case TLSModel::InitialExec:
5403       case TLSModel::LocalExec:
5404         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5405                                    Subtarget->is64Bit());
5406     }
5407   } else if (Subtarget->isTargetDarwin()) {
5408     // Darwin only has one model of TLS.  Lower to that.
5409     unsigned char OpFlag = 0;
5410     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
5411                            X86ISD::WrapperRIP : X86ISD::Wrapper;
5412     
5413     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5414     // global base reg.
5415     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
5416                   !Subtarget->is64Bit();
5417     if (PIC32)
5418       OpFlag = X86II::MO_TLVP_PIC_BASE;
5419     else
5420       OpFlag = X86II::MO_TLVP;
5421     DebugLoc DL = Op.getDebugLoc();    
5422     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
5423                                                 getPointerTy(),
5424                                                 GA->getOffset(), OpFlag);
5425     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5426   
5427     // With PIC32, the address is actually $g + Offset.
5428     if (PIC32)
5429       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5430                            DAG.getNode(X86ISD::GlobalBaseReg,
5431                                        DebugLoc(), getPointerTy()),
5432                            Offset);
5433     
5434     // Lowering the machine isd will make sure everything is in the right
5435     // location.
5436     SDValue Args[] = { Offset };
5437     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
5438     
5439     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
5440     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5441     MFI->setAdjustsStack(true);
5442
5443     // And our return value (tls address) is in the standard call return value
5444     // location.
5445     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
5446     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
5447   }
5448   
5449   assert(false &&
5450          "TLS not implemented for this target.");
5451
5452   llvm_unreachable("Unreachable");
5453   return SDValue();
5454 }
5455
5456
5457 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5458 /// take a 2 x i32 value to shift plus a shift amount.
5459 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5460   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5461   EVT VT = Op.getValueType();
5462   unsigned VTBits = VT.getSizeInBits();
5463   DebugLoc dl = Op.getDebugLoc();
5464   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5465   SDValue ShOpLo = Op.getOperand(0);
5466   SDValue ShOpHi = Op.getOperand(1);
5467   SDValue ShAmt  = Op.getOperand(2);
5468   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5469                                      DAG.getConstant(VTBits - 1, MVT::i8))
5470                        : DAG.getConstant(0, VT);
5471
5472   SDValue Tmp2, Tmp3;
5473   if (Op.getOpcode() == ISD::SHL_PARTS) {
5474     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5475     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5476   } else {
5477     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5478     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5479   }
5480
5481   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5482                                 DAG.getConstant(VTBits, MVT::i8));
5483   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5484                              AndNode, DAG.getConstant(0, MVT::i8));
5485
5486   SDValue Hi, Lo;
5487   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5488   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5489   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5490
5491   if (Op.getOpcode() == ISD::SHL_PARTS) {
5492     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5493     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5494   } else {
5495     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5496     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5497   }
5498
5499   SDValue Ops[2] = { Lo, Hi };
5500   return DAG.getMergeValues(Ops, 2, dl);
5501 }
5502
5503 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5504                                            SelectionDAG &DAG) const {
5505   EVT SrcVT = Op.getOperand(0).getValueType();
5506
5507   if (SrcVT.isVector()) {
5508     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5509       return Op;
5510     }
5511     return SDValue();
5512   }
5513
5514   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5515          "Unknown SINT_TO_FP to lower!");
5516
5517   // These are really Legal; return the operand so the caller accepts it as
5518   // Legal.
5519   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5520     return Op;
5521   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5522       Subtarget->is64Bit()) {
5523     return Op;
5524   }
5525
5526   DebugLoc dl = Op.getDebugLoc();
5527   unsigned Size = SrcVT.getSizeInBits()/8;
5528   MachineFunction &MF = DAG.getMachineFunction();
5529   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5530   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5531   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5532                                StackSlot,
5533                                PseudoSourceValue::getFixedStack(SSFI), 0,
5534                                false, false, 0);
5535   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5536 }
5537
5538 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5539                                      SDValue StackSlot, 
5540                                      SelectionDAG &DAG) const {
5541   // Build the FILD
5542   DebugLoc dl = Op.getDebugLoc();
5543   SDVTList Tys;
5544   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5545   if (useSSE)
5546     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5547   else
5548     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5549   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5550   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5551                                Tys, Ops, array_lengthof(Ops));
5552
5553   if (useSSE) {
5554     Chain = Result.getValue(1);
5555     SDValue InFlag = Result.getValue(2);
5556
5557     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5558     // shouldn't be necessary except that RFP cannot be live across
5559     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5560     MachineFunction &MF = DAG.getMachineFunction();
5561     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5562     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5563     Tys = DAG.getVTList(MVT::Other);
5564     SDValue Ops[] = {
5565       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5566     };
5567     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5568     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5569                          PseudoSourceValue::getFixedStack(SSFI), 0,
5570                          false, false, 0);
5571   }
5572
5573   return Result;
5574 }
5575
5576 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5577 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5578                                                SelectionDAG &DAG) const {
5579   // This algorithm is not obvious. Here it is in C code, more or less:
5580   /*
5581     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5582       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5583       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5584
5585       // Copy ints to xmm registers.
5586       __m128i xh = _mm_cvtsi32_si128( hi );
5587       __m128i xl = _mm_cvtsi32_si128( lo );
5588
5589       // Combine into low half of a single xmm register.
5590       __m128i x = _mm_unpacklo_epi32( xh, xl );
5591       __m128d d;
5592       double sd;
5593
5594       // Merge in appropriate exponents to give the integer bits the right
5595       // magnitude.
5596       x = _mm_unpacklo_epi32( x, exp );
5597
5598       // Subtract away the biases to deal with the IEEE-754 double precision
5599       // implicit 1.
5600       d = _mm_sub_pd( (__m128d) x, bias );
5601
5602       // All conversions up to here are exact. The correctly rounded result is
5603       // calculated using the current rounding mode using the following
5604       // horizontal add.
5605       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5606       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5607                                 // store doesn't really need to be here (except
5608                                 // maybe to zero the other double)
5609       return sd;
5610     }
5611   */
5612
5613   DebugLoc dl = Op.getDebugLoc();
5614   LLVMContext *Context = DAG.getContext();
5615
5616   // Build some magic constants.
5617   std::vector<Constant*> CV0;
5618   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5619   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5620   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5621   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5622   Constant *C0 = ConstantVector::get(CV0);
5623   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5624
5625   std::vector<Constant*> CV1;
5626   CV1.push_back(
5627     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5628   CV1.push_back(
5629     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5630   Constant *C1 = ConstantVector::get(CV1);
5631   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5632
5633   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5634                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5635                                         Op.getOperand(0),
5636                                         DAG.getIntPtrConstant(1)));
5637   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5638                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5639                                         Op.getOperand(0),
5640                                         DAG.getIntPtrConstant(0)));
5641   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5642   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5643                               PseudoSourceValue::getConstantPool(), 0,
5644                               false, false, 16);
5645   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5646   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5647   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5648                               PseudoSourceValue::getConstantPool(), 0,
5649                               false, false, 16);
5650   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5651
5652   // Add the halves; easiest way is to swap them into another reg first.
5653   int ShufMask[2] = { 1, -1 };
5654   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5655                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5656   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5657   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5658                      DAG.getIntPtrConstant(0));
5659 }
5660
5661 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5662 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5663                                                SelectionDAG &DAG) const {
5664   DebugLoc dl = Op.getDebugLoc();
5665   // FP constant to bias correct the final result.
5666   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5667                                    MVT::f64);
5668
5669   // Load the 32-bit value into an XMM register.
5670   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5671                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5672                                          Op.getOperand(0),
5673                                          DAG.getIntPtrConstant(0)));
5674
5675   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5676                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5677                      DAG.getIntPtrConstant(0));
5678
5679   // Or the load with the bias.
5680   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5681                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5682                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5683                                                    MVT::v2f64, Load)),
5684                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5685                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5686                                                    MVT::v2f64, Bias)));
5687   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5688                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5689                    DAG.getIntPtrConstant(0));
5690
5691   // Subtract the bias.
5692   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5693
5694   // Handle final rounding.
5695   EVT DestVT = Op.getValueType();
5696
5697   if (DestVT.bitsLT(MVT::f64)) {
5698     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5699                        DAG.getIntPtrConstant(0));
5700   } else if (DestVT.bitsGT(MVT::f64)) {
5701     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5702   }
5703
5704   // Handle final rounding.
5705   return Sub;
5706 }
5707
5708 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5709                                            SelectionDAG &DAG) const {
5710   SDValue N0 = Op.getOperand(0);
5711   DebugLoc dl = Op.getDebugLoc();
5712
5713   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5714   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5715   // the optimization here.
5716   if (DAG.SignBitIsZero(N0))
5717     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5718
5719   EVT SrcVT = N0.getValueType();
5720   EVT DstVT = Op.getValueType();
5721   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5722     return LowerUINT_TO_FP_i64(Op, DAG);
5723   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5724     return LowerUINT_TO_FP_i32(Op, DAG);
5725
5726   // Make a 64-bit buffer, and use it to build an FILD.
5727   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5728   if (SrcVT == MVT::i32) {
5729     SDValue WordOff = DAG.getConstant(4, getPointerTy());
5730     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5731                                      getPointerTy(), StackSlot, WordOff);
5732     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5733                                   StackSlot, NULL, 0, false, false, 0);
5734     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5735                                   OffsetSlot, NULL, 0, false, false, 0);
5736     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5737     return Fild;
5738   }
5739
5740   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5741   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5742                                 StackSlot, NULL, 0, false, false, 0);
5743   // For i64 source, we need to add the appropriate power of 2 if the input
5744   // was negative.  This is the same as the optimization in
5745   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5746   // we must be careful to do the computation in x87 extended precision, not
5747   // in SSE. (The generic code can't know it's OK to do this, or how to.)
5748   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5749   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5750   SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5751
5752   APInt FF(32, 0x5F800000ULL);
5753
5754   // Check whether the sign bit is set.
5755   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5756                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5757                                  ISD::SETLT);
5758
5759   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5760   SDValue FudgePtr = DAG.getConstantPool(
5761                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5762                                          getPointerTy());
5763
5764   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5765   SDValue Zero = DAG.getIntPtrConstant(0);
5766   SDValue Four = DAG.getIntPtrConstant(4);
5767   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5768                                Zero, Four);
5769   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5770
5771   // Load the value out, extending it from f32 to f80.
5772   // FIXME: Avoid the extend by constructing the right constant pool?
5773   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
5774                                  FudgePtr, PseudoSourceValue::getConstantPool(),
5775                                  0, MVT::f32, false, false, 4);
5776   // Extend everything to 80 bits to force it to be done on x87.
5777   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5778   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5779 }
5780
5781 std::pair<SDValue,SDValue> X86TargetLowering::
5782 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5783   DebugLoc dl = Op.getDebugLoc();
5784
5785   EVT DstTy = Op.getValueType();
5786
5787   if (!IsSigned) {
5788     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5789     DstTy = MVT::i64;
5790   }
5791
5792   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5793          DstTy.getSimpleVT() >= MVT::i16 &&
5794          "Unknown FP_TO_SINT to lower!");
5795
5796   // These are really Legal.
5797   if (DstTy == MVT::i32 &&
5798       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5799     return std::make_pair(SDValue(), SDValue());
5800   if (Subtarget->is64Bit() &&
5801       DstTy == MVT::i64 &&
5802       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5803     return std::make_pair(SDValue(), SDValue());
5804
5805   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5806   // stack slot.
5807   MachineFunction &MF = DAG.getMachineFunction();
5808   unsigned MemSize = DstTy.getSizeInBits()/8;
5809   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5810   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5811
5812   unsigned Opc;
5813   switch (DstTy.getSimpleVT().SimpleTy) {
5814   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5815   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5816   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5817   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5818   }
5819
5820   SDValue Chain = DAG.getEntryNode();
5821   SDValue Value = Op.getOperand(0);
5822   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5823     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5824     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5825                          PseudoSourceValue::getFixedStack(SSFI), 0,
5826                          false, false, 0);
5827     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5828     SDValue Ops[] = {
5829       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5830     };
5831     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5832     Chain = Value.getValue(1);
5833     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5834     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5835   }
5836
5837   // Build the FP_TO_INT*_IN_MEM
5838   SDValue Ops[] = { Chain, Value, StackSlot };
5839   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5840
5841   return std::make_pair(FIST, StackSlot);
5842 }
5843
5844 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5845                                            SelectionDAG &DAG) const {
5846   if (Op.getValueType().isVector()) {
5847     if (Op.getValueType() == MVT::v2i32 &&
5848         Op.getOperand(0).getValueType() == MVT::v2f64) {
5849       return Op;
5850     }
5851     return SDValue();
5852   }
5853
5854   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5855   SDValue FIST = Vals.first, StackSlot = Vals.second;
5856   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5857   if (FIST.getNode() == 0) return Op;
5858
5859   // Load the result.
5860   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5861                      FIST, StackSlot, NULL, 0, false, false, 0);
5862 }
5863
5864 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5865                                            SelectionDAG &DAG) const {
5866   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5867   SDValue FIST = Vals.first, StackSlot = Vals.second;
5868   assert(FIST.getNode() && "Unexpected failure");
5869
5870   // Load the result.
5871   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5872                      FIST, StackSlot, NULL, 0, false, false, 0);
5873 }
5874
5875 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5876                                      SelectionDAG &DAG) const {
5877   LLVMContext *Context = DAG.getContext();
5878   DebugLoc dl = Op.getDebugLoc();
5879   EVT VT = Op.getValueType();
5880   EVT EltVT = VT;
5881   if (VT.isVector())
5882     EltVT = VT.getVectorElementType();
5883   std::vector<Constant*> CV;
5884   if (EltVT == MVT::f64) {
5885     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5886     CV.push_back(C);
5887     CV.push_back(C);
5888   } else {
5889     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5890     CV.push_back(C);
5891     CV.push_back(C);
5892     CV.push_back(C);
5893     CV.push_back(C);
5894   }
5895   Constant *C = ConstantVector::get(CV);
5896   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5897   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5898                              PseudoSourceValue::getConstantPool(), 0,
5899                              false, false, 16);
5900   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5901 }
5902
5903 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5904   LLVMContext *Context = DAG.getContext();
5905   DebugLoc dl = Op.getDebugLoc();
5906   EVT VT = Op.getValueType();
5907   EVT EltVT = VT;
5908   if (VT.isVector())
5909     EltVT = VT.getVectorElementType();
5910   std::vector<Constant*> CV;
5911   if (EltVT == MVT::f64) {
5912     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5913     CV.push_back(C);
5914     CV.push_back(C);
5915   } else {
5916     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5917     CV.push_back(C);
5918     CV.push_back(C);
5919     CV.push_back(C);
5920     CV.push_back(C);
5921   }
5922   Constant *C = ConstantVector::get(CV);
5923   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5924   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5925                              PseudoSourceValue::getConstantPool(), 0,
5926                              false, false, 16);
5927   if (VT.isVector()) {
5928     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5929                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5930                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5931                                 Op.getOperand(0)),
5932                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5933   } else {
5934     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5935   }
5936 }
5937
5938 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5939   LLVMContext *Context = DAG.getContext();
5940   SDValue Op0 = Op.getOperand(0);
5941   SDValue Op1 = Op.getOperand(1);
5942   DebugLoc dl = Op.getDebugLoc();
5943   EVT VT = Op.getValueType();
5944   EVT SrcVT = Op1.getValueType();
5945
5946   // If second operand is smaller, extend it first.
5947   if (SrcVT.bitsLT(VT)) {
5948     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5949     SrcVT = VT;
5950   }
5951   // And if it is bigger, shrink it first.
5952   if (SrcVT.bitsGT(VT)) {
5953     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5954     SrcVT = VT;
5955   }
5956
5957   // At this point the operands and the result should have the same
5958   // type, and that won't be f80 since that is not custom lowered.
5959
5960   // First get the sign bit of second operand.
5961   std::vector<Constant*> CV;
5962   if (SrcVT == MVT::f64) {
5963     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5964     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5965   } else {
5966     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5967     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5968     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5969     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5970   }
5971   Constant *C = ConstantVector::get(CV);
5972   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5973   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5974                               PseudoSourceValue::getConstantPool(), 0,
5975                               false, false, 16);
5976   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5977
5978   // Shift sign bit right or left if the two operands have different types.
5979   if (SrcVT.bitsGT(VT)) {
5980     // Op0 is MVT::f32, Op1 is MVT::f64.
5981     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5982     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5983                           DAG.getConstant(32, MVT::i32));
5984     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5985     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5986                           DAG.getIntPtrConstant(0));
5987   }
5988
5989   // Clear first operand sign bit.
5990   CV.clear();
5991   if (VT == MVT::f64) {
5992     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5993     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5994   } else {
5995     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5996     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5997     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5998     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5999   }
6000   C = ConstantVector::get(CV);
6001   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6002   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6003                               PseudoSourceValue::getConstantPool(), 0,
6004                               false, false, 16);
6005   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6006
6007   // Or the value with the sign bit.
6008   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6009 }
6010
6011 /// Emit nodes that will be selected as "test Op0,Op0", or something
6012 /// equivalent.
6013 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6014                                     SelectionDAG &DAG) const {
6015   DebugLoc dl = Op.getDebugLoc();
6016
6017   // CF and OF aren't always set the way we want. Determine which
6018   // of these we need.
6019   bool NeedCF = false;
6020   bool NeedOF = false;
6021   switch (X86CC) {
6022   default: break;
6023   case X86::COND_A: case X86::COND_AE:
6024   case X86::COND_B: case X86::COND_BE:
6025     NeedCF = true;
6026     break;
6027   case X86::COND_G: case X86::COND_GE:
6028   case X86::COND_L: case X86::COND_LE:
6029   case X86::COND_O: case X86::COND_NO:
6030     NeedOF = true;
6031     break;
6032   }
6033
6034   // See if we can use the EFLAGS value from the operand instead of
6035   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6036   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6037   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6038     // Emit a CMP with 0, which is the TEST pattern.
6039     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6040                        DAG.getConstant(0, Op.getValueType()));
6041
6042   unsigned Opcode = 0;
6043   unsigned NumOperands = 0;
6044   switch (Op.getNode()->getOpcode()) {
6045   case ISD::ADD:
6046     // Due to an isel shortcoming, be conservative if this add is likely to be
6047     // selected as part of a load-modify-store instruction. When the root node
6048     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6049     // uses of other nodes in the match, such as the ADD in this case. This
6050     // leads to the ADD being left around and reselected, with the result being
6051     // two adds in the output.  Alas, even if none our users are stores, that
6052     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6053     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6054     // climbing the DAG back to the root, and it doesn't seem to be worth the
6055     // effort.
6056     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6057            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6058       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6059         goto default_case;
6060
6061     if (ConstantSDNode *C =
6062         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6063       // An add of one will be selected as an INC.
6064       if (C->getAPIntValue() == 1) {
6065         Opcode = X86ISD::INC;
6066         NumOperands = 1;
6067         break;
6068       }
6069
6070       // An add of negative one (subtract of one) will be selected as a DEC.
6071       if (C->getAPIntValue().isAllOnesValue()) {
6072         Opcode = X86ISD::DEC;
6073         NumOperands = 1;
6074         break;
6075       }
6076     }
6077
6078     // Otherwise use a regular EFLAGS-setting add.
6079     Opcode = X86ISD::ADD;
6080     NumOperands = 2;
6081     break;
6082   case ISD::AND: {
6083     // If the primary and result isn't used, don't bother using X86ISD::AND,
6084     // because a TEST instruction will be better.
6085     bool NonFlagUse = false;
6086     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6087            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6088       SDNode *User = *UI;
6089       unsigned UOpNo = UI.getOperandNo();
6090       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6091         // Look pass truncate.
6092         UOpNo = User->use_begin().getOperandNo();
6093         User = *User->use_begin();
6094       }
6095
6096       if (User->getOpcode() != ISD::BRCOND &&
6097           User->getOpcode() != ISD::SETCC &&
6098           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6099         NonFlagUse = true;
6100         break;
6101       }
6102     }
6103
6104     if (!NonFlagUse)
6105       break;
6106   }
6107     // FALL THROUGH
6108   case ISD::SUB:
6109   case ISD::OR:
6110   case ISD::XOR:
6111     // Due to the ISEL shortcoming noted above, be conservative if this op is
6112     // likely to be selected as part of a load-modify-store instruction.
6113     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6114            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6115       if (UI->getOpcode() == ISD::STORE)
6116         goto default_case;
6117
6118     // Otherwise use a regular EFLAGS-setting instruction.
6119     switch (Op.getNode()->getOpcode()) {
6120     default: llvm_unreachable("unexpected operator!");
6121     case ISD::SUB: Opcode = X86ISD::SUB; break;
6122     case ISD::OR:  Opcode = X86ISD::OR;  break;
6123     case ISD::XOR: Opcode = X86ISD::XOR; break;
6124     case ISD::AND: Opcode = X86ISD::AND; break;
6125     }
6126
6127     NumOperands = 2;
6128     break;
6129   case X86ISD::ADD:
6130   case X86ISD::SUB:
6131   case X86ISD::INC:
6132   case X86ISD::DEC:
6133   case X86ISD::OR:
6134   case X86ISD::XOR:
6135   case X86ISD::AND:
6136     return SDValue(Op.getNode(), 1);
6137   default:
6138   default_case:
6139     break;
6140   }
6141
6142   if (Opcode == 0)
6143     // Emit a CMP with 0, which is the TEST pattern.
6144     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6145                        DAG.getConstant(0, Op.getValueType()));
6146
6147   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6148   SmallVector<SDValue, 4> Ops;
6149   for (unsigned i = 0; i != NumOperands; ++i)
6150     Ops.push_back(Op.getOperand(i));
6151
6152   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6153   DAG.ReplaceAllUsesWith(Op, New);
6154   return SDValue(New.getNode(), 1);
6155 }
6156
6157 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6158 /// equivalent.
6159 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6160                                    SelectionDAG &DAG) const {
6161   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6162     if (C->getAPIntValue() == 0)
6163       return EmitTest(Op0, X86CC, DAG);
6164
6165   DebugLoc dl = Op0.getDebugLoc();
6166   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6167 }
6168
6169 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6170 /// if it's possible.
6171 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6172                                      DebugLoc dl, SelectionDAG &DAG) const {
6173   SDValue Op0 = And.getOperand(0);
6174   SDValue Op1 = And.getOperand(1);
6175   if (Op0.getOpcode() == ISD::TRUNCATE)
6176     Op0 = Op0.getOperand(0);
6177   if (Op1.getOpcode() == ISD::TRUNCATE)
6178     Op1 = Op1.getOperand(0);
6179
6180   SDValue LHS, RHS;
6181   if (Op1.getOpcode() == ISD::SHL)
6182     std::swap(Op0, Op1);
6183   if (Op0.getOpcode() == ISD::SHL) {
6184     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6185       if (And00C->getZExtValue() == 1) {
6186         // If we looked past a truncate, check that it's only truncating away
6187         // known zeros.
6188         unsigned BitWidth = Op0.getValueSizeInBits();
6189         unsigned AndBitWidth = And.getValueSizeInBits();
6190         if (BitWidth > AndBitWidth) {
6191           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6192           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6193           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6194             return SDValue();
6195         }
6196         LHS = Op1;
6197         RHS = Op0.getOperand(1);
6198       }
6199   } else if (Op1.getOpcode() == ISD::Constant) {
6200     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6201     SDValue AndLHS = Op0;
6202     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6203       LHS = AndLHS.getOperand(0);
6204       RHS = AndLHS.getOperand(1);
6205     }
6206   }
6207
6208   if (LHS.getNode()) {
6209     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6210     // instruction.  Since the shift amount is in-range-or-undefined, we know
6211     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6212     // the encoding for the i16 version is larger than the i32 version.
6213     // Also promote i16 to i32 for performance / code size reason.
6214     if (LHS.getValueType() == MVT::i8 ||
6215         LHS.getValueType() == MVT::i16)
6216       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6217
6218     // If the operand types disagree, extend the shift amount to match.  Since
6219     // BT ignores high bits (like shifts) we can use anyextend.
6220     if (LHS.getValueType() != RHS.getValueType())
6221       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6222
6223     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6224     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6225     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6226                        DAG.getConstant(Cond, MVT::i8), BT);
6227   }
6228
6229   return SDValue();
6230 }
6231
6232 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6233   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6234   SDValue Op0 = Op.getOperand(0);
6235   SDValue Op1 = Op.getOperand(1);
6236   DebugLoc dl = Op.getDebugLoc();
6237   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6238
6239   // Optimize to BT if possible.
6240   // Lower (X & (1 << N)) == 0 to BT(X, N).
6241   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6242   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6243   if (Op0.getOpcode() == ISD::AND &&
6244       Op0.hasOneUse() &&
6245       Op1.getOpcode() == ISD::Constant &&
6246       cast<ConstantSDNode>(Op1)->isNullValue() &&
6247       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6248     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6249     if (NewSetCC.getNode())
6250       return NewSetCC;
6251   }
6252
6253   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6254   if (Op0.getOpcode() == X86ISD::SETCC &&
6255       Op1.getOpcode() == ISD::Constant &&
6256       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6257        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6258       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6259     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6260     bool Invert = (CC == ISD::SETNE) ^
6261       cast<ConstantSDNode>(Op1)->isNullValue();
6262     if (Invert)
6263       CCode = X86::GetOppositeBranchCondition(CCode);
6264     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6265                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6266   }
6267
6268   bool isFP = Op1.getValueType().isFloatingPoint();
6269   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6270   if (X86CC == X86::COND_INVALID)
6271     return SDValue();
6272
6273   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6274
6275   // Use sbb x, x to materialize carry bit into a GPR.
6276   if (X86CC == X86::COND_B)
6277     return DAG.getNode(ISD::AND, dl, MVT::i8,
6278                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6279                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6280                        DAG.getConstant(1, MVT::i8));
6281
6282   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6283                      DAG.getConstant(X86CC, MVT::i8), Cond);
6284 }
6285
6286 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6287   SDValue Cond;
6288   SDValue Op0 = Op.getOperand(0);
6289   SDValue Op1 = Op.getOperand(1);
6290   SDValue CC = Op.getOperand(2);
6291   EVT VT = Op.getValueType();
6292   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6293   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6294   DebugLoc dl = Op.getDebugLoc();
6295
6296   if (isFP) {
6297     unsigned SSECC = 8;
6298     EVT VT0 = Op0.getValueType();
6299     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6300     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6301     bool Swap = false;
6302
6303     switch (SetCCOpcode) {
6304     default: break;
6305     case ISD::SETOEQ:
6306     case ISD::SETEQ:  SSECC = 0; break;
6307     case ISD::SETOGT:
6308     case ISD::SETGT: Swap = true; // Fallthrough
6309     case ISD::SETLT:
6310     case ISD::SETOLT: SSECC = 1; break;
6311     case ISD::SETOGE:
6312     case ISD::SETGE: Swap = true; // Fallthrough
6313     case ISD::SETLE:
6314     case ISD::SETOLE: SSECC = 2; break;
6315     case ISD::SETUO:  SSECC = 3; break;
6316     case ISD::SETUNE:
6317     case ISD::SETNE:  SSECC = 4; break;
6318     case ISD::SETULE: Swap = true;
6319     case ISD::SETUGE: SSECC = 5; break;
6320     case ISD::SETULT: Swap = true;
6321     case ISD::SETUGT: SSECC = 6; break;
6322     case ISD::SETO:   SSECC = 7; break;
6323     }
6324     if (Swap)
6325       std::swap(Op0, Op1);
6326
6327     // In the two special cases we can't handle, emit two comparisons.
6328     if (SSECC == 8) {
6329       if (SetCCOpcode == ISD::SETUEQ) {
6330         SDValue UNORD, EQ;
6331         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6332         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6333         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6334       }
6335       else if (SetCCOpcode == ISD::SETONE) {
6336         SDValue ORD, NEQ;
6337         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6338         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6339         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6340       }
6341       llvm_unreachable("Illegal FP comparison");
6342     }
6343     // Handle all other FP comparisons here.
6344     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6345   }
6346
6347   // We are handling one of the integer comparisons here.  Since SSE only has
6348   // GT and EQ comparisons for integer, swapping operands and multiple
6349   // operations may be required for some comparisons.
6350   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6351   bool Swap = false, Invert = false, FlipSigns = false;
6352
6353   switch (VT.getSimpleVT().SimpleTy) {
6354   default: break;
6355   case MVT::v8i8:
6356   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6357   case MVT::v4i16:
6358   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6359   case MVT::v2i32:
6360   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6361   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6362   }
6363
6364   switch (SetCCOpcode) {
6365   default: break;
6366   case ISD::SETNE:  Invert = true;
6367   case ISD::SETEQ:  Opc = EQOpc; break;
6368   case ISD::SETLT:  Swap = true;
6369   case ISD::SETGT:  Opc = GTOpc; break;
6370   case ISD::SETGE:  Swap = true;
6371   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6372   case ISD::SETULT: Swap = true;
6373   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6374   case ISD::SETUGE: Swap = true;
6375   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6376   }
6377   if (Swap)
6378     std::swap(Op0, Op1);
6379
6380   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6381   // bits of the inputs before performing those operations.
6382   if (FlipSigns) {
6383     EVT EltVT = VT.getVectorElementType();
6384     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6385                                       EltVT);
6386     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6387     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6388                                     SignBits.size());
6389     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6390     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6391   }
6392
6393   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6394
6395   // If the logical-not of the result is required, perform that now.
6396   if (Invert)
6397     Result = DAG.getNOT(dl, Result, VT);
6398
6399   return Result;
6400 }
6401
6402 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6403 static bool isX86LogicalCmp(SDValue Op) {
6404   unsigned Opc = Op.getNode()->getOpcode();
6405   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6406     return true;
6407   if (Op.getResNo() == 1 &&
6408       (Opc == X86ISD::ADD ||
6409        Opc == X86ISD::SUB ||
6410        Opc == X86ISD::SMUL ||
6411        Opc == X86ISD::UMUL ||
6412        Opc == X86ISD::INC ||
6413        Opc == X86ISD::DEC ||
6414        Opc == X86ISD::OR ||
6415        Opc == X86ISD::XOR ||
6416        Opc == X86ISD::AND))
6417     return true;
6418
6419   return false;
6420 }
6421
6422 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6423   bool addTest = true;
6424   SDValue Cond  = Op.getOperand(0);
6425   DebugLoc dl = Op.getDebugLoc();
6426   SDValue CC;
6427
6428   if (Cond.getOpcode() == ISD::SETCC) {
6429     SDValue NewCond = LowerSETCC(Cond, DAG);
6430     if (NewCond.getNode())
6431       Cond = NewCond;
6432   }
6433
6434   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6435   SDValue Op1 = Op.getOperand(1);
6436   SDValue Op2 = Op.getOperand(2);
6437   if (Cond.getOpcode() == X86ISD::SETCC &&
6438       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6439     SDValue Cmp = Cond.getOperand(1);
6440     if (Cmp.getOpcode() == X86ISD::CMP) {
6441       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6442       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6443       ConstantSDNode *RHSC =
6444         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6445       if (N1C && N1C->isAllOnesValue() &&
6446           N2C && N2C->isNullValue() &&
6447           RHSC && RHSC->isNullValue()) {
6448         SDValue CmpOp0 = Cmp.getOperand(0);
6449         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6450                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6451         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6452                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6453       }
6454     }
6455   }
6456
6457   // Look pass (and (setcc_carry (cmp ...)), 1).
6458   if (Cond.getOpcode() == ISD::AND &&
6459       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6460     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6461     if (C && C->getAPIntValue() == 1) 
6462       Cond = Cond.getOperand(0);
6463   }
6464
6465   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6466   // setting operand in place of the X86ISD::SETCC.
6467   if (Cond.getOpcode() == X86ISD::SETCC ||
6468       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6469     CC = Cond.getOperand(0);
6470
6471     SDValue Cmp = Cond.getOperand(1);
6472     unsigned Opc = Cmp.getOpcode();
6473     EVT VT = Op.getValueType();
6474
6475     bool IllegalFPCMov = false;
6476     if (VT.isFloatingPoint() && !VT.isVector() &&
6477         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6478       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6479
6480     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6481         Opc == X86ISD::BT) { // FIXME
6482       Cond = Cmp;
6483       addTest = false;
6484     }
6485   }
6486
6487   if (addTest) {
6488     // Look pass the truncate.
6489     if (Cond.getOpcode() == ISD::TRUNCATE)
6490       Cond = Cond.getOperand(0);
6491
6492     // We know the result of AND is compared against zero. Try to match
6493     // it to BT.
6494     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6495       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6496       if (NewSetCC.getNode()) {
6497         CC = NewSetCC.getOperand(0);
6498         Cond = NewSetCC.getOperand(1);
6499         addTest = false;
6500       }
6501     }
6502   }
6503
6504   if (addTest) {
6505     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6506     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6507   }
6508
6509   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6510   // condition is true.
6511   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6512   SDValue Ops[] = { Op2, Op1, CC, Cond };
6513   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6514 }
6515
6516 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6517 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6518 // from the AND / OR.
6519 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6520   Opc = Op.getOpcode();
6521   if (Opc != ISD::OR && Opc != ISD::AND)
6522     return false;
6523   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6524           Op.getOperand(0).hasOneUse() &&
6525           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6526           Op.getOperand(1).hasOneUse());
6527 }
6528
6529 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6530 // 1 and that the SETCC node has a single use.
6531 static bool isXor1OfSetCC(SDValue Op) {
6532   if (Op.getOpcode() != ISD::XOR)
6533     return false;
6534   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6535   if (N1C && N1C->getAPIntValue() == 1) {
6536     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6537       Op.getOperand(0).hasOneUse();
6538   }
6539   return false;
6540 }
6541
6542 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6543   bool addTest = true;
6544   SDValue Chain = Op.getOperand(0);
6545   SDValue Cond  = Op.getOperand(1);
6546   SDValue Dest  = Op.getOperand(2);
6547   DebugLoc dl = Op.getDebugLoc();
6548   SDValue CC;
6549
6550   if (Cond.getOpcode() == ISD::SETCC) {
6551     SDValue NewCond = LowerSETCC(Cond, DAG);
6552     if (NewCond.getNode())
6553       Cond = NewCond;
6554   }
6555 #if 0
6556   // FIXME: LowerXALUO doesn't handle these!!
6557   else if (Cond.getOpcode() == X86ISD::ADD  ||
6558            Cond.getOpcode() == X86ISD::SUB  ||
6559            Cond.getOpcode() == X86ISD::SMUL ||
6560            Cond.getOpcode() == X86ISD::UMUL)
6561     Cond = LowerXALUO(Cond, DAG);
6562 #endif
6563
6564   // Look pass (and (setcc_carry (cmp ...)), 1).
6565   if (Cond.getOpcode() == ISD::AND &&
6566       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6567     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6568     if (C && C->getAPIntValue() == 1) 
6569       Cond = Cond.getOperand(0);
6570   }
6571
6572   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6573   // setting operand in place of the X86ISD::SETCC.
6574   if (Cond.getOpcode() == X86ISD::SETCC ||
6575       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6576     CC = Cond.getOperand(0);
6577
6578     SDValue Cmp = Cond.getOperand(1);
6579     unsigned Opc = Cmp.getOpcode();
6580     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6581     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6582       Cond = Cmp;
6583       addTest = false;
6584     } else {
6585       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6586       default: break;
6587       case X86::COND_O:
6588       case X86::COND_B:
6589         // These can only come from an arithmetic instruction with overflow,
6590         // e.g. SADDO, UADDO.
6591         Cond = Cond.getNode()->getOperand(1);
6592         addTest = false;
6593         break;
6594       }
6595     }
6596   } else {
6597     unsigned CondOpc;
6598     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6599       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6600       if (CondOpc == ISD::OR) {
6601         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6602         // two branches instead of an explicit OR instruction with a
6603         // separate test.
6604         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6605             isX86LogicalCmp(Cmp)) {
6606           CC = Cond.getOperand(0).getOperand(0);
6607           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6608                               Chain, Dest, CC, Cmp);
6609           CC = Cond.getOperand(1).getOperand(0);
6610           Cond = Cmp;
6611           addTest = false;
6612         }
6613       } else { // ISD::AND
6614         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6615         // two branches instead of an explicit AND instruction with a
6616         // separate test. However, we only do this if this block doesn't
6617         // have a fall-through edge, because this requires an explicit
6618         // jmp when the condition is false.
6619         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6620             isX86LogicalCmp(Cmp) &&
6621             Op.getNode()->hasOneUse()) {
6622           X86::CondCode CCode =
6623             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6624           CCode = X86::GetOppositeBranchCondition(CCode);
6625           CC = DAG.getConstant(CCode, MVT::i8);
6626           SDNode *User = *Op.getNode()->use_begin();
6627           // Look for an unconditional branch following this conditional branch.
6628           // We need this because we need to reverse the successors in order
6629           // to implement FCMP_OEQ.
6630           if (User->getOpcode() == ISD::BR) {
6631             SDValue FalseBB = User->getOperand(1);
6632             SDNode *NewBR =
6633               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
6634             assert(NewBR == User);
6635             (void)NewBR;
6636             Dest = FalseBB;
6637
6638             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6639                                 Chain, Dest, CC, Cmp);
6640             X86::CondCode CCode =
6641               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6642             CCode = X86::GetOppositeBranchCondition(CCode);
6643             CC = DAG.getConstant(CCode, MVT::i8);
6644             Cond = Cmp;
6645             addTest = false;
6646           }
6647         }
6648       }
6649     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6650       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6651       // It should be transformed during dag combiner except when the condition
6652       // is set by a arithmetics with overflow node.
6653       X86::CondCode CCode =
6654         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6655       CCode = X86::GetOppositeBranchCondition(CCode);
6656       CC = DAG.getConstant(CCode, MVT::i8);
6657       Cond = Cond.getOperand(0).getOperand(1);
6658       addTest = false;
6659     }
6660   }
6661
6662   if (addTest) {
6663     // Look pass the truncate.
6664     if (Cond.getOpcode() == ISD::TRUNCATE)
6665       Cond = Cond.getOperand(0);
6666
6667     // We know the result of AND is compared against zero. Try to match
6668     // it to BT.
6669     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6670       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6671       if (NewSetCC.getNode()) {
6672         CC = NewSetCC.getOperand(0);
6673         Cond = NewSetCC.getOperand(1);
6674         addTest = false;
6675       }
6676     }
6677   }
6678
6679   if (addTest) {
6680     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6681     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6682   }
6683   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6684                      Chain, Dest, CC, Cond);
6685 }
6686
6687
6688 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6689 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6690 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6691 // that the guard pages used by the OS virtual memory manager are allocated in
6692 // correct sequence.
6693 SDValue
6694 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6695                                            SelectionDAG &DAG) const {
6696   assert(Subtarget->isTargetCygMing() &&
6697          "This should be used only on Cygwin/Mingw targets");
6698   DebugLoc dl = Op.getDebugLoc();
6699
6700   // Get the inputs.
6701   SDValue Chain = Op.getOperand(0);
6702   SDValue Size  = Op.getOperand(1);
6703   // FIXME: Ensure alignment here
6704
6705   SDValue Flag;
6706
6707   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6708
6709   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6710   Flag = Chain.getValue(1);
6711
6712   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6713
6714   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6715   Flag = Chain.getValue(1);
6716
6717   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6718
6719   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6720   return DAG.getMergeValues(Ops1, 2, dl);
6721 }
6722
6723 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6724   MachineFunction &MF = DAG.getMachineFunction();
6725   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6726
6727   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6728   DebugLoc dl = Op.getDebugLoc();
6729
6730   if (!Subtarget->is64Bit()) {
6731     // vastart just stores the address of the VarArgsFrameIndex slot into the
6732     // memory location argument.
6733     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6734                                    getPointerTy());
6735     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6736                         false, false, 0);
6737   }
6738
6739   // __va_list_tag:
6740   //   gp_offset         (0 - 6 * 8)
6741   //   fp_offset         (48 - 48 + 8 * 16)
6742   //   overflow_arg_area (point to parameters coming in memory).
6743   //   reg_save_area
6744   SmallVector<SDValue, 8> MemOps;
6745   SDValue FIN = Op.getOperand(1);
6746   // Store gp_offset
6747   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6748                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6749                                                MVT::i32),
6750                                FIN, SV, 0, false, false, 0);
6751   MemOps.push_back(Store);
6752
6753   // Store fp_offset
6754   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6755                     FIN, DAG.getIntPtrConstant(4));
6756   Store = DAG.getStore(Op.getOperand(0), dl,
6757                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6758                                        MVT::i32),
6759                        FIN, SV, 0, false, false, 0);
6760   MemOps.push_back(Store);
6761
6762   // Store ptr to overflow_arg_area
6763   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6764                     FIN, DAG.getIntPtrConstant(4));
6765   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6766                                     getPointerTy());
6767   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6768                        false, false, 0);
6769   MemOps.push_back(Store);
6770
6771   // Store ptr to reg_save_area.
6772   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6773                     FIN, DAG.getIntPtrConstant(8));
6774   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6775                                     getPointerTy());
6776   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6777                        false, false, 0);
6778   MemOps.push_back(Store);
6779   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6780                      &MemOps[0], MemOps.size());
6781 }
6782
6783 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6784   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6785   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6786
6787   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6788   return SDValue();
6789 }
6790
6791 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6792   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6793   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6794   SDValue Chain = Op.getOperand(0);
6795   SDValue DstPtr = Op.getOperand(1);
6796   SDValue SrcPtr = Op.getOperand(2);
6797   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6798   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6799   DebugLoc dl = Op.getDebugLoc();
6800
6801   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6802                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6803                        false, DstSV, 0, SrcSV, 0);
6804 }
6805
6806 SDValue
6807 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6808   DebugLoc dl = Op.getDebugLoc();
6809   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6810   switch (IntNo) {
6811   default: return SDValue();    // Don't custom lower most intrinsics.
6812   // Comparison intrinsics.
6813   case Intrinsic::x86_sse_comieq_ss:
6814   case Intrinsic::x86_sse_comilt_ss:
6815   case Intrinsic::x86_sse_comile_ss:
6816   case Intrinsic::x86_sse_comigt_ss:
6817   case Intrinsic::x86_sse_comige_ss:
6818   case Intrinsic::x86_sse_comineq_ss:
6819   case Intrinsic::x86_sse_ucomieq_ss:
6820   case Intrinsic::x86_sse_ucomilt_ss:
6821   case Intrinsic::x86_sse_ucomile_ss:
6822   case Intrinsic::x86_sse_ucomigt_ss:
6823   case Intrinsic::x86_sse_ucomige_ss:
6824   case Intrinsic::x86_sse_ucomineq_ss:
6825   case Intrinsic::x86_sse2_comieq_sd:
6826   case Intrinsic::x86_sse2_comilt_sd:
6827   case Intrinsic::x86_sse2_comile_sd:
6828   case Intrinsic::x86_sse2_comigt_sd:
6829   case Intrinsic::x86_sse2_comige_sd:
6830   case Intrinsic::x86_sse2_comineq_sd:
6831   case Intrinsic::x86_sse2_ucomieq_sd:
6832   case Intrinsic::x86_sse2_ucomilt_sd:
6833   case Intrinsic::x86_sse2_ucomile_sd:
6834   case Intrinsic::x86_sse2_ucomigt_sd:
6835   case Intrinsic::x86_sse2_ucomige_sd:
6836   case Intrinsic::x86_sse2_ucomineq_sd: {
6837     unsigned Opc = 0;
6838     ISD::CondCode CC = ISD::SETCC_INVALID;
6839     switch (IntNo) {
6840     default: break;
6841     case Intrinsic::x86_sse_comieq_ss:
6842     case Intrinsic::x86_sse2_comieq_sd:
6843       Opc = X86ISD::COMI;
6844       CC = ISD::SETEQ;
6845       break;
6846     case Intrinsic::x86_sse_comilt_ss:
6847     case Intrinsic::x86_sse2_comilt_sd:
6848       Opc = X86ISD::COMI;
6849       CC = ISD::SETLT;
6850       break;
6851     case Intrinsic::x86_sse_comile_ss:
6852     case Intrinsic::x86_sse2_comile_sd:
6853       Opc = X86ISD::COMI;
6854       CC = ISD::SETLE;
6855       break;
6856     case Intrinsic::x86_sse_comigt_ss:
6857     case Intrinsic::x86_sse2_comigt_sd:
6858       Opc = X86ISD::COMI;
6859       CC = ISD::SETGT;
6860       break;
6861     case Intrinsic::x86_sse_comige_ss:
6862     case Intrinsic::x86_sse2_comige_sd:
6863       Opc = X86ISD::COMI;
6864       CC = ISD::SETGE;
6865       break;
6866     case Intrinsic::x86_sse_comineq_ss:
6867     case Intrinsic::x86_sse2_comineq_sd:
6868       Opc = X86ISD::COMI;
6869       CC = ISD::SETNE;
6870       break;
6871     case Intrinsic::x86_sse_ucomieq_ss:
6872     case Intrinsic::x86_sse2_ucomieq_sd:
6873       Opc = X86ISD::UCOMI;
6874       CC = ISD::SETEQ;
6875       break;
6876     case Intrinsic::x86_sse_ucomilt_ss:
6877     case Intrinsic::x86_sse2_ucomilt_sd:
6878       Opc = X86ISD::UCOMI;
6879       CC = ISD::SETLT;
6880       break;
6881     case Intrinsic::x86_sse_ucomile_ss:
6882     case Intrinsic::x86_sse2_ucomile_sd:
6883       Opc = X86ISD::UCOMI;
6884       CC = ISD::SETLE;
6885       break;
6886     case Intrinsic::x86_sse_ucomigt_ss:
6887     case Intrinsic::x86_sse2_ucomigt_sd:
6888       Opc = X86ISD::UCOMI;
6889       CC = ISD::SETGT;
6890       break;
6891     case Intrinsic::x86_sse_ucomige_ss:
6892     case Intrinsic::x86_sse2_ucomige_sd:
6893       Opc = X86ISD::UCOMI;
6894       CC = ISD::SETGE;
6895       break;
6896     case Intrinsic::x86_sse_ucomineq_ss:
6897     case Intrinsic::x86_sse2_ucomineq_sd:
6898       Opc = X86ISD::UCOMI;
6899       CC = ISD::SETNE;
6900       break;
6901     }
6902
6903     SDValue LHS = Op.getOperand(1);
6904     SDValue RHS = Op.getOperand(2);
6905     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6906     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6907     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6908     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6909                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6910     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6911   }
6912   // ptest intrinsics. The intrinsic these come from are designed to return
6913   // an integer value, not just an instruction so lower it to the ptest
6914   // pattern and a setcc for the result.
6915   case Intrinsic::x86_sse41_ptestz:
6916   case Intrinsic::x86_sse41_ptestc:
6917   case Intrinsic::x86_sse41_ptestnzc:{
6918     unsigned X86CC = 0;
6919     switch (IntNo) {
6920     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6921     case Intrinsic::x86_sse41_ptestz:
6922       // ZF = 1
6923       X86CC = X86::COND_E;
6924       break;
6925     case Intrinsic::x86_sse41_ptestc:
6926       // CF = 1
6927       X86CC = X86::COND_B;
6928       break;
6929     case Intrinsic::x86_sse41_ptestnzc:
6930       // ZF and CF = 0
6931       X86CC = X86::COND_A;
6932       break;
6933     }
6934
6935     SDValue LHS = Op.getOperand(1);
6936     SDValue RHS = Op.getOperand(2);
6937     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6938     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6939     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6940     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6941   }
6942
6943   // Fix vector shift instructions where the last operand is a non-immediate
6944   // i32 value.
6945   case Intrinsic::x86_sse2_pslli_w:
6946   case Intrinsic::x86_sse2_pslli_d:
6947   case Intrinsic::x86_sse2_pslli_q:
6948   case Intrinsic::x86_sse2_psrli_w:
6949   case Intrinsic::x86_sse2_psrli_d:
6950   case Intrinsic::x86_sse2_psrli_q:
6951   case Intrinsic::x86_sse2_psrai_w:
6952   case Intrinsic::x86_sse2_psrai_d:
6953   case Intrinsic::x86_mmx_pslli_w:
6954   case Intrinsic::x86_mmx_pslli_d:
6955   case Intrinsic::x86_mmx_pslli_q:
6956   case Intrinsic::x86_mmx_psrli_w:
6957   case Intrinsic::x86_mmx_psrli_d:
6958   case Intrinsic::x86_mmx_psrli_q:
6959   case Intrinsic::x86_mmx_psrai_w:
6960   case Intrinsic::x86_mmx_psrai_d: {
6961     SDValue ShAmt = Op.getOperand(2);
6962     if (isa<ConstantSDNode>(ShAmt))
6963       return SDValue();
6964
6965     unsigned NewIntNo = 0;
6966     EVT ShAmtVT = MVT::v4i32;
6967     switch (IntNo) {
6968     case Intrinsic::x86_sse2_pslli_w:
6969       NewIntNo = Intrinsic::x86_sse2_psll_w;
6970       break;
6971     case Intrinsic::x86_sse2_pslli_d:
6972       NewIntNo = Intrinsic::x86_sse2_psll_d;
6973       break;
6974     case Intrinsic::x86_sse2_pslli_q:
6975       NewIntNo = Intrinsic::x86_sse2_psll_q;
6976       break;
6977     case Intrinsic::x86_sse2_psrli_w:
6978       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6979       break;
6980     case Intrinsic::x86_sse2_psrli_d:
6981       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6982       break;
6983     case Intrinsic::x86_sse2_psrli_q:
6984       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6985       break;
6986     case Intrinsic::x86_sse2_psrai_w:
6987       NewIntNo = Intrinsic::x86_sse2_psra_w;
6988       break;
6989     case Intrinsic::x86_sse2_psrai_d:
6990       NewIntNo = Intrinsic::x86_sse2_psra_d;
6991       break;
6992     default: {
6993       ShAmtVT = MVT::v2i32;
6994       switch (IntNo) {
6995       case Intrinsic::x86_mmx_pslli_w:
6996         NewIntNo = Intrinsic::x86_mmx_psll_w;
6997         break;
6998       case Intrinsic::x86_mmx_pslli_d:
6999         NewIntNo = Intrinsic::x86_mmx_psll_d;
7000         break;
7001       case Intrinsic::x86_mmx_pslli_q:
7002         NewIntNo = Intrinsic::x86_mmx_psll_q;
7003         break;
7004       case Intrinsic::x86_mmx_psrli_w:
7005         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7006         break;
7007       case Intrinsic::x86_mmx_psrli_d:
7008         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7009         break;
7010       case Intrinsic::x86_mmx_psrli_q:
7011         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7012         break;
7013       case Intrinsic::x86_mmx_psrai_w:
7014         NewIntNo = Intrinsic::x86_mmx_psra_w;
7015         break;
7016       case Intrinsic::x86_mmx_psrai_d:
7017         NewIntNo = Intrinsic::x86_mmx_psra_d;
7018         break;
7019       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7020       }
7021       break;
7022     }
7023     }
7024
7025     // The vector shift intrinsics with scalars uses 32b shift amounts but
7026     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7027     // to be zero.
7028     SDValue ShOps[4];
7029     ShOps[0] = ShAmt;
7030     ShOps[1] = DAG.getConstant(0, MVT::i32);
7031     if (ShAmtVT == MVT::v4i32) {
7032       ShOps[2] = DAG.getUNDEF(MVT::i32);
7033       ShOps[3] = DAG.getUNDEF(MVT::i32);
7034       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7035     } else {
7036       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7037     }
7038
7039     EVT VT = Op.getValueType();
7040     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7041     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7042                        DAG.getConstant(NewIntNo, MVT::i32),
7043                        Op.getOperand(1), ShAmt);
7044   }
7045   }
7046 }
7047
7048 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7049                                            SelectionDAG &DAG) const {
7050   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7051   MFI->setReturnAddressIsTaken(true);
7052
7053   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7054   DebugLoc dl = Op.getDebugLoc();
7055
7056   if (Depth > 0) {
7057     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7058     SDValue Offset =
7059       DAG.getConstant(TD->getPointerSize(),
7060                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7061     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7062                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7063                                    FrameAddr, Offset),
7064                        NULL, 0, false, false, 0);
7065   }
7066
7067   // Just load the return address.
7068   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7069   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7070                      RetAddrFI, NULL, 0, false, false, 0);
7071 }
7072
7073 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7074   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7075   MFI->setFrameAddressIsTaken(true);
7076
7077   EVT VT = Op.getValueType();
7078   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7079   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7080   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7081   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7082   while (Depth--)
7083     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7084                             false, false, 0);
7085   return FrameAddr;
7086 }
7087
7088 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7089                                                      SelectionDAG &DAG) const {
7090   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7091 }
7092
7093 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7094   MachineFunction &MF = DAG.getMachineFunction();
7095   SDValue Chain     = Op.getOperand(0);
7096   SDValue Offset    = Op.getOperand(1);
7097   SDValue Handler   = Op.getOperand(2);
7098   DebugLoc dl       = Op.getDebugLoc();
7099
7100   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7101                                   getPointerTy());
7102   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7103
7104   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7105                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7106   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7107   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7108   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7109   MF.getRegInfo().addLiveOut(StoreAddrReg);
7110
7111   return DAG.getNode(X86ISD::EH_RETURN, dl,
7112                      MVT::Other,
7113                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7114 }
7115
7116 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7117                                              SelectionDAG &DAG) const {
7118   SDValue Root = Op.getOperand(0);
7119   SDValue Trmp = Op.getOperand(1); // trampoline
7120   SDValue FPtr = Op.getOperand(2); // nested function
7121   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7122   DebugLoc dl  = Op.getDebugLoc();
7123
7124   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7125
7126   if (Subtarget->is64Bit()) {
7127     SDValue OutChains[6];
7128
7129     // Large code-model.
7130     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7131     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7132
7133     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7134     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7135
7136     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7137
7138     // Load the pointer to the nested function into R11.
7139     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7140     SDValue Addr = Trmp;
7141     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7142                                 Addr, TrmpAddr, 0, false, false, 0);
7143
7144     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7145                        DAG.getConstant(2, MVT::i64));
7146     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7147                                 false, false, 2);
7148
7149     // Load the 'nest' parameter value into R10.
7150     // R10 is specified in X86CallingConv.td
7151     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7152     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7153                        DAG.getConstant(10, MVT::i64));
7154     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7155                                 Addr, TrmpAddr, 10, false, false, 0);
7156
7157     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7158                        DAG.getConstant(12, MVT::i64));
7159     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7160                                 false, false, 2);
7161
7162     // Jump to the nested function.
7163     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7164     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7165                        DAG.getConstant(20, MVT::i64));
7166     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7167                                 Addr, TrmpAddr, 20, false, false, 0);
7168
7169     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7170     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7171                        DAG.getConstant(22, MVT::i64));
7172     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7173                                 TrmpAddr, 22, false, false, 0);
7174
7175     SDValue Ops[] =
7176       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7177     return DAG.getMergeValues(Ops, 2, dl);
7178   } else {
7179     const Function *Func =
7180       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7181     CallingConv::ID CC = Func->getCallingConv();
7182     unsigned NestReg;
7183
7184     switch (CC) {
7185     default:
7186       llvm_unreachable("Unsupported calling convention");
7187     case CallingConv::C:
7188     case CallingConv::X86_StdCall: {
7189       // Pass 'nest' parameter in ECX.
7190       // Must be kept in sync with X86CallingConv.td
7191       NestReg = X86::ECX;
7192
7193       // Check that ECX wasn't needed by an 'inreg' parameter.
7194       const FunctionType *FTy = Func->getFunctionType();
7195       const AttrListPtr &Attrs = Func->getAttributes();
7196
7197       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7198         unsigned InRegCount = 0;
7199         unsigned Idx = 1;
7200
7201         for (FunctionType::param_iterator I = FTy->param_begin(),
7202              E = FTy->param_end(); I != E; ++I, ++Idx)
7203           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7204             // FIXME: should only count parameters that are lowered to integers.
7205             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7206
7207         if (InRegCount > 2) {
7208           report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7209         }
7210       }
7211       break;
7212     }
7213     case CallingConv::X86_FastCall:
7214     case CallingConv::X86_ThisCall:
7215     case CallingConv::Fast:
7216       // Pass 'nest' parameter in EAX.
7217       // Must be kept in sync with X86CallingConv.td
7218       NestReg = X86::EAX;
7219       break;
7220     }
7221
7222     SDValue OutChains[4];
7223     SDValue Addr, Disp;
7224
7225     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7226                        DAG.getConstant(10, MVT::i32));
7227     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7228
7229     // This is storing the opcode for MOV32ri.
7230     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7231     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7232     OutChains[0] = DAG.getStore(Root, dl,
7233                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7234                                 Trmp, TrmpAddr, 0, false, false, 0);
7235
7236     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7237                        DAG.getConstant(1, MVT::i32));
7238     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7239                                 false, false, 1);
7240
7241     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7242     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7243                        DAG.getConstant(5, MVT::i32));
7244     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7245                                 TrmpAddr, 5, false, false, 1);
7246
7247     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7248                        DAG.getConstant(6, MVT::i32));
7249     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7250                                 false, false, 1);
7251
7252     SDValue Ops[] =
7253       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7254     return DAG.getMergeValues(Ops, 2, dl);
7255   }
7256 }
7257
7258 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7259                                             SelectionDAG &DAG) const {
7260   /*
7261    The rounding mode is in bits 11:10 of FPSR, and has the following
7262    settings:
7263      00 Round to nearest
7264      01 Round to -inf
7265      10 Round to +inf
7266      11 Round to 0
7267
7268   FLT_ROUNDS, on the other hand, expects the following:
7269     -1 Undefined
7270      0 Round to 0
7271      1 Round to nearest
7272      2 Round to +inf
7273      3 Round to -inf
7274
7275   To perform the conversion, we do:
7276     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7277   */
7278
7279   MachineFunction &MF = DAG.getMachineFunction();
7280   const TargetMachine &TM = MF.getTarget();
7281   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7282   unsigned StackAlignment = TFI.getStackAlignment();
7283   EVT VT = Op.getValueType();
7284   DebugLoc dl = Op.getDebugLoc();
7285
7286   // Save FP Control Word to stack slot
7287   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7288   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7289
7290   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7291                               DAG.getEntryNode(), StackSlot);
7292
7293   // Load FP Control Word from stack slot
7294   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7295                             false, false, 0);
7296
7297   // Transform as necessary
7298   SDValue CWD1 =
7299     DAG.getNode(ISD::SRL, dl, MVT::i16,
7300                 DAG.getNode(ISD::AND, dl, MVT::i16,
7301                             CWD, DAG.getConstant(0x800, MVT::i16)),
7302                 DAG.getConstant(11, MVT::i8));
7303   SDValue CWD2 =
7304     DAG.getNode(ISD::SRL, dl, MVT::i16,
7305                 DAG.getNode(ISD::AND, dl, MVT::i16,
7306                             CWD, DAG.getConstant(0x400, MVT::i16)),
7307                 DAG.getConstant(9, MVT::i8));
7308
7309   SDValue RetVal =
7310     DAG.getNode(ISD::AND, dl, MVT::i16,
7311                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7312                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7313                             DAG.getConstant(1, MVT::i16)),
7314                 DAG.getConstant(3, MVT::i16));
7315
7316
7317   return DAG.getNode((VT.getSizeInBits() < 16 ?
7318                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7319 }
7320
7321 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7322   EVT VT = Op.getValueType();
7323   EVT OpVT = VT;
7324   unsigned NumBits = VT.getSizeInBits();
7325   DebugLoc dl = Op.getDebugLoc();
7326
7327   Op = Op.getOperand(0);
7328   if (VT == MVT::i8) {
7329     // Zero extend to i32 since there is not an i8 bsr.
7330     OpVT = MVT::i32;
7331     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7332   }
7333
7334   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7335   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7336   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7337
7338   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7339   SDValue Ops[] = {
7340     Op,
7341     DAG.getConstant(NumBits+NumBits-1, OpVT),
7342     DAG.getConstant(X86::COND_E, MVT::i8),
7343     Op.getValue(1)
7344   };
7345   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7346
7347   // Finally xor with NumBits-1.
7348   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7349
7350   if (VT == MVT::i8)
7351     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7352   return Op;
7353 }
7354
7355 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7356   EVT VT = Op.getValueType();
7357   EVT OpVT = VT;
7358   unsigned NumBits = VT.getSizeInBits();
7359   DebugLoc dl = Op.getDebugLoc();
7360
7361   Op = Op.getOperand(0);
7362   if (VT == MVT::i8) {
7363     OpVT = MVT::i32;
7364     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7365   }
7366
7367   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7368   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7369   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7370
7371   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7372   SDValue Ops[] = {
7373     Op,
7374     DAG.getConstant(NumBits, OpVT),
7375     DAG.getConstant(X86::COND_E, MVT::i8),
7376     Op.getValue(1)
7377   };
7378   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7379
7380   if (VT == MVT::i8)
7381     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7382   return Op;
7383 }
7384
7385 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7386   EVT VT = Op.getValueType();
7387   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7388   DebugLoc dl = Op.getDebugLoc();
7389
7390   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7391   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7392   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7393   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7394   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7395   //
7396   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7397   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7398   //  return AloBlo + AloBhi + AhiBlo;
7399
7400   SDValue A = Op.getOperand(0);
7401   SDValue B = Op.getOperand(1);
7402
7403   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7404                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7405                        A, DAG.getConstant(32, MVT::i32));
7406   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7407                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7408                        B, DAG.getConstant(32, MVT::i32));
7409   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7410                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7411                        A, B);
7412   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7413                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7414                        A, Bhi);
7415   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7416                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7417                        Ahi, B);
7418   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7419                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7420                        AloBhi, DAG.getConstant(32, MVT::i32));
7421   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7422                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7423                        AhiBlo, DAG.getConstant(32, MVT::i32));
7424   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7425   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7426   return Res;
7427 }
7428
7429
7430 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7431   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7432   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7433   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7434   // has only one use.
7435   SDNode *N = Op.getNode();
7436   SDValue LHS = N->getOperand(0);
7437   SDValue RHS = N->getOperand(1);
7438   unsigned BaseOp = 0;
7439   unsigned Cond = 0;
7440   DebugLoc dl = Op.getDebugLoc();
7441
7442   switch (Op.getOpcode()) {
7443   default: llvm_unreachable("Unknown ovf instruction!");
7444   case ISD::SADDO:
7445     // A subtract of one will be selected as a INC. Note that INC doesn't
7446     // set CF, so we can't do this for UADDO.
7447     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7448       if (C->getAPIntValue() == 1) {
7449         BaseOp = X86ISD::INC;
7450         Cond = X86::COND_O;
7451         break;
7452       }
7453     BaseOp = X86ISD::ADD;
7454     Cond = X86::COND_O;
7455     break;
7456   case ISD::UADDO:
7457     BaseOp = X86ISD::ADD;
7458     Cond = X86::COND_B;
7459     break;
7460   case ISD::SSUBO:
7461     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7462     // set CF, so we can't do this for USUBO.
7463     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7464       if (C->getAPIntValue() == 1) {
7465         BaseOp = X86ISD::DEC;
7466         Cond = X86::COND_O;
7467         break;
7468       }
7469     BaseOp = X86ISD::SUB;
7470     Cond = X86::COND_O;
7471     break;
7472   case ISD::USUBO:
7473     BaseOp = X86ISD::SUB;
7474     Cond = X86::COND_B;
7475     break;
7476   case ISD::SMULO:
7477     BaseOp = X86ISD::SMUL;
7478     Cond = X86::COND_O;
7479     break;
7480   case ISD::UMULO:
7481     BaseOp = X86ISD::UMUL;
7482     Cond = X86::COND_B;
7483     break;
7484   }
7485
7486   // Also sets EFLAGS.
7487   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7488   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7489
7490   SDValue SetCC =
7491     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7492                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7493
7494   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7495   return Sum;
7496 }
7497
7498 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7499   EVT T = Op.getValueType();
7500   DebugLoc dl = Op.getDebugLoc();
7501   unsigned Reg = 0;
7502   unsigned size = 0;
7503   switch(T.getSimpleVT().SimpleTy) {
7504   default:
7505     assert(false && "Invalid value type!");
7506   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7507   case MVT::i16: Reg = X86::AX;  size = 2; break;
7508   case MVT::i32: Reg = X86::EAX; size = 4; break;
7509   case MVT::i64:
7510     assert(Subtarget->is64Bit() && "Node not type legal!");
7511     Reg = X86::RAX; size = 8;
7512     break;
7513   }
7514   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7515                                     Op.getOperand(2), SDValue());
7516   SDValue Ops[] = { cpIn.getValue(0),
7517                     Op.getOperand(1),
7518                     Op.getOperand(3),
7519                     DAG.getTargetConstant(size, MVT::i8),
7520                     cpIn.getValue(1) };
7521   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7522   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7523   SDValue cpOut =
7524     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7525   return cpOut;
7526 }
7527
7528 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7529                                                  SelectionDAG &DAG) const {
7530   assert(Subtarget->is64Bit() && "Result not type legalized?");
7531   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7532   SDValue TheChain = Op.getOperand(0);
7533   DebugLoc dl = Op.getDebugLoc();
7534   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7535   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7536   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7537                                    rax.getValue(2));
7538   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7539                             DAG.getConstant(32, MVT::i8));
7540   SDValue Ops[] = {
7541     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7542     rdx.getValue(1)
7543   };
7544   return DAG.getMergeValues(Ops, 2, dl);
7545 }
7546
7547 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
7548                                             SelectionDAG &DAG) const {
7549   EVT SrcVT = Op.getOperand(0).getValueType();
7550   EVT DstVT = Op.getValueType();
7551   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
7552           Subtarget->hasMMX() && !DisableMMX) &&
7553          "Unexpected custom BIT_CONVERT");
7554   assert((DstVT == MVT::i64 || 
7555           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
7556          "Unexpected custom BIT_CONVERT");
7557   // i64 <=> MMX conversions are Legal.
7558   if (SrcVT==MVT::i64 && DstVT.isVector())
7559     return Op;
7560   if (DstVT==MVT::i64 && SrcVT.isVector())
7561     return Op;
7562   // MMX <=> MMX conversions are Legal.
7563   if (SrcVT.isVector() && DstVT.isVector())
7564     return Op;
7565   // All other conversions need to be expanded.
7566   return SDValue();
7567 }
7568 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7569   SDNode *Node = Op.getNode();
7570   DebugLoc dl = Node->getDebugLoc();
7571   EVT T = Node->getValueType(0);
7572   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7573                               DAG.getConstant(0, T), Node->getOperand(2));
7574   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7575                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7576                        Node->getOperand(0),
7577                        Node->getOperand(1), negOp,
7578                        cast<AtomicSDNode>(Node)->getSrcValue(),
7579                        cast<AtomicSDNode>(Node)->getAlignment());
7580 }
7581
7582 /// LowerOperation - Provide custom lowering hooks for some operations.
7583 ///
7584 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7585   switch (Op.getOpcode()) {
7586   default: llvm_unreachable("Should not custom lower this!");
7587   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7588   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7589   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7590   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7591   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7592   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7593   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7594   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7595   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7596   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7597   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7598   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7599   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7600   case ISD::SHL_PARTS:
7601   case ISD::SRA_PARTS:
7602   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7603   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7604   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7605   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7606   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7607   case ISD::FABS:               return LowerFABS(Op, DAG);
7608   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7609   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7610   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7611   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7612   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7613   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7614   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7615   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7616   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7617   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7618   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7619   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7620   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7621   case ISD::FRAME_TO_ARGS_OFFSET:
7622                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7623   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7624   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7625   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7626   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7627   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7628   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7629   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7630   case ISD::SADDO:
7631   case ISD::UADDO:
7632   case ISD::SSUBO:
7633   case ISD::USUBO:
7634   case ISD::SMULO:
7635   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7636   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7637   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
7638   }
7639 }
7640
7641 void X86TargetLowering::
7642 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7643                         SelectionDAG &DAG, unsigned NewOp) const {
7644   EVT T = Node->getValueType(0);
7645   DebugLoc dl = Node->getDebugLoc();
7646   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7647
7648   SDValue Chain = Node->getOperand(0);
7649   SDValue In1 = Node->getOperand(1);
7650   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7651                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7652   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7653                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7654   SDValue Ops[] = { Chain, In1, In2L, In2H };
7655   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7656   SDValue Result =
7657     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7658                             cast<MemSDNode>(Node)->getMemOperand());
7659   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7660   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7661   Results.push_back(Result.getValue(2));
7662 }
7663
7664 /// ReplaceNodeResults - Replace a node with an illegal result type
7665 /// with a new node built out of custom code.
7666 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7667                                            SmallVectorImpl<SDValue>&Results,
7668                                            SelectionDAG &DAG) const {
7669   DebugLoc dl = N->getDebugLoc();
7670   switch (N->getOpcode()) {
7671   default:
7672     assert(false && "Do not know how to custom type legalize this operation!");
7673     return;
7674   case ISD::FP_TO_SINT: {
7675     std::pair<SDValue,SDValue> Vals =
7676         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7677     SDValue FIST = Vals.first, StackSlot = Vals.second;
7678     if (FIST.getNode() != 0) {
7679       EVT VT = N->getValueType(0);
7680       // Return a load from the stack slot.
7681       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7682                                     false, false, 0));
7683     }
7684     return;
7685   }
7686   case ISD::READCYCLECOUNTER: {
7687     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7688     SDValue TheChain = N->getOperand(0);
7689     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7690     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7691                                      rd.getValue(1));
7692     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7693                                      eax.getValue(2));
7694     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7695     SDValue Ops[] = { eax, edx };
7696     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7697     Results.push_back(edx.getValue(1));
7698     return;
7699   }
7700   case ISD::ATOMIC_CMP_SWAP: {
7701     EVT T = N->getValueType(0);
7702     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7703     SDValue cpInL, cpInH;
7704     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7705                         DAG.getConstant(0, MVT::i32));
7706     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7707                         DAG.getConstant(1, MVT::i32));
7708     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7709     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7710                              cpInL.getValue(1));
7711     SDValue swapInL, swapInH;
7712     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7713                           DAG.getConstant(0, MVT::i32));
7714     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7715                           DAG.getConstant(1, MVT::i32));
7716     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7717                                cpInH.getValue(1));
7718     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7719                                swapInL.getValue(1));
7720     SDValue Ops[] = { swapInH.getValue(0),
7721                       N->getOperand(1),
7722                       swapInH.getValue(1) };
7723     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7724     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7725     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7726                                         MVT::i32, Result.getValue(1));
7727     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7728                                         MVT::i32, cpOutL.getValue(2));
7729     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7730     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7731     Results.push_back(cpOutH.getValue(1));
7732     return;
7733   }
7734   case ISD::ATOMIC_LOAD_ADD:
7735     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7736     return;
7737   case ISD::ATOMIC_LOAD_AND:
7738     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7739     return;
7740   case ISD::ATOMIC_LOAD_NAND:
7741     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7742     return;
7743   case ISD::ATOMIC_LOAD_OR:
7744     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7745     return;
7746   case ISD::ATOMIC_LOAD_SUB:
7747     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7748     return;
7749   case ISD::ATOMIC_LOAD_XOR:
7750     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7751     return;
7752   case ISD::ATOMIC_SWAP:
7753     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7754     return;
7755   }
7756 }
7757
7758 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7759   switch (Opcode) {
7760   default: return NULL;
7761   case X86ISD::BSF:                return "X86ISD::BSF";
7762   case X86ISD::BSR:                return "X86ISD::BSR";
7763   case X86ISD::SHLD:               return "X86ISD::SHLD";
7764   case X86ISD::SHRD:               return "X86ISD::SHRD";
7765   case X86ISD::FAND:               return "X86ISD::FAND";
7766   case X86ISD::FOR:                return "X86ISD::FOR";
7767   case X86ISD::FXOR:               return "X86ISD::FXOR";
7768   case X86ISD::FSRL:               return "X86ISD::FSRL";
7769   case X86ISD::FILD:               return "X86ISD::FILD";
7770   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7771   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7772   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7773   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7774   case X86ISD::FLD:                return "X86ISD::FLD";
7775   case X86ISD::FST:                return "X86ISD::FST";
7776   case X86ISD::CALL:               return "X86ISD::CALL";
7777   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7778   case X86ISD::BT:                 return "X86ISD::BT";
7779   case X86ISD::CMP:                return "X86ISD::CMP";
7780   case X86ISD::COMI:               return "X86ISD::COMI";
7781   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7782   case X86ISD::SETCC:              return "X86ISD::SETCC";
7783   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7784   case X86ISD::CMOV:               return "X86ISD::CMOV";
7785   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7786   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7787   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7788   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7789   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7790   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7791   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7792   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7793   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7794   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7795   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7796   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7797   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7798   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7799   case X86ISD::FMAX:               return "X86ISD::FMAX";
7800   case X86ISD::FMIN:               return "X86ISD::FMIN";
7801   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7802   case X86ISD::FRCP:               return "X86ISD::FRCP";
7803   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7804   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
7805   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7806   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7807   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7808   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7809   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7810   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7811   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7812   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7813   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7814   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7815   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7816   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7817   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7818   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7819   case X86ISD::VSHL:               return "X86ISD::VSHL";
7820   case X86ISD::VSRL:               return "X86ISD::VSRL";
7821   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7822   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7823   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7824   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7825   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7826   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7827   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7828   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7829   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7830   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7831   case X86ISD::ADD:                return "X86ISD::ADD";
7832   case X86ISD::SUB:                return "X86ISD::SUB";
7833   case X86ISD::SMUL:               return "X86ISD::SMUL";
7834   case X86ISD::UMUL:               return "X86ISD::UMUL";
7835   case X86ISD::INC:                return "X86ISD::INC";
7836   case X86ISD::DEC:                return "X86ISD::DEC";
7837   case X86ISD::OR:                 return "X86ISD::OR";
7838   case X86ISD::XOR:                return "X86ISD::XOR";
7839   case X86ISD::AND:                return "X86ISD::AND";
7840   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7841   case X86ISD::PTEST:              return "X86ISD::PTEST";
7842   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7843   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7844   }
7845 }
7846
7847 // isLegalAddressingMode - Return true if the addressing mode represented
7848 // by AM is legal for this target, for a load/store of the specified type.
7849 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7850                                               const Type *Ty) const {
7851   // X86 supports extremely general addressing modes.
7852   CodeModel::Model M = getTargetMachine().getCodeModel();
7853
7854   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7855   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7856     return false;
7857
7858   if (AM.BaseGV) {
7859     unsigned GVFlags =
7860       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7861
7862     // If a reference to this global requires an extra load, we can't fold it.
7863     if (isGlobalStubReference(GVFlags))
7864       return false;
7865
7866     // If BaseGV requires a register for the PIC base, we cannot also have a
7867     // BaseReg specified.
7868     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7869       return false;
7870
7871     // If lower 4G is not available, then we must use rip-relative addressing.
7872     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7873       return false;
7874   }
7875
7876   switch (AM.Scale) {
7877   case 0:
7878   case 1:
7879   case 2:
7880   case 4:
7881   case 8:
7882     // These scales always work.
7883     break;
7884   case 3:
7885   case 5:
7886   case 9:
7887     // These scales are formed with basereg+scalereg.  Only accept if there is
7888     // no basereg yet.
7889     if (AM.HasBaseReg)
7890       return false;
7891     break;
7892   default:  // Other stuff never works.
7893     return false;
7894   }
7895
7896   return true;
7897 }
7898
7899
7900 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7901   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7902     return false;
7903   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7904   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7905   if (NumBits1 <= NumBits2)
7906     return false;
7907   return true;
7908 }
7909
7910 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7911   if (!VT1.isInteger() || !VT2.isInteger())
7912     return false;
7913   unsigned NumBits1 = VT1.getSizeInBits();
7914   unsigned NumBits2 = VT2.getSizeInBits();
7915   if (NumBits1 <= NumBits2)
7916     return false;
7917   return true;
7918 }
7919
7920 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7921   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7922   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7923 }
7924
7925 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7926   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7927   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7928 }
7929
7930 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7931   // i16 instructions are longer (0x66 prefix) and potentially slower.
7932   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7933 }
7934
7935 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7936 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7937 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7938 /// are assumed to be legal.
7939 bool
7940 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7941                                       EVT VT) const {
7942   // Very little shuffling can be done for 64-bit vectors right now.
7943   if (VT.getSizeInBits() == 64)
7944     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7945
7946   // FIXME: pshufb, blends, shifts.
7947   return (VT.getVectorNumElements() == 2 ||
7948           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7949           isMOVLMask(M, VT) ||
7950           isSHUFPMask(M, VT) ||
7951           isPSHUFDMask(M, VT) ||
7952           isPSHUFHWMask(M, VT) ||
7953           isPSHUFLWMask(M, VT) ||
7954           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7955           isUNPCKLMask(M, VT) ||
7956           isUNPCKHMask(M, VT) ||
7957           isUNPCKL_v_undef_Mask(M, VT) ||
7958           isUNPCKH_v_undef_Mask(M, VT));
7959 }
7960
7961 bool
7962 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7963                                           EVT VT) const {
7964   unsigned NumElts = VT.getVectorNumElements();
7965   // FIXME: This collection of masks seems suspect.
7966   if (NumElts == 2)
7967     return true;
7968   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7969     return (isMOVLMask(Mask, VT)  ||
7970             isCommutedMOVLMask(Mask, VT, true) ||
7971             isSHUFPMask(Mask, VT) ||
7972             isCommutedSHUFPMask(Mask, VT));
7973   }
7974   return false;
7975 }
7976
7977 //===----------------------------------------------------------------------===//
7978 //                           X86 Scheduler Hooks
7979 //===----------------------------------------------------------------------===//
7980
7981 // private utility function
7982 MachineBasicBlock *
7983 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7984                                                        MachineBasicBlock *MBB,
7985                                                        unsigned regOpc,
7986                                                        unsigned immOpc,
7987                                                        unsigned LoadOpc,
7988                                                        unsigned CXchgOpc,
7989                                                        unsigned copyOpc,
7990                                                        unsigned notOpc,
7991                                                        unsigned EAXreg,
7992                                                        TargetRegisterClass *RC,
7993                                                        bool invSrc) const {
7994   // For the atomic bitwise operator, we generate
7995   //   thisMBB:
7996   //   newMBB:
7997   //     ld  t1 = [bitinstr.addr]
7998   //     op  t2 = t1, [bitinstr.val]
7999   //     mov EAX = t1
8000   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8001   //     bz  newMBB
8002   //     fallthrough -->nextMBB
8003   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8004   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8005   MachineFunction::iterator MBBIter = MBB;
8006   ++MBBIter;
8007
8008   /// First build the CFG
8009   MachineFunction *F = MBB->getParent();
8010   MachineBasicBlock *thisMBB = MBB;
8011   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8012   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8013   F->insert(MBBIter, newMBB);
8014   F->insert(MBBIter, nextMBB);
8015
8016   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8017   nextMBB->splice(nextMBB->begin(), thisMBB,
8018                   llvm::next(MachineBasicBlock::iterator(bInstr)),
8019                   thisMBB->end());
8020   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8021
8022   // Update thisMBB to fall through to newMBB
8023   thisMBB->addSuccessor(newMBB);
8024
8025   // newMBB jumps to itself and fall through to nextMBB
8026   newMBB->addSuccessor(nextMBB);
8027   newMBB->addSuccessor(newMBB);
8028
8029   // Insert instructions into newMBB based on incoming instruction
8030   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8031          "unexpected number of operands");
8032   DebugLoc dl = bInstr->getDebugLoc();
8033   MachineOperand& destOper = bInstr->getOperand(0);
8034   MachineOperand* argOpers[2 + X86AddrNumOperands];
8035   int numArgs = bInstr->getNumOperands() - 1;
8036   for (int i=0; i < numArgs; ++i)
8037     argOpers[i] = &bInstr->getOperand(i+1);
8038
8039   // x86 address has 4 operands: base, index, scale, and displacement
8040   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8041   int valArgIndx = lastAddrIndx + 1;
8042
8043   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8044   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8045   for (int i=0; i <= lastAddrIndx; ++i)
8046     (*MIB).addOperand(*argOpers[i]);
8047
8048   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8049   if (invSrc) {
8050     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8051   }
8052   else
8053     tt = t1;
8054
8055   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8056   assert((argOpers[valArgIndx]->isReg() ||
8057           argOpers[valArgIndx]->isImm()) &&
8058          "invalid operand");
8059   if (argOpers[valArgIndx]->isReg())
8060     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8061   else
8062     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8063   MIB.addReg(tt);
8064   (*MIB).addOperand(*argOpers[valArgIndx]);
8065
8066   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8067   MIB.addReg(t1);
8068
8069   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8070   for (int i=0; i <= lastAddrIndx; ++i)
8071     (*MIB).addOperand(*argOpers[i]);
8072   MIB.addReg(t2);
8073   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8074   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8075                     bInstr->memoperands_end());
8076
8077   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8078   MIB.addReg(EAXreg);
8079
8080   // insert branch
8081   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8082
8083   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
8084   return nextMBB;
8085 }
8086
8087 // private utility function:  64 bit atomics on 32 bit host.
8088 MachineBasicBlock *
8089 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8090                                                        MachineBasicBlock *MBB,
8091                                                        unsigned regOpcL,
8092                                                        unsigned regOpcH,
8093                                                        unsigned immOpcL,
8094                                                        unsigned immOpcH,
8095                                                        bool invSrc) const {
8096   // For the atomic bitwise operator, we generate
8097   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8098   //     ld t1,t2 = [bitinstr.addr]
8099   //   newMBB:
8100   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8101   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8102   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8103   //     mov ECX, EBX <- t5, t6
8104   //     mov EAX, EDX <- t1, t2
8105   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8106   //     mov t3, t4 <- EAX, EDX
8107   //     bz  newMBB
8108   //     result in out1, out2
8109   //     fallthrough -->nextMBB
8110
8111   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8112   const unsigned LoadOpc = X86::MOV32rm;
8113   const unsigned copyOpc = X86::MOV32rr;
8114   const unsigned NotOpc = X86::NOT32r;
8115   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8116   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8117   MachineFunction::iterator MBBIter = MBB;
8118   ++MBBIter;
8119
8120   /// First build the CFG
8121   MachineFunction *F = MBB->getParent();
8122   MachineBasicBlock *thisMBB = MBB;
8123   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8124   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8125   F->insert(MBBIter, newMBB);
8126   F->insert(MBBIter, nextMBB);
8127
8128   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8129   nextMBB->splice(nextMBB->begin(), thisMBB,
8130                   llvm::next(MachineBasicBlock::iterator(bInstr)),
8131                   thisMBB->end());
8132   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8133
8134   // Update thisMBB to fall through to newMBB
8135   thisMBB->addSuccessor(newMBB);
8136
8137   // newMBB jumps to itself and fall through to nextMBB
8138   newMBB->addSuccessor(nextMBB);
8139   newMBB->addSuccessor(newMBB);
8140
8141   DebugLoc dl = bInstr->getDebugLoc();
8142   // Insert instructions into newMBB based on incoming instruction
8143   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8144   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8145          "unexpected number of operands");
8146   MachineOperand& dest1Oper = bInstr->getOperand(0);
8147   MachineOperand& dest2Oper = bInstr->getOperand(1);
8148   MachineOperand* argOpers[2 + X86AddrNumOperands];
8149   for (int i=0; i < 2 + X86AddrNumOperands; ++i) {
8150     argOpers[i] = &bInstr->getOperand(i+2);
8151
8152     // We use some of the operands multiple times, so conservatively just
8153     // clear any kill flags that might be present.
8154     if (argOpers[i]->isReg() && argOpers[i]->isUse())
8155       argOpers[i]->setIsKill(false);
8156   }
8157
8158   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8159   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8160
8161   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8162   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8163   for (int i=0; i <= lastAddrIndx; ++i)
8164     (*MIB).addOperand(*argOpers[i]);
8165   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8166   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8167   // add 4 to displacement.
8168   for (int i=0; i <= lastAddrIndx-2; ++i)
8169     (*MIB).addOperand(*argOpers[i]);
8170   MachineOperand newOp3 = *(argOpers[3]);
8171   if (newOp3.isImm())
8172     newOp3.setImm(newOp3.getImm()+4);
8173   else
8174     newOp3.setOffset(newOp3.getOffset()+4);
8175   (*MIB).addOperand(newOp3);
8176   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8177
8178   // t3/4 are defined later, at the bottom of the loop
8179   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8180   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8181   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8182     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8183   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8184     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8185
8186   // The subsequent operations should be using the destination registers of
8187   //the PHI instructions.
8188   if (invSrc) {
8189     t1 = F->getRegInfo().createVirtualRegister(RC);
8190     t2 = F->getRegInfo().createVirtualRegister(RC);
8191     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8192     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8193   } else {
8194     t1 = dest1Oper.getReg();
8195     t2 = dest2Oper.getReg();
8196   }
8197
8198   int valArgIndx = lastAddrIndx + 1;
8199   assert((argOpers[valArgIndx]->isReg() ||
8200           argOpers[valArgIndx]->isImm()) &&
8201          "invalid operand");
8202   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8203   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8204   if (argOpers[valArgIndx]->isReg())
8205     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8206   else
8207     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8208   if (regOpcL != X86::MOV32rr)
8209     MIB.addReg(t1);
8210   (*MIB).addOperand(*argOpers[valArgIndx]);
8211   assert(argOpers[valArgIndx + 1]->isReg() ==
8212          argOpers[valArgIndx]->isReg());
8213   assert(argOpers[valArgIndx + 1]->isImm() ==
8214          argOpers[valArgIndx]->isImm());
8215   if (argOpers[valArgIndx + 1]->isReg())
8216     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8217   else
8218     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8219   if (regOpcH != X86::MOV32rr)
8220     MIB.addReg(t2);
8221   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8222
8223   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8224   MIB.addReg(t1);
8225   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8226   MIB.addReg(t2);
8227
8228   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8229   MIB.addReg(t5);
8230   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8231   MIB.addReg(t6);
8232
8233   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8234   for (int i=0; i <= lastAddrIndx; ++i)
8235     (*MIB).addOperand(*argOpers[i]);
8236
8237   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8238   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8239                     bInstr->memoperands_end());
8240
8241   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8242   MIB.addReg(X86::EAX);
8243   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8244   MIB.addReg(X86::EDX);
8245
8246   // insert branch
8247   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8248
8249   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
8250   return nextMBB;
8251 }
8252
8253 // private utility function
8254 MachineBasicBlock *
8255 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8256                                                       MachineBasicBlock *MBB,
8257                                                       unsigned cmovOpc) const {
8258   // For the atomic min/max operator, we generate
8259   //   thisMBB:
8260   //   newMBB:
8261   //     ld t1 = [min/max.addr]
8262   //     mov t2 = [min/max.val]
8263   //     cmp  t1, t2
8264   //     cmov[cond] t2 = t1
8265   //     mov EAX = t1
8266   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8267   //     bz   newMBB
8268   //     fallthrough -->nextMBB
8269   //
8270   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8271   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8272   MachineFunction::iterator MBBIter = MBB;
8273   ++MBBIter;
8274
8275   /// First build the CFG
8276   MachineFunction *F = MBB->getParent();
8277   MachineBasicBlock *thisMBB = MBB;
8278   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8279   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8280   F->insert(MBBIter, newMBB);
8281   F->insert(MBBIter, nextMBB);
8282
8283   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8284   nextMBB->splice(nextMBB->begin(), thisMBB,
8285                   llvm::next(MachineBasicBlock::iterator(mInstr)),
8286                   thisMBB->end());
8287   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8288
8289   // Update thisMBB to fall through to newMBB
8290   thisMBB->addSuccessor(newMBB);
8291
8292   // newMBB jumps to newMBB and fall through to nextMBB
8293   newMBB->addSuccessor(nextMBB);
8294   newMBB->addSuccessor(newMBB);
8295
8296   DebugLoc dl = mInstr->getDebugLoc();
8297   // Insert instructions into newMBB based on incoming instruction
8298   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8299          "unexpected number of operands");
8300   MachineOperand& destOper = mInstr->getOperand(0);
8301   MachineOperand* argOpers[2 + X86AddrNumOperands];
8302   int numArgs = mInstr->getNumOperands() - 1;
8303   for (int i=0; i < numArgs; ++i)
8304     argOpers[i] = &mInstr->getOperand(i+1);
8305
8306   // x86 address has 4 operands: base, index, scale, and displacement
8307   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8308   int valArgIndx = lastAddrIndx + 1;
8309
8310   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8311   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8312   for (int i=0; i <= lastAddrIndx; ++i)
8313     (*MIB).addOperand(*argOpers[i]);
8314
8315   // We only support register and immediate values
8316   assert((argOpers[valArgIndx]->isReg() ||
8317           argOpers[valArgIndx]->isImm()) &&
8318          "invalid operand");
8319
8320   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8321   if (argOpers[valArgIndx]->isReg())
8322     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8323   else
8324     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8325   (*MIB).addOperand(*argOpers[valArgIndx]);
8326
8327   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8328   MIB.addReg(t1);
8329
8330   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8331   MIB.addReg(t1);
8332   MIB.addReg(t2);
8333
8334   // Generate movc
8335   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8336   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8337   MIB.addReg(t2);
8338   MIB.addReg(t1);
8339
8340   // Cmp and exchange if none has modified the memory location
8341   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8342   for (int i=0; i <= lastAddrIndx; ++i)
8343     (*MIB).addOperand(*argOpers[i]);
8344   MIB.addReg(t3);
8345   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8346   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8347                     mInstr->memoperands_end());
8348
8349   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8350   MIB.addReg(X86::EAX);
8351
8352   // insert branch
8353   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8354
8355   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
8356   return nextMBB;
8357 }
8358
8359 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8360 // all of this code can be replaced with that in the .td file.
8361 MachineBasicBlock *
8362 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8363                             unsigned numArgs, bool memArg) const {
8364
8365   DebugLoc dl = MI->getDebugLoc();
8366   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8367
8368   unsigned Opc;
8369   if (memArg)
8370     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8371   else
8372     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8373
8374   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8375
8376   for (unsigned i = 0; i < numArgs; ++i) {
8377     MachineOperand &Op = MI->getOperand(i+1);
8378
8379     if (!(Op.isReg() && Op.isImplicit()))
8380       MIB.addOperand(Op);
8381   }
8382
8383   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8384     .addReg(X86::XMM0);
8385
8386   MI->eraseFromParent();
8387
8388   return BB;
8389 }
8390
8391 MachineBasicBlock *
8392 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8393                                                  MachineInstr *MI,
8394                                                  MachineBasicBlock *MBB) const {
8395   // Emit code to save XMM registers to the stack. The ABI says that the
8396   // number of registers to save is given in %al, so it's theoretically
8397   // possible to do an indirect jump trick to avoid saving all of them,
8398   // however this code takes a simpler approach and just executes all
8399   // of the stores if %al is non-zero. It's less code, and it's probably
8400   // easier on the hardware branch predictor, and stores aren't all that
8401   // expensive anyway.
8402
8403   // Create the new basic blocks. One block contains all the XMM stores,
8404   // and one block is the final destination regardless of whether any
8405   // stores were performed.
8406   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8407   MachineFunction *F = MBB->getParent();
8408   MachineFunction::iterator MBBIter = MBB;
8409   ++MBBIter;
8410   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8411   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8412   F->insert(MBBIter, XMMSaveMBB);
8413   F->insert(MBBIter, EndMBB);
8414
8415   // Transfer the remainder of MBB and its successor edges to EndMBB.
8416   EndMBB->splice(EndMBB->begin(), MBB,
8417                  llvm::next(MachineBasicBlock::iterator(MI)),
8418                  MBB->end());
8419   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
8420
8421   // The original block will now fall through to the XMM save block.
8422   MBB->addSuccessor(XMMSaveMBB);
8423   // The XMMSaveMBB will fall through to the end block.
8424   XMMSaveMBB->addSuccessor(EndMBB);
8425
8426   // Now add the instructions.
8427   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8428   DebugLoc DL = MI->getDebugLoc();
8429
8430   unsigned CountReg = MI->getOperand(0).getReg();
8431   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8432   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8433
8434   if (!Subtarget->isTargetWin64()) {
8435     // If %al is 0, branch around the XMM save block.
8436     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8437     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8438     MBB->addSuccessor(EndMBB);
8439   }
8440
8441   // In the XMM save block, save all the XMM argument registers.
8442   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8443     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8444     MachineMemOperand *MMO =
8445       F->getMachineMemOperand(
8446         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8447         MachineMemOperand::MOStore, Offset,
8448         /*Size=*/16, /*Align=*/16);
8449     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8450       .addFrameIndex(RegSaveFrameIndex)
8451       .addImm(/*Scale=*/1)
8452       .addReg(/*IndexReg=*/0)
8453       .addImm(/*Disp=*/Offset)
8454       .addReg(/*Segment=*/0)
8455       .addReg(MI->getOperand(i).getReg())
8456       .addMemOperand(MMO);
8457   }
8458
8459   MI->eraseFromParent();   // The pseudo instruction is gone now.
8460
8461   return EndMBB;
8462 }
8463
8464 MachineBasicBlock *
8465 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8466                                      MachineBasicBlock *BB) const {
8467   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8468   DebugLoc DL = MI->getDebugLoc();
8469
8470   // To "insert" a SELECT_CC instruction, we actually have to insert the
8471   // diamond control-flow pattern.  The incoming instruction knows the
8472   // destination vreg to set, the condition code register to branch on, the
8473   // true/false values to select between, and a branch opcode to use.
8474   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8475   MachineFunction::iterator It = BB;
8476   ++It;
8477
8478   //  thisMBB:
8479   //  ...
8480   //   TrueVal = ...
8481   //   cmpTY ccX, r1, r2
8482   //   bCC copy1MBB
8483   //   fallthrough --> copy0MBB
8484   MachineBasicBlock *thisMBB = BB;
8485   MachineFunction *F = BB->getParent();
8486   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8487   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8488   F->insert(It, copy0MBB);
8489   F->insert(It, sinkMBB);
8490
8491   // If the EFLAGS register isn't dead in the terminator, then claim that it's
8492   // live into the sink and copy blocks.
8493   const MachineFunction *MF = BB->getParent();
8494   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
8495   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
8496
8497   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
8498     const MachineOperand &MO = MI->getOperand(I);
8499     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
8500     unsigned Reg = MO.getReg();
8501     if (Reg != X86::EFLAGS) continue;
8502     copy0MBB->addLiveIn(Reg);
8503     sinkMBB->addLiveIn(Reg);
8504   }
8505
8506   // Transfer the remainder of BB and its successor edges to sinkMBB.
8507   sinkMBB->splice(sinkMBB->begin(), BB,
8508                   llvm::next(MachineBasicBlock::iterator(MI)),
8509                   BB->end());
8510   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8511
8512   // Add the true and fallthrough blocks as its successors.
8513   BB->addSuccessor(copy0MBB);
8514   BB->addSuccessor(sinkMBB);
8515
8516   // Create the conditional branch instruction.
8517   unsigned Opc =
8518     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8519   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8520
8521   //  copy0MBB:
8522   //   %FalseValue = ...
8523   //   # fallthrough to sinkMBB
8524   copy0MBB->addSuccessor(sinkMBB);
8525
8526   //  sinkMBB:
8527   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8528   //  ...
8529   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8530           TII->get(X86::PHI), MI->getOperand(0).getReg())
8531     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8532     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8533
8534   MI->eraseFromParent();   // The pseudo instruction is gone now.
8535   return sinkMBB;
8536 }
8537
8538 MachineBasicBlock *
8539 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8540                                           MachineBasicBlock *BB) const {
8541   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8542   DebugLoc DL = MI->getDebugLoc();
8543
8544   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8545   // non-trivial part is impdef of ESP.
8546   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8547   // mingw-w64.
8548
8549   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
8550     .addExternalSymbol("_alloca")
8551     .addReg(X86::EAX, RegState::Implicit)
8552     .addReg(X86::ESP, RegState::Implicit)
8553     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8554     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8555
8556   MI->eraseFromParent();   // The pseudo instruction is gone now.
8557   return BB;
8558 }
8559
8560 MachineBasicBlock *
8561 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
8562                                       MachineBasicBlock *BB) const {
8563   // This is pretty easy.  We're taking the value that we received from
8564   // our load from the relocation, sticking it in either RDI (x86-64)
8565   // or EAX and doing an indirect call.  The return value will then
8566   // be in the normal return register.
8567   const X86InstrInfo *TII 
8568     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
8569   DebugLoc DL = MI->getDebugLoc();
8570   MachineFunction *F = BB->getParent();
8571   
8572   assert(MI->getOperand(3).isGlobal() && "This should be a global");
8573   
8574   if (Subtarget->is64Bit()) {
8575     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8576                                       TII->get(X86::MOV64rm), X86::RDI)
8577     .addReg(X86::RIP)
8578     .addImm(0).addReg(0)
8579     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8580                       MI->getOperand(3).getTargetFlags())
8581     .addReg(0);
8582     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
8583     addDirectMem(MIB, X86::RDI).addReg(0);
8584   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
8585     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8586                                       TII->get(X86::MOV32rm), X86::EAX)
8587     .addReg(0)
8588     .addImm(0).addReg(0)
8589     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8590                       MI->getOperand(3).getTargetFlags())
8591     .addReg(0);
8592     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
8593     addDirectMem(MIB, X86::EAX).addReg(0);
8594   } else {
8595     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8596                                       TII->get(X86::MOV32rm), X86::EAX)
8597     .addReg(TII->getGlobalBaseReg(F))
8598     .addImm(0).addReg(0)
8599     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8600                       MI->getOperand(3).getTargetFlags())
8601     .addReg(0);
8602     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
8603     addDirectMem(MIB, X86::EAX).addReg(0);
8604   }
8605   
8606   MI->eraseFromParent(); // The pseudo instruction is gone now.
8607   return BB;
8608 }
8609
8610 MachineBasicBlock *
8611 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8612                                                MachineBasicBlock *BB) const {
8613   switch (MI->getOpcode()) {
8614   default: assert(false && "Unexpected instr type to insert");
8615   case X86::MINGW_ALLOCA:
8616     return EmitLoweredMingwAlloca(MI, BB);
8617   case X86::TLSCall_32:
8618   case X86::TLSCall_64:
8619     return EmitLoweredTLSCall(MI, BB);
8620   case X86::CMOV_GR8:
8621   case X86::CMOV_V1I64:
8622   case X86::CMOV_FR32:
8623   case X86::CMOV_FR64:
8624   case X86::CMOV_V4F32:
8625   case X86::CMOV_V2F64:
8626   case X86::CMOV_V2I64:
8627   case X86::CMOV_GR16:
8628   case X86::CMOV_GR32:
8629   case X86::CMOV_RFP32:
8630   case X86::CMOV_RFP64:
8631   case X86::CMOV_RFP80:
8632     return EmitLoweredSelect(MI, BB);
8633
8634   case X86::FP32_TO_INT16_IN_MEM:
8635   case X86::FP32_TO_INT32_IN_MEM:
8636   case X86::FP32_TO_INT64_IN_MEM:
8637   case X86::FP64_TO_INT16_IN_MEM:
8638   case X86::FP64_TO_INT32_IN_MEM:
8639   case X86::FP64_TO_INT64_IN_MEM:
8640   case X86::FP80_TO_INT16_IN_MEM:
8641   case X86::FP80_TO_INT32_IN_MEM:
8642   case X86::FP80_TO_INT64_IN_MEM: {
8643     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8644     DebugLoc DL = MI->getDebugLoc();
8645
8646     // Change the floating point control register to use "round towards zero"
8647     // mode when truncating to an integer value.
8648     MachineFunction *F = BB->getParent();
8649     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8650     addFrameReference(BuildMI(*BB, MI, DL,
8651                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
8652
8653     // Load the old value of the high byte of the control word...
8654     unsigned OldCW =
8655       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8656     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
8657                       CWFrameIdx);
8658
8659     // Set the high part to be round to zero...
8660     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8661       .addImm(0xC7F);
8662
8663     // Reload the modified control word now...
8664     addFrameReference(BuildMI(*BB, MI, DL,
8665                               TII->get(X86::FLDCW16m)), CWFrameIdx);
8666
8667     // Restore the memory image of control word to original value
8668     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8669       .addReg(OldCW);
8670
8671     // Get the X86 opcode to use.
8672     unsigned Opc;
8673     switch (MI->getOpcode()) {
8674     default: llvm_unreachable("illegal opcode!");
8675     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8676     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8677     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8678     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8679     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8680     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8681     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8682     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8683     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8684     }
8685
8686     X86AddressMode AM;
8687     MachineOperand &Op = MI->getOperand(0);
8688     if (Op.isReg()) {
8689       AM.BaseType = X86AddressMode::RegBase;
8690       AM.Base.Reg = Op.getReg();
8691     } else {
8692       AM.BaseType = X86AddressMode::FrameIndexBase;
8693       AM.Base.FrameIndex = Op.getIndex();
8694     }
8695     Op = MI->getOperand(1);
8696     if (Op.isImm())
8697       AM.Scale = Op.getImm();
8698     Op = MI->getOperand(2);
8699     if (Op.isImm())
8700       AM.IndexReg = Op.getImm();
8701     Op = MI->getOperand(3);
8702     if (Op.isGlobal()) {
8703       AM.GV = Op.getGlobal();
8704     } else {
8705       AM.Disp = Op.getImm();
8706     }
8707     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
8708                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8709
8710     // Reload the original control word now.
8711     addFrameReference(BuildMI(*BB, MI, DL,
8712                               TII->get(X86::FLDCW16m)), CWFrameIdx);
8713
8714     MI->eraseFromParent();   // The pseudo instruction is gone now.
8715     return BB;
8716   }
8717     // String/text processing lowering.
8718   case X86::PCMPISTRM128REG:
8719     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8720   case X86::PCMPISTRM128MEM:
8721     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8722   case X86::PCMPESTRM128REG:
8723     return EmitPCMP(MI, BB, 5, false /* in mem */);
8724   case X86::PCMPESTRM128MEM:
8725     return EmitPCMP(MI, BB, 5, true /* in mem */);
8726
8727     // Atomic Lowering.
8728   case X86::ATOMAND32:
8729     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8730                                                X86::AND32ri, X86::MOV32rm,
8731                                                X86::LCMPXCHG32, X86::MOV32rr,
8732                                                X86::NOT32r, X86::EAX,
8733                                                X86::GR32RegisterClass);
8734   case X86::ATOMOR32:
8735     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8736                                                X86::OR32ri, X86::MOV32rm,
8737                                                X86::LCMPXCHG32, X86::MOV32rr,
8738                                                X86::NOT32r, X86::EAX,
8739                                                X86::GR32RegisterClass);
8740   case X86::ATOMXOR32:
8741     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8742                                                X86::XOR32ri, X86::MOV32rm,
8743                                                X86::LCMPXCHG32, X86::MOV32rr,
8744                                                X86::NOT32r, X86::EAX,
8745                                                X86::GR32RegisterClass);
8746   case X86::ATOMNAND32:
8747     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8748                                                X86::AND32ri, X86::MOV32rm,
8749                                                X86::LCMPXCHG32, X86::MOV32rr,
8750                                                X86::NOT32r, X86::EAX,
8751                                                X86::GR32RegisterClass, true);
8752   case X86::ATOMMIN32:
8753     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8754   case X86::ATOMMAX32:
8755     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8756   case X86::ATOMUMIN32:
8757     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8758   case X86::ATOMUMAX32:
8759     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8760
8761   case X86::ATOMAND16:
8762     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8763                                                X86::AND16ri, X86::MOV16rm,
8764                                                X86::LCMPXCHG16, X86::MOV16rr,
8765                                                X86::NOT16r, X86::AX,
8766                                                X86::GR16RegisterClass);
8767   case X86::ATOMOR16:
8768     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8769                                                X86::OR16ri, X86::MOV16rm,
8770                                                X86::LCMPXCHG16, X86::MOV16rr,
8771                                                X86::NOT16r, X86::AX,
8772                                                X86::GR16RegisterClass);
8773   case X86::ATOMXOR16:
8774     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8775                                                X86::XOR16ri, X86::MOV16rm,
8776                                                X86::LCMPXCHG16, X86::MOV16rr,
8777                                                X86::NOT16r, X86::AX,
8778                                                X86::GR16RegisterClass);
8779   case X86::ATOMNAND16:
8780     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8781                                                X86::AND16ri, X86::MOV16rm,
8782                                                X86::LCMPXCHG16, X86::MOV16rr,
8783                                                X86::NOT16r, X86::AX,
8784                                                X86::GR16RegisterClass, true);
8785   case X86::ATOMMIN16:
8786     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8787   case X86::ATOMMAX16:
8788     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8789   case X86::ATOMUMIN16:
8790     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8791   case X86::ATOMUMAX16:
8792     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8793
8794   case X86::ATOMAND8:
8795     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8796                                                X86::AND8ri, X86::MOV8rm,
8797                                                X86::LCMPXCHG8, X86::MOV8rr,
8798                                                X86::NOT8r, X86::AL,
8799                                                X86::GR8RegisterClass);
8800   case X86::ATOMOR8:
8801     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8802                                                X86::OR8ri, X86::MOV8rm,
8803                                                X86::LCMPXCHG8, X86::MOV8rr,
8804                                                X86::NOT8r, X86::AL,
8805                                                X86::GR8RegisterClass);
8806   case X86::ATOMXOR8:
8807     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8808                                                X86::XOR8ri, X86::MOV8rm,
8809                                                X86::LCMPXCHG8, X86::MOV8rr,
8810                                                X86::NOT8r, X86::AL,
8811                                                X86::GR8RegisterClass);
8812   case X86::ATOMNAND8:
8813     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8814                                                X86::AND8ri, X86::MOV8rm,
8815                                                X86::LCMPXCHG8, X86::MOV8rr,
8816                                                X86::NOT8r, X86::AL,
8817                                                X86::GR8RegisterClass, true);
8818   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8819   // This group is for 64-bit host.
8820   case X86::ATOMAND64:
8821     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8822                                                X86::AND64ri32, X86::MOV64rm,
8823                                                X86::LCMPXCHG64, X86::MOV64rr,
8824                                                X86::NOT64r, X86::RAX,
8825                                                X86::GR64RegisterClass);
8826   case X86::ATOMOR64:
8827     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8828                                                X86::OR64ri32, X86::MOV64rm,
8829                                                X86::LCMPXCHG64, X86::MOV64rr,
8830                                                X86::NOT64r, X86::RAX,
8831                                                X86::GR64RegisterClass);
8832   case X86::ATOMXOR64:
8833     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8834                                                X86::XOR64ri32, X86::MOV64rm,
8835                                                X86::LCMPXCHG64, X86::MOV64rr,
8836                                                X86::NOT64r, X86::RAX,
8837                                                X86::GR64RegisterClass);
8838   case X86::ATOMNAND64:
8839     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8840                                                X86::AND64ri32, X86::MOV64rm,
8841                                                X86::LCMPXCHG64, X86::MOV64rr,
8842                                                X86::NOT64r, X86::RAX,
8843                                                X86::GR64RegisterClass, true);
8844   case X86::ATOMMIN64:
8845     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8846   case X86::ATOMMAX64:
8847     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8848   case X86::ATOMUMIN64:
8849     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8850   case X86::ATOMUMAX64:
8851     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8852
8853   // This group does 64-bit operations on a 32-bit host.
8854   case X86::ATOMAND6432:
8855     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8856                                                X86::AND32rr, X86::AND32rr,
8857                                                X86::AND32ri, X86::AND32ri,
8858                                                false);
8859   case X86::ATOMOR6432:
8860     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8861                                                X86::OR32rr, X86::OR32rr,
8862                                                X86::OR32ri, X86::OR32ri,
8863                                                false);
8864   case X86::ATOMXOR6432:
8865     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8866                                                X86::XOR32rr, X86::XOR32rr,
8867                                                X86::XOR32ri, X86::XOR32ri,
8868                                                false);
8869   case X86::ATOMNAND6432:
8870     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8871                                                X86::AND32rr, X86::AND32rr,
8872                                                X86::AND32ri, X86::AND32ri,
8873                                                true);
8874   case X86::ATOMADD6432:
8875     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8876                                                X86::ADD32rr, X86::ADC32rr,
8877                                                X86::ADD32ri, X86::ADC32ri,
8878                                                false);
8879   case X86::ATOMSUB6432:
8880     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8881                                                X86::SUB32rr, X86::SBB32rr,
8882                                                X86::SUB32ri, X86::SBB32ri,
8883                                                false);
8884   case X86::ATOMSWAP6432:
8885     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8886                                                X86::MOV32rr, X86::MOV32rr,
8887                                                X86::MOV32ri, X86::MOV32ri,
8888                                                false);
8889   case X86::VASTART_SAVE_XMM_REGS:
8890     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8891   }
8892 }
8893
8894 //===----------------------------------------------------------------------===//
8895 //                           X86 Optimization Hooks
8896 //===----------------------------------------------------------------------===//
8897
8898 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8899                                                        const APInt &Mask,
8900                                                        APInt &KnownZero,
8901                                                        APInt &KnownOne,
8902                                                        const SelectionDAG &DAG,
8903                                                        unsigned Depth) const {
8904   unsigned Opc = Op.getOpcode();
8905   assert((Opc >= ISD::BUILTIN_OP_END ||
8906           Opc == ISD::INTRINSIC_WO_CHAIN ||
8907           Opc == ISD::INTRINSIC_W_CHAIN ||
8908           Opc == ISD::INTRINSIC_VOID) &&
8909          "Should use MaskedValueIsZero if you don't know whether Op"
8910          " is a target node!");
8911
8912   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8913   switch (Opc) {
8914   default: break;
8915   case X86ISD::ADD:
8916   case X86ISD::SUB:
8917   case X86ISD::SMUL:
8918   case X86ISD::UMUL:
8919   case X86ISD::INC:
8920   case X86ISD::DEC:
8921   case X86ISD::OR:
8922   case X86ISD::XOR:
8923   case X86ISD::AND:
8924     // These nodes' second result is a boolean.
8925     if (Op.getResNo() == 0)
8926       break;
8927     // Fallthrough
8928   case X86ISD::SETCC:
8929     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8930                                        Mask.getBitWidth() - 1);
8931     break;
8932   }
8933 }
8934
8935 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8936 /// node is a GlobalAddress + offset.
8937 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8938                                        const GlobalValue* &GA,
8939                                        int64_t &Offset) const {
8940   if (N->getOpcode() == X86ISD::Wrapper) {
8941     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8942       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8943       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8944       return true;
8945     }
8946   }
8947   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8948 }
8949
8950 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8951 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8952 /// if the load addresses are consecutive, non-overlapping, and in the right
8953 /// order.
8954 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8955                                      const TargetLowering &TLI) {
8956   DebugLoc dl = N->getDebugLoc();
8957   EVT VT = N->getValueType(0);
8958   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8959
8960   if (VT.getSizeInBits() != 128)
8961     return SDValue();
8962
8963   SmallVector<SDValue, 16> Elts;
8964   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8965     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8966   
8967   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8968 }
8969
8970 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8971 /// and convert it from being a bunch of shuffles and extracts to a simple
8972 /// store and scalar loads to extract the elements.
8973 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8974                                                 const TargetLowering &TLI) {
8975   SDValue InputVector = N->getOperand(0);
8976
8977   // Only operate on vectors of 4 elements, where the alternative shuffling
8978   // gets to be more expensive.
8979   if (InputVector.getValueType() != MVT::v4i32)
8980     return SDValue();
8981
8982   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8983   // single use which is a sign-extend or zero-extend, and all elements are
8984   // used.
8985   SmallVector<SDNode *, 4> Uses;
8986   unsigned ExtractedElements = 0;
8987   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8988        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8989     if (UI.getUse().getResNo() != InputVector.getResNo())
8990       return SDValue();
8991
8992     SDNode *Extract = *UI;
8993     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8994       return SDValue();
8995
8996     if (Extract->getValueType(0) != MVT::i32)
8997       return SDValue();
8998     if (!Extract->hasOneUse())
8999       return SDValue();
9000     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
9001         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
9002       return SDValue();
9003     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
9004       return SDValue();
9005
9006     // Record which element was extracted.
9007     ExtractedElements |=
9008       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
9009
9010     Uses.push_back(Extract);
9011   }
9012
9013   // If not all the elements were used, this may not be worthwhile.
9014   if (ExtractedElements != 15)
9015     return SDValue();
9016
9017   // Ok, we've now decided to do the transformation.
9018   DebugLoc dl = InputVector.getDebugLoc();
9019
9020   // Store the value to a temporary stack slot.
9021   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
9022   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
9023                             false, false, 0);
9024
9025   // Replace each use (extract) with a load of the appropriate element.
9026   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
9027        UE = Uses.end(); UI != UE; ++UI) {
9028     SDNode *Extract = *UI;
9029
9030     // Compute the element's address.
9031     SDValue Idx = Extract->getOperand(1);
9032     unsigned EltSize =
9033         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9034     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9035     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9036
9037     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
9038
9039     // Load the scalar.
9040     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
9041                           NULL, 0, false, false, 0);
9042
9043     // Replace the exact with the load.
9044     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9045   }
9046
9047   // The replacement was made in place; don't return anything.
9048   return SDValue();
9049 }
9050
9051 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9052 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9053                                     const X86Subtarget *Subtarget) {
9054   DebugLoc DL = N->getDebugLoc();
9055   SDValue Cond = N->getOperand(0);
9056   // Get the LHS/RHS of the select.
9057   SDValue LHS = N->getOperand(1);
9058   SDValue RHS = N->getOperand(2);
9059
9060   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9061   // instructions match the semantics of the common C idiom x<y?x:y but not
9062   // x<=y?x:y, because of how they handle negative zero (which can be
9063   // ignored in unsafe-math mode).
9064   if (Subtarget->hasSSE2() &&
9065       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9066       Cond.getOpcode() == ISD::SETCC) {
9067     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9068
9069     unsigned Opcode = 0;
9070     // Check for x CC y ? x : y.
9071     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9072         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9073       switch (CC) {
9074       default: break;
9075       case ISD::SETULT:
9076         // Converting this to a min would handle NaNs incorrectly, and swapping
9077         // the operands would cause it to handle comparisons between positive
9078         // and negative zero incorrectly.
9079         if (!FiniteOnlyFPMath() &&
9080             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9081           if (!UnsafeFPMath &&
9082               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9083             break;
9084           std::swap(LHS, RHS);
9085         }
9086         Opcode = X86ISD::FMIN;
9087         break;
9088       case ISD::SETOLE:
9089         // Converting this to a min would handle comparisons between positive
9090         // and negative zero incorrectly.
9091         if (!UnsafeFPMath &&
9092             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9093           break;
9094         Opcode = X86ISD::FMIN;
9095         break;
9096       case ISD::SETULE:
9097         // Converting this to a min would handle both negative zeros and NaNs
9098         // incorrectly, but we can swap the operands to fix both.
9099         std::swap(LHS, RHS);
9100       case ISD::SETOLT:
9101       case ISD::SETLT:
9102       case ISD::SETLE:
9103         Opcode = X86ISD::FMIN;
9104         break;
9105
9106       case ISD::SETOGE:
9107         // Converting this to a max would handle comparisons between positive
9108         // and negative zero incorrectly.
9109         if (!UnsafeFPMath &&
9110             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9111           break;
9112         Opcode = X86ISD::FMAX;
9113         break;
9114       case ISD::SETUGT:
9115         // Converting this to a max would handle NaNs incorrectly, and swapping
9116         // the operands would cause it to handle comparisons between positive
9117         // and negative zero incorrectly.
9118         if (!FiniteOnlyFPMath() &&
9119             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9120           if (!UnsafeFPMath &&
9121               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9122             break;
9123           std::swap(LHS, RHS);
9124         }
9125         Opcode = X86ISD::FMAX;
9126         break;
9127       case ISD::SETUGE:
9128         // Converting this to a max would handle both negative zeros and NaNs
9129         // incorrectly, but we can swap the operands to fix both.
9130         std::swap(LHS, RHS);
9131       case ISD::SETOGT:
9132       case ISD::SETGT:
9133       case ISD::SETGE:
9134         Opcode = X86ISD::FMAX;
9135         break;
9136       }
9137     // Check for x CC y ? y : x -- a min/max with reversed arms.
9138     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9139                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9140       switch (CC) {
9141       default: break;
9142       case ISD::SETOGE:
9143         // Converting this to a min would handle comparisons between positive
9144         // and negative zero incorrectly, and swapping the operands would
9145         // cause it to handle NaNs incorrectly.
9146         if (!UnsafeFPMath &&
9147             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9148           if (!FiniteOnlyFPMath() &&
9149               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9150             break;
9151           std::swap(LHS, RHS);
9152         }
9153         Opcode = X86ISD::FMIN;
9154         break;
9155       case ISD::SETUGT:
9156         // Converting this to a min would handle NaNs incorrectly.
9157         if (!UnsafeFPMath &&
9158             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9159           break;
9160         Opcode = X86ISD::FMIN;
9161         break;
9162       case ISD::SETUGE:
9163         // Converting this to a min would handle both negative zeros and NaNs
9164         // incorrectly, but we can swap the operands to fix both.
9165         std::swap(LHS, RHS);
9166       case ISD::SETOGT:
9167       case ISD::SETGT:
9168       case ISD::SETGE:
9169         Opcode = X86ISD::FMIN;
9170         break;
9171
9172       case ISD::SETULT:
9173         // Converting this to a max would handle NaNs incorrectly.
9174         if (!FiniteOnlyFPMath() &&
9175             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9176           break;
9177         Opcode = X86ISD::FMAX;
9178         break;
9179       case ISD::SETOLE:
9180         // Converting this to a max would handle comparisons between positive
9181         // and negative zero incorrectly, and swapping the operands would
9182         // cause it to handle NaNs incorrectly.
9183         if (!UnsafeFPMath &&
9184             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9185           if (!FiniteOnlyFPMath() &&
9186               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9187             break;
9188           std::swap(LHS, RHS);
9189         }
9190         Opcode = X86ISD::FMAX;
9191         break;
9192       case ISD::SETULE:
9193         // Converting this to a max would handle both negative zeros and NaNs
9194         // incorrectly, but we can swap the operands to fix both.
9195         std::swap(LHS, RHS);
9196       case ISD::SETOLT:
9197       case ISD::SETLT:
9198       case ISD::SETLE:
9199         Opcode = X86ISD::FMAX;
9200         break;
9201       }
9202     }
9203
9204     if (Opcode)
9205       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9206   }
9207
9208   // If this is a select between two integer constants, try to do some
9209   // optimizations.
9210   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9211     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9212       // Don't do this for crazy integer types.
9213       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9214         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9215         // so that TrueC (the true value) is larger than FalseC.
9216         bool NeedsCondInvert = false;
9217
9218         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9219             // Efficiently invertible.
9220             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9221              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9222               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9223           NeedsCondInvert = true;
9224           std::swap(TrueC, FalseC);
9225         }
9226
9227         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9228         if (FalseC->getAPIntValue() == 0 &&
9229             TrueC->getAPIntValue().isPowerOf2()) {
9230           if (NeedsCondInvert) // Invert the condition if needed.
9231             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9232                                DAG.getConstant(1, Cond.getValueType()));
9233
9234           // Zero extend the condition if needed.
9235           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9236
9237           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9238           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9239                              DAG.getConstant(ShAmt, MVT::i8));
9240         }
9241
9242         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9243         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9244           if (NeedsCondInvert) // Invert the condition if needed.
9245             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9246                                DAG.getConstant(1, Cond.getValueType()));
9247
9248           // Zero extend the condition if needed.
9249           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9250                              FalseC->getValueType(0), Cond);
9251           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9252                              SDValue(FalseC, 0));
9253         }
9254
9255         // Optimize cases that will turn into an LEA instruction.  This requires
9256         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9257         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9258           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9259           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9260
9261           bool isFastMultiplier = false;
9262           if (Diff < 10) {
9263             switch ((unsigned char)Diff) {
9264               default: break;
9265               case 1:  // result = add base, cond
9266               case 2:  // result = lea base(    , cond*2)
9267               case 3:  // result = lea base(cond, cond*2)
9268               case 4:  // result = lea base(    , cond*4)
9269               case 5:  // result = lea base(cond, cond*4)
9270               case 8:  // result = lea base(    , cond*8)
9271               case 9:  // result = lea base(cond, cond*8)
9272                 isFastMultiplier = true;
9273                 break;
9274             }
9275           }
9276
9277           if (isFastMultiplier) {
9278             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9279             if (NeedsCondInvert) // Invert the condition if needed.
9280               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9281                                  DAG.getConstant(1, Cond.getValueType()));
9282
9283             // Zero extend the condition if needed.
9284             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9285                                Cond);
9286             // Scale the condition by the difference.
9287             if (Diff != 1)
9288               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9289                                  DAG.getConstant(Diff, Cond.getValueType()));
9290
9291             // Add the base if non-zero.
9292             if (FalseC->getAPIntValue() != 0)
9293               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9294                                  SDValue(FalseC, 0));
9295             return Cond;
9296           }
9297         }
9298       }
9299   }
9300
9301   return SDValue();
9302 }
9303
9304 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9305 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9306                                   TargetLowering::DAGCombinerInfo &DCI) {
9307   DebugLoc DL = N->getDebugLoc();
9308
9309   // If the flag operand isn't dead, don't touch this CMOV.
9310   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9311     return SDValue();
9312
9313   // If this is a select between two integer constants, try to do some
9314   // optimizations.  Note that the operands are ordered the opposite of SELECT
9315   // operands.
9316   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9317     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9318       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9319       // larger than FalseC (the false value).
9320       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9321
9322       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9323         CC = X86::GetOppositeBranchCondition(CC);
9324         std::swap(TrueC, FalseC);
9325       }
9326
9327       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9328       // This is efficient for any integer data type (including i8/i16) and
9329       // shift amount.
9330       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9331         SDValue Cond = N->getOperand(3);
9332         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9333                            DAG.getConstant(CC, MVT::i8), Cond);
9334
9335         // Zero extend the condition if needed.
9336         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9337
9338         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9339         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9340                            DAG.getConstant(ShAmt, MVT::i8));
9341         if (N->getNumValues() == 2)  // Dead flag value?
9342           return DCI.CombineTo(N, Cond, SDValue());
9343         return Cond;
9344       }
9345
9346       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9347       // for any integer data type, including i8/i16.
9348       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9349         SDValue Cond = N->getOperand(3);
9350         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9351                            DAG.getConstant(CC, MVT::i8), Cond);
9352
9353         // Zero extend the condition if needed.
9354         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9355                            FalseC->getValueType(0), Cond);
9356         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9357                            SDValue(FalseC, 0));
9358
9359         if (N->getNumValues() == 2)  // Dead flag value?
9360           return DCI.CombineTo(N, Cond, SDValue());
9361         return Cond;
9362       }
9363
9364       // Optimize cases that will turn into an LEA instruction.  This requires
9365       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9366       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9367         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9368         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9369
9370         bool isFastMultiplier = false;
9371         if (Diff < 10) {
9372           switch ((unsigned char)Diff) {
9373           default: break;
9374           case 1:  // result = add base, cond
9375           case 2:  // result = lea base(    , cond*2)
9376           case 3:  // result = lea base(cond, cond*2)
9377           case 4:  // result = lea base(    , cond*4)
9378           case 5:  // result = lea base(cond, cond*4)
9379           case 8:  // result = lea base(    , cond*8)
9380           case 9:  // result = lea base(cond, cond*8)
9381             isFastMultiplier = true;
9382             break;
9383           }
9384         }
9385
9386         if (isFastMultiplier) {
9387           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9388           SDValue Cond = N->getOperand(3);
9389           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9390                              DAG.getConstant(CC, MVT::i8), Cond);
9391           // Zero extend the condition if needed.
9392           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9393                              Cond);
9394           // Scale the condition by the difference.
9395           if (Diff != 1)
9396             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9397                                DAG.getConstant(Diff, Cond.getValueType()));
9398
9399           // Add the base if non-zero.
9400           if (FalseC->getAPIntValue() != 0)
9401             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9402                                SDValue(FalseC, 0));
9403           if (N->getNumValues() == 2)  // Dead flag value?
9404             return DCI.CombineTo(N, Cond, SDValue());
9405           return Cond;
9406         }
9407       }
9408     }
9409   }
9410   return SDValue();
9411 }
9412
9413
9414 /// PerformMulCombine - Optimize a single multiply with constant into two
9415 /// in order to implement it with two cheaper instructions, e.g.
9416 /// LEA + SHL, LEA + LEA.
9417 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9418                                  TargetLowering::DAGCombinerInfo &DCI) {
9419   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9420     return SDValue();
9421
9422   EVT VT = N->getValueType(0);
9423   if (VT != MVT::i64)
9424     return SDValue();
9425
9426   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9427   if (!C)
9428     return SDValue();
9429   uint64_t MulAmt = C->getZExtValue();
9430   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9431     return SDValue();
9432
9433   uint64_t MulAmt1 = 0;
9434   uint64_t MulAmt2 = 0;
9435   if ((MulAmt % 9) == 0) {
9436     MulAmt1 = 9;
9437     MulAmt2 = MulAmt / 9;
9438   } else if ((MulAmt % 5) == 0) {
9439     MulAmt1 = 5;
9440     MulAmt2 = MulAmt / 5;
9441   } else if ((MulAmt % 3) == 0) {
9442     MulAmt1 = 3;
9443     MulAmt2 = MulAmt / 3;
9444   }
9445   if (MulAmt2 &&
9446       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9447     DebugLoc DL = N->getDebugLoc();
9448
9449     if (isPowerOf2_64(MulAmt2) &&
9450         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9451       // If second multiplifer is pow2, issue it first. We want the multiply by
9452       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9453       // is an add.
9454       std::swap(MulAmt1, MulAmt2);
9455
9456     SDValue NewMul;
9457     if (isPowerOf2_64(MulAmt1))
9458       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9459                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9460     else
9461       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9462                            DAG.getConstant(MulAmt1, VT));
9463
9464     if (isPowerOf2_64(MulAmt2))
9465       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9466                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9467     else
9468       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9469                            DAG.getConstant(MulAmt2, VT));
9470
9471     // Do not add new nodes to DAG combiner worklist.
9472     DCI.CombineTo(N, NewMul, false);
9473   }
9474   return SDValue();
9475 }
9476
9477 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9478   SDValue N0 = N->getOperand(0);
9479   SDValue N1 = N->getOperand(1);
9480   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9481   EVT VT = N0.getValueType();
9482
9483   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9484   // since the result of setcc_c is all zero's or all ones.
9485   if (N1C && N0.getOpcode() == ISD::AND &&
9486       N0.getOperand(1).getOpcode() == ISD::Constant) {
9487     SDValue N00 = N0.getOperand(0);
9488     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9489         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9490           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9491          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9492       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9493       APInt ShAmt = N1C->getAPIntValue();
9494       Mask = Mask.shl(ShAmt);
9495       if (Mask != 0)
9496         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9497                            N00, DAG.getConstant(Mask, VT));
9498     }
9499   }
9500
9501   return SDValue();
9502 }
9503
9504 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9505 ///                       when possible.
9506 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9507                                    const X86Subtarget *Subtarget) {
9508   EVT VT = N->getValueType(0);
9509   if (!VT.isVector() && VT.isInteger() &&
9510       N->getOpcode() == ISD::SHL)
9511     return PerformSHLCombine(N, DAG);
9512
9513   // On X86 with SSE2 support, we can transform this to a vector shift if
9514   // all elements are shifted by the same amount.  We can't do this in legalize
9515   // because the a constant vector is typically transformed to a constant pool
9516   // so we have no knowledge of the shift amount.
9517   if (!Subtarget->hasSSE2())
9518     return SDValue();
9519
9520   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9521     return SDValue();
9522
9523   SDValue ShAmtOp = N->getOperand(1);
9524   EVT EltVT = VT.getVectorElementType();
9525   DebugLoc DL = N->getDebugLoc();
9526   SDValue BaseShAmt = SDValue();
9527   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9528     unsigned NumElts = VT.getVectorNumElements();
9529     unsigned i = 0;
9530     for (; i != NumElts; ++i) {
9531       SDValue Arg = ShAmtOp.getOperand(i);
9532       if (Arg.getOpcode() == ISD::UNDEF) continue;
9533       BaseShAmt = Arg;
9534       break;
9535     }
9536     for (; i != NumElts; ++i) {
9537       SDValue Arg = ShAmtOp.getOperand(i);
9538       if (Arg.getOpcode() == ISD::UNDEF) continue;
9539       if (Arg != BaseShAmt) {
9540         return SDValue();
9541       }
9542     }
9543   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9544              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9545     SDValue InVec = ShAmtOp.getOperand(0);
9546     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9547       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9548       unsigned i = 0;
9549       for (; i != NumElts; ++i) {
9550         SDValue Arg = InVec.getOperand(i);
9551         if (Arg.getOpcode() == ISD::UNDEF) continue;
9552         BaseShAmt = Arg;
9553         break;
9554       }
9555     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9556        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9557          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9558          if (C->getZExtValue() == SplatIdx)
9559            BaseShAmt = InVec.getOperand(1);
9560        }
9561     }
9562     if (BaseShAmt.getNode() == 0)
9563       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9564                               DAG.getIntPtrConstant(0));
9565   } else
9566     return SDValue();
9567
9568   // The shift amount is an i32.
9569   if (EltVT.bitsGT(MVT::i32))
9570     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9571   else if (EltVT.bitsLT(MVT::i32))
9572     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9573
9574   // The shift amount is identical so we can do a vector shift.
9575   SDValue  ValOp = N->getOperand(0);
9576   switch (N->getOpcode()) {
9577   default:
9578     llvm_unreachable("Unknown shift opcode!");
9579     break;
9580   case ISD::SHL:
9581     if (VT == MVT::v2i64)
9582       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9583                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9584                          ValOp, BaseShAmt);
9585     if (VT == MVT::v4i32)
9586       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9587                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9588                          ValOp, BaseShAmt);
9589     if (VT == MVT::v8i16)
9590       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9591                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9592                          ValOp, BaseShAmt);
9593     break;
9594   case ISD::SRA:
9595     if (VT == MVT::v4i32)
9596       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9597                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9598                          ValOp, BaseShAmt);
9599     if (VT == MVT::v8i16)
9600       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9601                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9602                          ValOp, BaseShAmt);
9603     break;
9604   case ISD::SRL:
9605     if (VT == MVT::v2i64)
9606       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9607                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9608                          ValOp, BaseShAmt);
9609     if (VT == MVT::v4i32)
9610       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9611                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9612                          ValOp, BaseShAmt);
9613     if (VT ==  MVT::v8i16)
9614       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9615                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9616                          ValOp, BaseShAmt);
9617     break;
9618   }
9619   return SDValue();
9620 }
9621
9622 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9623                                 TargetLowering::DAGCombinerInfo &DCI,
9624                                 const X86Subtarget *Subtarget) {
9625   if (DCI.isBeforeLegalizeOps())
9626     return SDValue();
9627
9628   EVT VT = N->getValueType(0);
9629   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9630     return SDValue();
9631
9632   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9633   SDValue N0 = N->getOperand(0);
9634   SDValue N1 = N->getOperand(1);
9635   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9636     std::swap(N0, N1);
9637   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9638     return SDValue();
9639   if (!N0.hasOneUse() || !N1.hasOneUse())
9640     return SDValue();
9641
9642   SDValue ShAmt0 = N0.getOperand(1);
9643   if (ShAmt0.getValueType() != MVT::i8)
9644     return SDValue();
9645   SDValue ShAmt1 = N1.getOperand(1);
9646   if (ShAmt1.getValueType() != MVT::i8)
9647     return SDValue();
9648   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9649     ShAmt0 = ShAmt0.getOperand(0);
9650   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9651     ShAmt1 = ShAmt1.getOperand(0);
9652
9653   DebugLoc DL = N->getDebugLoc();
9654   unsigned Opc = X86ISD::SHLD;
9655   SDValue Op0 = N0.getOperand(0);
9656   SDValue Op1 = N1.getOperand(0);
9657   if (ShAmt0.getOpcode() == ISD::SUB) {
9658     Opc = X86ISD::SHRD;
9659     std::swap(Op0, Op1);
9660     std::swap(ShAmt0, ShAmt1);
9661   }
9662
9663   unsigned Bits = VT.getSizeInBits();
9664   if (ShAmt1.getOpcode() == ISD::SUB) {
9665     SDValue Sum = ShAmt1.getOperand(0);
9666     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9667       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
9668       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
9669         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
9670       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
9671         return DAG.getNode(Opc, DL, VT,
9672                            Op0, Op1,
9673                            DAG.getNode(ISD::TRUNCATE, DL,
9674                                        MVT::i8, ShAmt0));
9675     }
9676   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9677     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9678     if (ShAmt0C &&
9679         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9680       return DAG.getNode(Opc, DL, VT,
9681                          N0.getOperand(0), N1.getOperand(0),
9682                          DAG.getNode(ISD::TRUNCATE, DL,
9683                                        MVT::i8, ShAmt0));
9684   }
9685
9686   return SDValue();
9687 }
9688
9689 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9690 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9691                                    const X86Subtarget *Subtarget) {
9692   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9693   // the FP state in cases where an emms may be missing.
9694   // A preferable solution to the general problem is to figure out the right
9695   // places to insert EMMS.  This qualifies as a quick hack.
9696
9697   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9698   StoreSDNode *St = cast<StoreSDNode>(N);
9699   EVT VT = St->getValue().getValueType();
9700   if (VT.getSizeInBits() != 64)
9701     return SDValue();
9702
9703   const Function *F = DAG.getMachineFunction().getFunction();
9704   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9705   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9706     && Subtarget->hasSSE2();
9707   if ((VT.isVector() ||
9708        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9709       isa<LoadSDNode>(St->getValue()) &&
9710       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9711       St->getChain().hasOneUse() && !St->isVolatile()) {
9712     SDNode* LdVal = St->getValue().getNode();
9713     LoadSDNode *Ld = 0;
9714     int TokenFactorIndex = -1;
9715     SmallVector<SDValue, 8> Ops;
9716     SDNode* ChainVal = St->getChain().getNode();
9717     // Must be a store of a load.  We currently handle two cases:  the load
9718     // is a direct child, and it's under an intervening TokenFactor.  It is
9719     // possible to dig deeper under nested TokenFactors.
9720     if (ChainVal == LdVal)
9721       Ld = cast<LoadSDNode>(St->getChain());
9722     else if (St->getValue().hasOneUse() &&
9723              ChainVal->getOpcode() == ISD::TokenFactor) {
9724       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9725         if (ChainVal->getOperand(i).getNode() == LdVal) {
9726           TokenFactorIndex = i;
9727           Ld = cast<LoadSDNode>(St->getValue());
9728         } else
9729           Ops.push_back(ChainVal->getOperand(i));
9730       }
9731     }
9732
9733     if (!Ld || !ISD::isNormalLoad(Ld))
9734       return SDValue();
9735
9736     // If this is not the MMX case, i.e. we are just turning i64 load/store
9737     // into f64 load/store, avoid the transformation if there are multiple
9738     // uses of the loaded value.
9739     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9740       return SDValue();
9741
9742     DebugLoc LdDL = Ld->getDebugLoc();
9743     DebugLoc StDL = N->getDebugLoc();
9744     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9745     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9746     // pair instead.
9747     if (Subtarget->is64Bit() || F64IsLegal) {
9748       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9749       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9750                                   Ld->getBasePtr(), Ld->getSrcValue(),
9751                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9752                                   Ld->isNonTemporal(), Ld->getAlignment());
9753       SDValue NewChain = NewLd.getValue(1);
9754       if (TokenFactorIndex != -1) {
9755         Ops.push_back(NewChain);
9756         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9757                                Ops.size());
9758       }
9759       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9760                           St->getSrcValue(), St->getSrcValueOffset(),
9761                           St->isVolatile(), St->isNonTemporal(),
9762                           St->getAlignment());
9763     }
9764
9765     // Otherwise, lower to two pairs of 32-bit loads / stores.
9766     SDValue LoAddr = Ld->getBasePtr();
9767     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9768                                  DAG.getConstant(4, MVT::i32));
9769
9770     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9771                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9772                                Ld->isVolatile(), Ld->isNonTemporal(),
9773                                Ld->getAlignment());
9774     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9775                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9776                                Ld->isVolatile(), Ld->isNonTemporal(),
9777                                MinAlign(Ld->getAlignment(), 4));
9778
9779     SDValue NewChain = LoLd.getValue(1);
9780     if (TokenFactorIndex != -1) {
9781       Ops.push_back(LoLd);
9782       Ops.push_back(HiLd);
9783       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9784                              Ops.size());
9785     }
9786
9787     LoAddr = St->getBasePtr();
9788     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9789                          DAG.getConstant(4, MVT::i32));
9790
9791     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9792                                 St->getSrcValue(), St->getSrcValueOffset(),
9793                                 St->isVolatile(), St->isNonTemporal(),
9794                                 St->getAlignment());
9795     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9796                                 St->getSrcValue(),
9797                                 St->getSrcValueOffset() + 4,
9798                                 St->isVolatile(),
9799                                 St->isNonTemporal(),
9800                                 MinAlign(St->getAlignment(), 4));
9801     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9802   }
9803   return SDValue();
9804 }
9805
9806 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9807 /// X86ISD::FXOR nodes.
9808 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9809   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9810   // F[X]OR(0.0, x) -> x
9811   // F[X]OR(x, 0.0) -> x
9812   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9813     if (C->getValueAPF().isPosZero())
9814       return N->getOperand(1);
9815   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9816     if (C->getValueAPF().isPosZero())
9817       return N->getOperand(0);
9818   return SDValue();
9819 }
9820
9821 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9822 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9823   // FAND(0.0, x) -> 0.0
9824   // FAND(x, 0.0) -> 0.0
9825   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9826     if (C->getValueAPF().isPosZero())
9827       return N->getOperand(0);
9828   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9829     if (C->getValueAPF().isPosZero())
9830       return N->getOperand(1);
9831   return SDValue();
9832 }
9833
9834 static SDValue PerformBTCombine(SDNode *N,
9835                                 SelectionDAG &DAG,
9836                                 TargetLowering::DAGCombinerInfo &DCI) {
9837   // BT ignores high bits in the bit index operand.
9838   SDValue Op1 = N->getOperand(1);
9839   if (Op1.hasOneUse()) {
9840     unsigned BitWidth = Op1.getValueSizeInBits();
9841     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9842     APInt KnownZero, KnownOne;
9843     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9844                                           !DCI.isBeforeLegalizeOps());
9845     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9846     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9847         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9848       DCI.CommitTargetLoweringOpt(TLO);
9849   }
9850   return SDValue();
9851 }
9852
9853 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9854   SDValue Op = N->getOperand(0);
9855   if (Op.getOpcode() == ISD::BIT_CONVERT)
9856     Op = Op.getOperand(0);
9857   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9858   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9859       VT.getVectorElementType().getSizeInBits() ==
9860       OpVT.getVectorElementType().getSizeInBits()) {
9861     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9862   }
9863   return SDValue();
9864 }
9865
9866 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9867   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9868   //           (and (i32 x86isd::setcc_carry), 1)
9869   // This eliminates the zext. This transformation is necessary because
9870   // ISD::SETCC is always legalized to i8.
9871   DebugLoc dl = N->getDebugLoc();
9872   SDValue N0 = N->getOperand(0);
9873   EVT VT = N->getValueType(0);
9874   if (N0.getOpcode() == ISD::AND &&
9875       N0.hasOneUse() &&
9876       N0.getOperand(0).hasOneUse()) {
9877     SDValue N00 = N0.getOperand(0);
9878     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9879       return SDValue();
9880     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9881     if (!C || C->getZExtValue() != 1)
9882       return SDValue();
9883     return DAG.getNode(ISD::AND, dl, VT,
9884                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9885                                    N00.getOperand(0), N00.getOperand(1)),
9886                        DAG.getConstant(1, VT));
9887   }
9888
9889   return SDValue();
9890 }
9891
9892 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9893                                              DAGCombinerInfo &DCI) const {
9894   SelectionDAG &DAG = DCI.DAG;
9895   switch (N->getOpcode()) {
9896   default: break;
9897   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9898   case ISD::EXTRACT_VECTOR_ELT:
9899                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9900   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9901   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9902   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9903   case ISD::SHL:
9904   case ISD::SRA:
9905   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9906   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
9907   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9908   case X86ISD::FXOR:
9909   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9910   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9911   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9912   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9913   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9914   }
9915
9916   return SDValue();
9917 }
9918
9919 /// isTypeDesirableForOp - Return true if the target has native support for
9920 /// the specified value type and it is 'desirable' to use the type for the
9921 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9922 /// instruction encodings are longer and some i16 instructions are slow.
9923 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9924   if (!isTypeLegal(VT))
9925     return false;
9926   if (VT != MVT::i16)
9927     return true;
9928
9929   switch (Opc) {
9930   default:
9931     return true;
9932   case ISD::LOAD:
9933   case ISD::SIGN_EXTEND:
9934   case ISD::ZERO_EXTEND:
9935   case ISD::ANY_EXTEND:
9936   case ISD::SHL:
9937   case ISD::SRL:
9938   case ISD::SUB:
9939   case ISD::ADD:
9940   case ISD::MUL:
9941   case ISD::AND:
9942   case ISD::OR:
9943   case ISD::XOR:
9944     return false;
9945   }
9946 }
9947
9948 static bool MayFoldLoad(SDValue Op) {
9949   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9950 }
9951
9952 static bool MayFoldIntoStore(SDValue Op) {
9953   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9954 }
9955
9956 /// IsDesirableToPromoteOp - This method query the target whether it is
9957 /// beneficial for dag combiner to promote the specified node. If true, it
9958 /// should return the desired promotion type by reference.
9959 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9960   EVT VT = Op.getValueType();
9961   if (VT != MVT::i16)
9962     return false;
9963
9964   bool Promote = false;
9965   bool Commute = false;
9966   switch (Op.getOpcode()) {
9967   default: break;
9968   case ISD::LOAD: {
9969     LoadSDNode *LD = cast<LoadSDNode>(Op);
9970     // If the non-extending load has a single use and it's not live out, then it
9971     // might be folded.
9972     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9973                                                      Op.hasOneUse()*/) {
9974       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9975              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9976         // The only case where we'd want to promote LOAD (rather then it being
9977         // promoted as an operand is when it's only use is liveout.
9978         if (UI->getOpcode() != ISD::CopyToReg)
9979           return false;
9980       }
9981     }
9982     Promote = true;
9983     break;
9984   }
9985   case ISD::SIGN_EXTEND:
9986   case ISD::ZERO_EXTEND:
9987   case ISD::ANY_EXTEND:
9988     Promote = true;
9989     break;
9990   case ISD::SHL:
9991   case ISD::SRL: {
9992     SDValue N0 = Op.getOperand(0);
9993     // Look out for (store (shl (load), x)).
9994     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9995       return false;
9996     Promote = true;
9997     break;
9998   }
9999   case ISD::ADD:
10000   case ISD::MUL:
10001   case ISD::AND:
10002   case ISD::OR:
10003   case ISD::XOR:
10004     Commute = true;
10005     // fallthrough
10006   case ISD::SUB: {
10007     SDValue N0 = Op.getOperand(0);
10008     SDValue N1 = Op.getOperand(1);
10009     if (!Commute && MayFoldLoad(N1))
10010       return false;
10011     // Avoid disabling potential load folding opportunities.
10012     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
10013       return false;
10014     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
10015       return false;
10016     Promote = true;
10017   }
10018   }
10019
10020   PVT = MVT::i32;
10021   return Promote;
10022 }
10023
10024 //===----------------------------------------------------------------------===//
10025 //                           X86 Inline Assembly Support
10026 //===----------------------------------------------------------------------===//
10027
10028 static bool LowerToBSwap(CallInst *CI) {
10029   // FIXME: this should verify that we are targetting a 486 or better.  If not,
10030   // we will turn this bswap into something that will be lowered to logical ops
10031   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
10032   // so don't worry about this.
10033
10034   // Verify this is a simple bswap.
10035   if (CI->getNumArgOperands() != 1 ||
10036       CI->getType() != CI->getArgOperand(0)->getType() ||
10037       !CI->getType()->isIntegerTy())
10038     return false;
10039
10040   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10041   if (!Ty || Ty->getBitWidth() % 16 != 0)
10042     return false;
10043
10044   // Okay, we can do this xform, do so now.
10045   const Type *Tys[] = { Ty };
10046   Module *M = CI->getParent()->getParent()->getParent();
10047   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10048
10049   Value *Op = CI->getArgOperand(0);
10050   Op = CallInst::Create(Int, Op, CI->getName(), CI);
10051
10052   CI->replaceAllUsesWith(Op);
10053   CI->eraseFromParent();
10054   return true;
10055 }
10056
10057 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10058   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10059   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10060
10061   std::string AsmStr = IA->getAsmString();
10062
10063   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10064   SmallVector<StringRef, 4> AsmPieces;
10065   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
10066
10067   switch (AsmPieces.size()) {
10068   default: return false;
10069   case 1:
10070     AsmStr = AsmPieces[0];
10071     AsmPieces.clear();
10072     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
10073
10074     // bswap $0
10075     if (AsmPieces.size() == 2 &&
10076         (AsmPieces[0] == "bswap" ||
10077          AsmPieces[0] == "bswapq" ||
10078          AsmPieces[0] == "bswapl") &&
10079         (AsmPieces[1] == "$0" ||
10080          AsmPieces[1] == "${0:q}")) {
10081       // No need to check constraints, nothing other than the equivalent of
10082       // "=r,0" would be valid here.
10083       return LowerToBSwap(CI);
10084     }
10085     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
10086     if (CI->getType()->isIntegerTy(16) &&
10087         AsmPieces.size() == 3 &&
10088         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10089         AsmPieces[1] == "$$8," &&
10090         AsmPieces[2] == "${0:w}" &&
10091         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10092       AsmPieces.clear();
10093       const std::string &Constraints = IA->getConstraintString();
10094       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10095       std::sort(AsmPieces.begin(), AsmPieces.end());
10096       if (AsmPieces.size() == 4 &&
10097           AsmPieces[0] == "~{cc}" &&
10098           AsmPieces[1] == "~{dirflag}" &&
10099           AsmPieces[2] == "~{flags}" &&
10100           AsmPieces[3] == "~{fpsr}") {
10101         return LowerToBSwap(CI);
10102       }
10103     }
10104     break;
10105   case 3:
10106     if (CI->getType()->isIntegerTy(64) &&
10107         Constraints.size() >= 2 &&
10108         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10109         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10110       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
10111       SmallVector<StringRef, 4> Words;
10112       SplitString(AsmPieces[0], Words, " \t");
10113       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10114         Words.clear();
10115         SplitString(AsmPieces[1], Words, " \t");
10116         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10117           Words.clear();
10118           SplitString(AsmPieces[2], Words, " \t,");
10119           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10120               Words[2] == "%edx") {
10121             return LowerToBSwap(CI);
10122           }
10123         }
10124       }
10125     }
10126     break;
10127   }
10128   return false;
10129 }
10130
10131
10132
10133 /// getConstraintType - Given a constraint letter, return the type of
10134 /// constraint it is for this target.
10135 X86TargetLowering::ConstraintType
10136 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10137   if (Constraint.size() == 1) {
10138     switch (Constraint[0]) {
10139     case 'A':
10140       return C_Register;
10141     case 'f':
10142     case 'r':
10143     case 'R':
10144     case 'l':
10145     case 'q':
10146     case 'Q':
10147     case 'x':
10148     case 'y':
10149     case 'Y':
10150       return C_RegisterClass;
10151     case 'e':
10152     case 'Z':
10153       return C_Other;
10154     default:
10155       break;
10156     }
10157   }
10158   return TargetLowering::getConstraintType(Constraint);
10159 }
10160
10161 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10162 /// with another that has more specific requirements based on the type of the
10163 /// corresponding operand.
10164 const char *X86TargetLowering::
10165 LowerXConstraint(EVT ConstraintVT) const {
10166   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10167   // 'f' like normal targets.
10168   if (ConstraintVT.isFloatingPoint()) {
10169     if (Subtarget->hasSSE2())
10170       return "Y";
10171     if (Subtarget->hasSSE1())
10172       return "x";
10173   }
10174
10175   return TargetLowering::LowerXConstraint(ConstraintVT);
10176 }
10177
10178 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10179 /// vector.  If it is invalid, don't add anything to Ops.
10180 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10181                                                      char Constraint,
10182                                                      std::vector<SDValue>&Ops,
10183                                                      SelectionDAG &DAG) const {
10184   SDValue Result(0, 0);
10185
10186   switch (Constraint) {
10187   default: break;
10188   case 'I':
10189     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10190       if (C->getZExtValue() <= 31) {
10191         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10192         break;
10193       }
10194     }
10195     return;
10196   case 'J':
10197     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10198       if (C->getZExtValue() <= 63) {
10199         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10200         break;
10201       }
10202     }
10203     return;
10204   case 'K':
10205     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10206       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10207         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10208         break;
10209       }
10210     }
10211     return;
10212   case 'N':
10213     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10214       if (C->getZExtValue() <= 255) {
10215         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10216         break;
10217       }
10218     }
10219     return;
10220   case 'e': {
10221     // 32-bit signed value
10222     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10223       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10224                                            C->getSExtValue())) {
10225         // Widen to 64 bits here to get it sign extended.
10226         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10227         break;
10228       }
10229     // FIXME gcc accepts some relocatable values here too, but only in certain
10230     // memory models; it's complicated.
10231     }
10232     return;
10233   }
10234   case 'Z': {
10235     // 32-bit unsigned value
10236     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10237       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10238                                            C->getZExtValue())) {
10239         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10240         break;
10241       }
10242     }
10243     // FIXME gcc accepts some relocatable values here too, but only in certain
10244     // memory models; it's complicated.
10245     return;
10246   }
10247   case 'i': {
10248     // Literal immediates are always ok.
10249     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10250       // Widen to 64 bits here to get it sign extended.
10251       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10252       break;
10253     }
10254
10255     // In any sort of PIC mode addresses need to be computed at runtime by
10256     // adding in a register or some sort of table lookup.  These can't
10257     // be used as immediates.
10258     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
10259       return;
10260
10261     // If we are in non-pic codegen mode, we allow the address of a global (with
10262     // an optional displacement) to be used with 'i'.
10263     GlobalAddressSDNode *GA = 0;
10264     int64_t Offset = 0;
10265
10266     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10267     while (1) {
10268       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10269         Offset += GA->getOffset();
10270         break;
10271       } else if (Op.getOpcode() == ISD::ADD) {
10272         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10273           Offset += C->getZExtValue();
10274           Op = Op.getOperand(0);
10275           continue;
10276         }
10277       } else if (Op.getOpcode() == ISD::SUB) {
10278         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10279           Offset += -C->getZExtValue();
10280           Op = Op.getOperand(0);
10281           continue;
10282         }
10283       }
10284
10285       // Otherwise, this isn't something we can handle, reject it.
10286       return;
10287     }
10288
10289     const GlobalValue *GV = GA->getGlobal();
10290     // If we require an extra load to get this address, as in PIC mode, we
10291     // can't accept it.
10292     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10293                                                         getTargetMachine())))
10294       return;
10295
10296     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
10297                                         GA->getValueType(0), Offset);
10298     break;
10299   }
10300   }
10301
10302   if (Result.getNode()) {
10303     Ops.push_back(Result);
10304     return;
10305   }
10306   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10307 }
10308
10309 std::vector<unsigned> X86TargetLowering::
10310 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10311                                   EVT VT) const {
10312   if (Constraint.size() == 1) {
10313     // FIXME: not handling fp-stack yet!
10314     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10315     default: break;  // Unknown constraint letter
10316     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10317       if (Subtarget->is64Bit()) {
10318         if (VT == MVT::i32)
10319           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10320                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10321                                        X86::R10D,X86::R11D,X86::R12D,
10322                                        X86::R13D,X86::R14D,X86::R15D,
10323                                        X86::EBP, X86::ESP, 0);
10324         else if (VT == MVT::i16)
10325           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10326                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10327                                        X86::R10W,X86::R11W,X86::R12W,
10328                                        X86::R13W,X86::R14W,X86::R15W,
10329                                        X86::BP,  X86::SP, 0);
10330         else if (VT == MVT::i8)
10331           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10332                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10333                                        X86::R10B,X86::R11B,X86::R12B,
10334                                        X86::R13B,X86::R14B,X86::R15B,
10335                                        X86::BPL, X86::SPL, 0);
10336
10337         else if (VT == MVT::i64)
10338           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10339                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10340                                        X86::R10, X86::R11, X86::R12,
10341                                        X86::R13, X86::R14, X86::R15,
10342                                        X86::RBP, X86::RSP, 0);
10343
10344         break;
10345       }
10346       // 32-bit fallthrough
10347     case 'Q':   // Q_REGS
10348       if (VT == MVT::i32)
10349         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10350       else if (VT == MVT::i16)
10351         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10352       else if (VT == MVT::i8)
10353         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10354       else if (VT == MVT::i64)
10355         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10356       break;
10357     }
10358   }
10359
10360   return std::vector<unsigned>();
10361 }
10362
10363 std::pair<unsigned, const TargetRegisterClass*>
10364 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10365                                                 EVT VT) const {
10366   // First, see if this is a constraint that directly corresponds to an LLVM
10367   // register class.
10368   if (Constraint.size() == 1) {
10369     // GCC Constraint Letters
10370     switch (Constraint[0]) {
10371     default: break;
10372     case 'r':   // GENERAL_REGS
10373     case 'l':   // INDEX_REGS
10374       if (VT == MVT::i8)
10375         return std::make_pair(0U, X86::GR8RegisterClass);
10376       if (VT == MVT::i16)
10377         return std::make_pair(0U, X86::GR16RegisterClass);
10378       if (VT == MVT::i32 || !Subtarget->is64Bit())
10379         return std::make_pair(0U, X86::GR32RegisterClass);
10380       return std::make_pair(0U, X86::GR64RegisterClass);
10381     case 'R':   // LEGACY_REGS
10382       if (VT == MVT::i8)
10383         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10384       if (VT == MVT::i16)
10385         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10386       if (VT == MVT::i32 || !Subtarget->is64Bit())
10387         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10388       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10389     case 'f':  // FP Stack registers.
10390       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10391       // value to the correct fpstack register class.
10392       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10393         return std::make_pair(0U, X86::RFP32RegisterClass);
10394       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10395         return std::make_pair(0U, X86::RFP64RegisterClass);
10396       return std::make_pair(0U, X86::RFP80RegisterClass);
10397     case 'y':   // MMX_REGS if MMX allowed.
10398       if (!Subtarget->hasMMX()) break;
10399       return std::make_pair(0U, X86::VR64RegisterClass);
10400     case 'Y':   // SSE_REGS if SSE2 allowed
10401       if (!Subtarget->hasSSE2()) break;
10402       // FALL THROUGH.
10403     case 'x':   // SSE_REGS if SSE1 allowed
10404       if (!Subtarget->hasSSE1()) break;
10405
10406       switch (VT.getSimpleVT().SimpleTy) {
10407       default: break;
10408       // Scalar SSE types.
10409       case MVT::f32:
10410       case MVT::i32:
10411         return std::make_pair(0U, X86::FR32RegisterClass);
10412       case MVT::f64:
10413       case MVT::i64:
10414         return std::make_pair(0U, X86::FR64RegisterClass);
10415       // Vector types.
10416       case MVT::v16i8:
10417       case MVT::v8i16:
10418       case MVT::v4i32:
10419       case MVT::v2i64:
10420       case MVT::v4f32:
10421       case MVT::v2f64:
10422         return std::make_pair(0U, X86::VR128RegisterClass);
10423       }
10424       break;
10425     }
10426   }
10427
10428   // Use the default implementation in TargetLowering to convert the register
10429   // constraint into a member of a register class.
10430   std::pair<unsigned, const TargetRegisterClass*> Res;
10431   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10432
10433   // Not found as a standard register?
10434   if (Res.second == 0) {
10435     // Map st(0) -> st(7) -> ST0
10436     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10437         tolower(Constraint[1]) == 's' &&
10438         tolower(Constraint[2]) == 't' &&
10439         Constraint[3] == '(' &&
10440         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10441         Constraint[5] == ')' &&
10442         Constraint[6] == '}') {
10443
10444       Res.first = X86::ST0+Constraint[4]-'0';
10445       Res.second = X86::RFP80RegisterClass;
10446       return Res;
10447     }
10448
10449     // GCC allows "st(0)" to be called just plain "st".
10450     if (StringRef("{st}").equals_lower(Constraint)) {
10451       Res.first = X86::ST0;
10452       Res.second = X86::RFP80RegisterClass;
10453       return Res;
10454     }
10455
10456     // flags -> EFLAGS
10457     if (StringRef("{flags}").equals_lower(Constraint)) {
10458       Res.first = X86::EFLAGS;
10459       Res.second = X86::CCRRegisterClass;
10460       return Res;
10461     }
10462
10463     // 'A' means EAX + EDX.
10464     if (Constraint == "A") {
10465       Res.first = X86::EAX;
10466       Res.second = X86::GR32_ADRegisterClass;
10467       return Res;
10468     }
10469     return Res;
10470   }
10471
10472   // Otherwise, check to see if this is a register class of the wrong value
10473   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10474   // turn into {ax},{dx}.
10475   if (Res.second->hasType(VT))
10476     return Res;   // Correct type already, nothing to do.
10477
10478   // All of the single-register GCC register classes map their values onto
10479   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10480   // really want an 8-bit or 32-bit register, map to the appropriate register
10481   // class and return the appropriate register.
10482   if (Res.second == X86::GR16RegisterClass) {
10483     if (VT == MVT::i8) {
10484       unsigned DestReg = 0;
10485       switch (Res.first) {
10486       default: break;
10487       case X86::AX: DestReg = X86::AL; break;
10488       case X86::DX: DestReg = X86::DL; break;
10489       case X86::CX: DestReg = X86::CL; break;
10490       case X86::BX: DestReg = X86::BL; break;
10491       }
10492       if (DestReg) {
10493         Res.first = DestReg;
10494         Res.second = X86::GR8RegisterClass;
10495       }
10496     } else if (VT == MVT::i32) {
10497       unsigned DestReg = 0;
10498       switch (Res.first) {
10499       default: break;
10500       case X86::AX: DestReg = X86::EAX; break;
10501       case X86::DX: DestReg = X86::EDX; break;
10502       case X86::CX: DestReg = X86::ECX; break;
10503       case X86::BX: DestReg = X86::EBX; break;
10504       case X86::SI: DestReg = X86::ESI; break;
10505       case X86::DI: DestReg = X86::EDI; break;
10506       case X86::BP: DestReg = X86::EBP; break;
10507       case X86::SP: DestReg = X86::ESP; break;
10508       }
10509       if (DestReg) {
10510         Res.first = DestReg;
10511         Res.second = X86::GR32RegisterClass;
10512       }
10513     } else if (VT == MVT::i64) {
10514       unsigned DestReg = 0;
10515       switch (Res.first) {
10516       default: break;
10517       case X86::AX: DestReg = X86::RAX; break;
10518       case X86::DX: DestReg = X86::RDX; break;
10519       case X86::CX: DestReg = X86::RCX; break;
10520       case X86::BX: DestReg = X86::RBX; break;
10521       case X86::SI: DestReg = X86::RSI; break;
10522       case X86::DI: DestReg = X86::RDI; break;
10523       case X86::BP: DestReg = X86::RBP; break;
10524       case X86::SP: DestReg = X86::RSP; break;
10525       }
10526       if (DestReg) {
10527         Res.first = DestReg;
10528         Res.second = X86::GR64RegisterClass;
10529       }
10530     }
10531   } else if (Res.second == X86::FR32RegisterClass ||
10532              Res.second == X86::FR64RegisterClass ||
10533              Res.second == X86::VR128RegisterClass) {
10534     // Handle references to XMM physical registers that got mapped into the
10535     // wrong class.  This can happen with constraints like {xmm0} where the
10536     // target independent register mapper will just pick the first match it can
10537     // find, ignoring the required type.
10538     if (VT == MVT::f32)
10539       Res.second = X86::FR32RegisterClass;
10540     else if (VT == MVT::f64)
10541       Res.second = X86::FR64RegisterClass;
10542     else if (X86::VR128RegisterClass->hasType(VT))
10543       Res.second = X86::VR128RegisterClass;
10544   }
10545
10546   return Res;
10547 }