Make x86-64 membarriers work without sse and clean up some of the
[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   // We may not have a libcall for MEMBARRIER so we should lower this.
347   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
348   
349   // On X86 and X86-64, atomic operations are lowered to locked instructions.
350   // Locked instructions, in turn, have implicit fence semantics (all memory
351   // operations are flushed before issuing the locked instruction, and they
352   // are not buffered), so we can fold away the common pattern of
353   // fence-atomic-fence.
354   setShouldFoldAtomicFences(true);
355
356   // Expand certain atomics
357   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
358   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
359   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
360   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
361
362   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
363   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
364   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
365   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
366
367   if (!Subtarget->is64Bit()) {
368     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
369     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
370     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
371     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
372     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
373     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
374     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
375   }
376
377   // FIXME - use subtarget debug flags
378   if (!Subtarget->isTargetDarwin() &&
379       !Subtarget->isTargetELF() &&
380       !Subtarget->isTargetCygMing()) {
381     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
382   }
383
384   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
385   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
386   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
387   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
388   if (Subtarget->is64Bit()) {
389     setExceptionPointerRegister(X86::RAX);
390     setExceptionSelectorRegister(X86::RDX);
391   } else {
392     setExceptionPointerRegister(X86::EAX);
393     setExceptionSelectorRegister(X86::EDX);
394   }
395   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
396   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
397
398   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
399
400   setOperationAction(ISD::TRAP, MVT::Other, Legal);
401
402   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
403   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
404   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
405   if (Subtarget->is64Bit()) {
406     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
407     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
408   } else {
409     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
410     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
411   }
412
413   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
414   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
415   if (Subtarget->is64Bit())
416     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
417   if (Subtarget->isTargetCygMing())
418     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
419   else
420     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
421
422   if (!UseSoftFloat && X86ScalarSSEf64) {
423     // f32 and f64 use SSE.
424     // Set up the FP register classes.
425     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
426     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
427
428     // Use ANDPD to simulate FABS.
429     setOperationAction(ISD::FABS , MVT::f64, Custom);
430     setOperationAction(ISD::FABS , MVT::f32, Custom);
431
432     // Use XORP to simulate FNEG.
433     setOperationAction(ISD::FNEG , MVT::f64, Custom);
434     setOperationAction(ISD::FNEG , MVT::f32, Custom);
435
436     // Use ANDPD and ORPD to simulate FCOPYSIGN.
437     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
438     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
439
440     // We don't support sin/cos/fmod
441     setOperationAction(ISD::FSIN , MVT::f64, Expand);
442     setOperationAction(ISD::FCOS , MVT::f64, Expand);
443     setOperationAction(ISD::FSIN , MVT::f32, Expand);
444     setOperationAction(ISD::FCOS , MVT::f32, Expand);
445
446     // Expand FP immediates into loads from the stack, except for the special
447     // cases we handle.
448     addLegalFPImmediate(APFloat(+0.0)); // xorpd
449     addLegalFPImmediate(APFloat(+0.0f)); // xorps
450   } else if (!UseSoftFloat && X86ScalarSSEf32) {
451     // Use SSE for f32, x87 for f64.
452     // Set up the FP register classes.
453     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
454     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
455
456     // Use ANDPS to simulate FABS.
457     setOperationAction(ISD::FABS , MVT::f32, Custom);
458
459     // Use XORP to simulate FNEG.
460     setOperationAction(ISD::FNEG , MVT::f32, Custom);
461
462     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
463
464     // Use ANDPS and ORPS to simulate FCOPYSIGN.
465     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
467
468     // We don't support sin/cos/fmod
469     setOperationAction(ISD::FSIN , MVT::f32, Expand);
470     setOperationAction(ISD::FCOS , MVT::f32, Expand);
471
472     // Special cases we handle for FP constants.
473     addLegalFPImmediate(APFloat(+0.0f)); // xorps
474     addLegalFPImmediate(APFloat(+0.0)); // FLD0
475     addLegalFPImmediate(APFloat(+1.0)); // FLD1
476     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
477     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
478
479     if (!UnsafeFPMath) {
480       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
481       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
482     }
483   } else if (!UseSoftFloat) {
484     // f32 and f64 in x87.
485     // Set up the FP register classes.
486     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
487     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
488
489     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
490     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
491     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
492     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
493
494     if (!UnsafeFPMath) {
495       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
496       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
497     }
498     addLegalFPImmediate(APFloat(+0.0)); // FLD0
499     addLegalFPImmediate(APFloat(+1.0)); // FLD1
500     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
501     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
502     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
503     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
504     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
505     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
506   }
507
508   // Long double always uses X87.
509   if (!UseSoftFloat) {
510     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
511     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
512     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
513     {
514       bool ignored;
515       APFloat TmpFlt(+0.0);
516       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
517                      &ignored);
518       addLegalFPImmediate(TmpFlt);  // FLD0
519       TmpFlt.changeSign();
520       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
521       APFloat TmpFlt2(+1.0);
522       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
523                       &ignored);
524       addLegalFPImmediate(TmpFlt2);  // FLD1
525       TmpFlt2.changeSign();
526       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
527     }
528
529     if (!UnsafeFPMath) {
530       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
531       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
532     }
533   }
534
535   // Always use a library call for pow.
536   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
537   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
538   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
539
540   setOperationAction(ISD::FLOG, MVT::f80, Expand);
541   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
542   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
543   setOperationAction(ISD::FEXP, MVT::f80, Expand);
544   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
545
546   // First set operation action for all vector types to either promote
547   // (for widening) or expand (for scalarization). Then we will selectively
548   // turn on ones that can be effectively codegen'd.
549   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
550        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
551     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
566     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
567     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
600     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
604     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
605          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
606       setTruncStoreAction((MVT::SimpleValueType)VT,
607                           (MVT::SimpleValueType)InnerVT, Expand);
608     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
609     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
610     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
611   }
612
613   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
614   // with -msoft-float, disable use of MMX as well.
615   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
616     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
617     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
618     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
619     
620     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
621
622     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
623     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
624     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
625     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
626
627     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
628     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
629     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
630     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
631
632     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
633     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
634
635     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
636     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
637     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
638     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
639     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
640     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
641     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
642
643     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
644     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
645     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
646     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
647     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
648     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
649     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
650
651     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
652     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
653     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
654     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
655     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
656     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
657     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
658
659     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
660     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
661     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
662     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
663     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
664     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
665     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
666
667     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
668     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
669     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
670     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
671
672     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
673     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
674     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
675     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
676
677     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
678     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
679     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
680
681     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
682
683     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
684     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
685     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
686     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
687     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
688     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
689     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
690
691     if (!X86ScalarSSEf64 && Subtarget->is64Bit()) {
692       setOperationAction(ISD::BIT_CONVERT,        MVT::v8i8,  Custom);
693       setOperationAction(ISD::BIT_CONVERT,        MVT::v4i16, Custom);
694       setOperationAction(ISD::BIT_CONVERT,        MVT::v2i32, Custom);
695       setOperationAction(ISD::BIT_CONVERT,        MVT::v1i64, Custom);
696     }
697   }
698
699   if (!UseSoftFloat && Subtarget->hasSSE1()) {
700     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
701
702     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
703     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
704     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
705     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
706     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
707     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
708     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
709     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
710     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
711     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
712     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
713     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
714   }
715
716   if (!UseSoftFloat && Subtarget->hasSSE2()) {
717     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
718
719     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
720     // registers cannot be used even for integer operations.
721     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
722     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
723     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
724     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
725
726     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
727     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
728     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
729     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
730     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
731     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
732     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
733     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
734     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
735     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
736     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
737     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
738     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
739     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
740     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
741     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
742
743     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
744     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
745     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
746     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
747
748     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
749     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
750     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
751     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
752     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
753
754     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
755     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
756     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
757     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
758     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
759
760     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
761     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
762       EVT VT = (MVT::SimpleValueType)i;
763       // Do not attempt to custom lower non-power-of-2 vectors
764       if (!isPowerOf2_32(VT.getVectorNumElements()))
765         continue;
766       // Do not attempt to custom lower non-128-bit vectors
767       if (!VT.is128BitVector())
768         continue;
769       setOperationAction(ISD::BUILD_VECTOR,
770                          VT.getSimpleVT().SimpleTy, Custom);
771       setOperationAction(ISD::VECTOR_SHUFFLE,
772                          VT.getSimpleVT().SimpleTy, Custom);
773       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
774                          VT.getSimpleVT().SimpleTy, Custom);
775     }
776
777     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
778     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
779     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
780     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
781     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
782     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
783
784     if (Subtarget->is64Bit()) {
785       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
786       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
787     }
788
789     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
790     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
791       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
792       EVT VT = SVT;
793
794       // Do not attempt to promote non-128-bit vectors
795       if (!VT.is128BitVector())
796         continue;
797       
798       setOperationAction(ISD::AND,    SVT, Promote);
799       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
800       setOperationAction(ISD::OR,     SVT, Promote);
801       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
802       setOperationAction(ISD::XOR,    SVT, Promote);
803       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
804       setOperationAction(ISD::LOAD,   SVT, Promote);
805       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
806       setOperationAction(ISD::SELECT, SVT, Promote);
807       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
808     }
809
810     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
811
812     // Custom lower v2i64 and v2f64 selects.
813     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
814     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
815     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
816     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
817
818     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
819     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
820     if (!DisableMMX && Subtarget->hasMMX()) {
821       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
822       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
823     }
824   }
825
826   if (Subtarget->hasSSE41()) {
827     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
828     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
829     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
830     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
831     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
832     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
833     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
834     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
835     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
836     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
837
838     // FIXME: Do we need to handle scalar-to-vector here?
839     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
840
841     // Can turn SHL into an integer multiply.
842     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
843     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
844
845     // i8 and i16 vectors are custom , because the source register and source
846     // source memory operand types are not the same width.  f32 vectors are
847     // custom since the immediate controlling the insert encodes additional
848     // information.
849     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
850     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
851     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
852     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
853
854     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
855     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
856     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
857     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
858
859     if (Subtarget->is64Bit()) {
860       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
862     }
863   }
864
865   if (Subtarget->hasSSE42()) {
866     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
867   }
868
869   if (!UseSoftFloat && Subtarget->hasAVX()) {
870     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
871     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
872     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
873     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
874
875     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
876     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
877     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
878     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
879     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
880     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
881     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
882     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
883     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
884     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
885     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
886     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
887     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
888     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
889     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
890
891     // Operations to consider commented out -v16i16 v32i8
892     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
893     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
894     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
895     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
896     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
897     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
898     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
899     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
900     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
901     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
902     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
903     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
904     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
905     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
906
907     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
908     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
909     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
910     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
911
912     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
913     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
914     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
915     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
916     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
917
918     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
919     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
920     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
921     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
922     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
924
925 #if 0
926     // Not sure we want to do this since there are no 256-bit integer
927     // operations in AVX
928
929     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
930     // This includes 256-bit vectors
931     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
932       EVT VT = (MVT::SimpleValueType)i;
933
934       // Do not attempt to custom lower non-power-of-2 vectors
935       if (!isPowerOf2_32(VT.getVectorNumElements()))
936         continue;
937
938       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
939       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
940       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
941     }
942
943     if (Subtarget->is64Bit()) {
944       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
945       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
946     }
947 #endif
948
949 #if 0
950     // Not sure we want to do this since there are no 256-bit integer
951     // operations in AVX
952
953     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
954     // Including 256-bit vectors
955     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
956       EVT VT = (MVT::SimpleValueType)i;
957
958       if (!VT.is256BitVector()) {
959         continue;
960       }
961       setOperationAction(ISD::AND,    VT, Promote);
962       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
963       setOperationAction(ISD::OR,     VT, Promote);
964       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
965       setOperationAction(ISD::XOR,    VT, Promote);
966       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
967       setOperationAction(ISD::LOAD,   VT, Promote);
968       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
969       setOperationAction(ISD::SELECT, VT, Promote);
970       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
971     }
972
973     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
974 #endif
975   }
976
977   // We want to custom lower some of our intrinsics.
978   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
979
980   // Add/Sub/Mul with overflow operations are custom lowered.
981   setOperationAction(ISD::SADDO, MVT::i32, Custom);
982   setOperationAction(ISD::UADDO, MVT::i32, Custom);
983   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
984   setOperationAction(ISD::USUBO, MVT::i32, Custom);
985   setOperationAction(ISD::SMULO, MVT::i32, Custom);
986
987   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
988   // handle type legalization for these operations here.
989   //
990   // FIXME: We really should do custom legalization for addition and
991   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
992   // than generic legalization for 64-bit multiplication-with-overflow, though.
993   if (Subtarget->is64Bit()) {
994     setOperationAction(ISD::SADDO, MVT::i64, Custom);
995     setOperationAction(ISD::UADDO, MVT::i64, Custom);
996     setOperationAction(ISD::SSUBO, MVT::i64, Custom);
997     setOperationAction(ISD::USUBO, MVT::i64, Custom);
998     setOperationAction(ISD::SMULO, MVT::i64, Custom);
999   }
1000
1001   if (!Subtarget->is64Bit()) {
1002     // These libcalls are not available in 32-bit.
1003     setLibcallName(RTLIB::SHL_I128, 0);
1004     setLibcallName(RTLIB::SRL_I128, 0);
1005     setLibcallName(RTLIB::SRA_I128, 0);
1006   }
1007
1008   // We have target-specific dag combine patterns for the following nodes:
1009   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1010   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1011   setTargetDAGCombine(ISD::BUILD_VECTOR);
1012   setTargetDAGCombine(ISD::SELECT);
1013   setTargetDAGCombine(ISD::SHL);
1014   setTargetDAGCombine(ISD::SRA);
1015   setTargetDAGCombine(ISD::SRL);
1016   setTargetDAGCombine(ISD::OR);
1017   setTargetDAGCombine(ISD::STORE);
1018   setTargetDAGCombine(ISD::ZERO_EXTEND);
1019   if (Subtarget->is64Bit())
1020     setTargetDAGCombine(ISD::MUL);
1021
1022   computeRegisterProperties();
1023
1024   // FIXME: These should be based on subtarget info. Plus, the values should
1025   // be smaller when we are in optimizing for size mode.
1026   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1027   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1028   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1029   setPrefLoopAlignment(16);
1030   benefitFromCodePlacementOpt = true;
1031 }
1032
1033
1034 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1035   return MVT::i8;
1036 }
1037
1038
1039 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1040 /// the desired ByVal argument alignment.
1041 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1042   if (MaxAlign == 16)
1043     return;
1044   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1045     if (VTy->getBitWidth() == 128)
1046       MaxAlign = 16;
1047   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1048     unsigned EltAlign = 0;
1049     getMaxByValAlign(ATy->getElementType(), EltAlign);
1050     if (EltAlign > MaxAlign)
1051       MaxAlign = EltAlign;
1052   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1053     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1054       unsigned EltAlign = 0;
1055       getMaxByValAlign(STy->getElementType(i), EltAlign);
1056       if (EltAlign > MaxAlign)
1057         MaxAlign = EltAlign;
1058       if (MaxAlign == 16)
1059         break;
1060     }
1061   }
1062   return;
1063 }
1064
1065 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1066 /// function arguments in the caller parameter area. For X86, aggregates
1067 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1068 /// are at 4-byte boundaries.
1069 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1070   if (Subtarget->is64Bit()) {
1071     // Max of 8 and alignment of type.
1072     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1073     if (TyAlign > 8)
1074       return TyAlign;
1075     return 8;
1076   }
1077
1078   unsigned Align = 4;
1079   if (Subtarget->hasSSE1())
1080     getMaxByValAlign(Ty, Align);
1081   return Align;
1082 }
1083
1084 /// getOptimalMemOpType - Returns the target specific optimal type for load
1085 /// and store operations as a result of memset, memcpy, and memmove
1086 /// lowering. If DstAlign is zero that means it's safe to destination
1087 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1088 /// means there isn't a need to check it against alignment requirement,
1089 /// probably because the source does not need to be loaded. If
1090 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1091 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1092 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1093 /// constant so it does not need to be loaded.
1094 /// It returns EVT::Other if the type should be determined using generic
1095 /// target-independent logic.
1096 EVT
1097 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1098                                        unsigned DstAlign, unsigned SrcAlign,
1099                                        bool NonScalarIntSafe,
1100                                        bool MemcpyStrSrc,
1101                                        MachineFunction &MF) const {
1102   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1103   // linux.  This is because the stack realignment code can't handle certain
1104   // cases like PR2962.  This should be removed when PR2962 is fixed.
1105   const Function *F = MF.getFunction();
1106   if (NonScalarIntSafe &&
1107       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1108     if (Size >= 16 &&
1109         (Subtarget->isUnalignedMemAccessFast() ||
1110          ((DstAlign == 0 || DstAlign >= 16) &&
1111           (SrcAlign == 0 || SrcAlign >= 16))) &&
1112         Subtarget->getStackAlignment() >= 16) {
1113       if (Subtarget->hasSSE2())
1114         return MVT::v4i32;
1115       if (Subtarget->hasSSE1())
1116         return MVT::v4f32;
1117     } else if (!MemcpyStrSrc && Size >= 8 &&
1118                !Subtarget->is64Bit() &&
1119                Subtarget->getStackAlignment() >= 8 &&
1120                Subtarget->hasSSE2()) {
1121       // Do not use f64 to lower memcpy if source is string constant. It's
1122       // better to use i32 to avoid the loads.
1123       return MVT::f64;
1124     }
1125   }
1126   if (Subtarget->is64Bit() && Size >= 8)
1127     return MVT::i64;
1128   return MVT::i32;
1129 }
1130
1131 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1132 /// current function.  The returned value is a member of the
1133 /// MachineJumpTableInfo::JTEntryKind enum.
1134 unsigned X86TargetLowering::getJumpTableEncoding() const {
1135   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1136   // symbol.
1137   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1138       Subtarget->isPICStyleGOT())
1139     return MachineJumpTableInfo::EK_Custom32;
1140   
1141   // Otherwise, use the normal jump table encoding heuristics.
1142   return TargetLowering::getJumpTableEncoding();
1143 }
1144
1145 /// getPICBaseSymbol - Return the X86-32 PIC base.
1146 MCSymbol *
1147 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1148                                     MCContext &Ctx) const {
1149   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1150   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1151                                Twine(MF->getFunctionNumber())+"$pb");
1152 }
1153
1154
1155 const MCExpr *
1156 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1157                                              const MachineBasicBlock *MBB,
1158                                              unsigned uid,MCContext &Ctx) const{
1159   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1160          Subtarget->isPICStyleGOT());
1161   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1162   // entries.
1163   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1164                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1165 }
1166
1167 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1168 /// jumptable.
1169 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1170                                                     SelectionDAG &DAG) const {
1171   if (!Subtarget->is64Bit())
1172     // This doesn't have DebugLoc associated with it, but is not really the
1173     // same as a Register.
1174     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1175   return Table;
1176 }
1177
1178 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1179 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1180 /// MCExpr.
1181 const MCExpr *X86TargetLowering::
1182 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1183                              MCContext &Ctx) const {
1184   // X86-64 uses RIP relative addressing based on the jump table label.
1185   if (Subtarget->isPICStyleRIPRel())
1186     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1187
1188   // Otherwise, the reference is relative to the PIC base.
1189   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1190 }
1191
1192 /// getFunctionAlignment - Return the Log2 alignment of this function.
1193 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1194   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1195 }
1196
1197 std::pair<const TargetRegisterClass*, uint8_t>
1198 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1199   const TargetRegisterClass *RRC = 0;
1200   uint8_t Cost = 1;
1201   switch (VT.getSimpleVT().SimpleTy) {
1202   default:
1203     return TargetLowering::findRepresentativeClass(VT);
1204   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1205     RRC = (Subtarget->is64Bit()
1206            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1207     break;
1208   case MVT::v8i8: case MVT::v4i16:
1209   case MVT::v2i32: case MVT::v1i64: 
1210     RRC = X86::VR64RegisterClass;
1211     break;
1212   case MVT::f32: case MVT::f64:
1213   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1214   case MVT::v4f32: case MVT::v2f64:
1215   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1216   case MVT::v4f64:
1217     RRC = X86::VR128RegisterClass;
1218     break;
1219   }
1220   return std::make_pair(RRC, Cost);
1221 }
1222
1223 unsigned
1224 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1225                                        MachineFunction &MF) const {
1226   unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1227   switch (RC->getID()) {
1228   default:
1229     return 0;
1230   case X86::GR32RegClassID:
1231     return 4 - FPDiff;
1232   case X86::GR64RegClassID:
1233     return 8 - FPDiff;
1234   case X86::VR128RegClassID:
1235     return Subtarget->is64Bit() ? 10 : 4;
1236   case X86::VR64RegClassID:
1237     return 4;
1238   }
1239 }
1240
1241 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1242                                                unsigned &Offset) const {
1243   if (!Subtarget->isTargetLinux())
1244     return false;
1245
1246   if (Subtarget->is64Bit()) {
1247     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1248     Offset = 0x28;
1249     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1250       AddressSpace = 256;
1251     else
1252       AddressSpace = 257;
1253   } else {
1254     // %gs:0x14 on i386
1255     Offset = 0x14;
1256     AddressSpace = 256;
1257   }
1258   return true;
1259 }
1260
1261
1262 //===----------------------------------------------------------------------===//
1263 //               Return Value Calling Convention Implementation
1264 //===----------------------------------------------------------------------===//
1265
1266 #include "X86GenCallingConv.inc"
1267
1268 bool 
1269 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1270                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1271                         LLVMContext &Context) const {
1272   SmallVector<CCValAssign, 16> RVLocs;
1273   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1274                  RVLocs, Context);
1275   return CCInfo.CheckReturn(Outs, RetCC_X86);
1276 }
1277
1278 SDValue
1279 X86TargetLowering::LowerReturn(SDValue Chain,
1280                                CallingConv::ID CallConv, bool isVarArg,
1281                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1282                                const SmallVectorImpl<SDValue> &OutVals,
1283                                DebugLoc dl, SelectionDAG &DAG) const {
1284   MachineFunction &MF = DAG.getMachineFunction();
1285   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1286
1287   SmallVector<CCValAssign, 16> RVLocs;
1288   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1289                  RVLocs, *DAG.getContext());
1290   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1291
1292   // Add the regs to the liveout set for the function.
1293   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1294   for (unsigned i = 0; i != RVLocs.size(); ++i)
1295     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1296       MRI.addLiveOut(RVLocs[i].getLocReg());
1297
1298   SDValue Flag;
1299
1300   SmallVector<SDValue, 6> RetOps;
1301   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1302   // Operand #1 = Bytes To Pop
1303   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1304                    MVT::i16));
1305
1306   // Copy the result values into the output registers.
1307   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1308     CCValAssign &VA = RVLocs[i];
1309     assert(VA.isRegLoc() && "Can only return in registers!");
1310     SDValue ValToCopy = OutVals[i];
1311     EVT ValVT = ValToCopy.getValueType();
1312
1313     // If this is x86-64, and we disabled SSE, we can't return FP values
1314     if ((ValVT == MVT::f32 || ValVT == MVT::f64) &&
1315         (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1316       report_fatal_error("SSE register return with SSE disabled");
1317     }
1318     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1319     // llvm-gcc has never done it right and no one has noticed, so this
1320     // should be OK for now.
1321     if (ValVT == MVT::f64 &&
1322         (Subtarget->is64Bit() && !Subtarget->hasSSE2())) {
1323       report_fatal_error("SSE2 register return with SSE2 disabled");
1324     }
1325
1326     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1327     // the RET instruction and handled by the FP Stackifier.
1328     if (VA.getLocReg() == X86::ST0 ||
1329         VA.getLocReg() == X86::ST1) {
1330       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1331       // change the value to the FP stack register class.
1332       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1333         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1334       RetOps.push_back(ValToCopy);
1335       // Don't emit a copytoreg.
1336       continue;
1337     }
1338
1339     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1340     // which is returned in RAX / RDX.
1341     if (Subtarget->is64Bit()) {
1342       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1343         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1344         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1345           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1346                                   ValToCopy);
1347       }
1348     }
1349
1350     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1351     Flag = Chain.getValue(1);
1352   }
1353
1354   // The x86-64 ABI for returning structs by value requires that we copy
1355   // the sret argument into %rax for the return. We saved the argument into
1356   // a virtual register in the entry block, so now we copy the value out
1357   // and into %rax.
1358   if (Subtarget->is64Bit() &&
1359       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1360     MachineFunction &MF = DAG.getMachineFunction();
1361     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1362     unsigned Reg = FuncInfo->getSRetReturnReg();
1363     assert(Reg && 
1364            "SRetReturnReg should have been set in LowerFormalArguments().");
1365     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1366
1367     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1368     Flag = Chain.getValue(1);
1369
1370     // RAX now acts like a return value.
1371     MRI.addLiveOut(X86::RAX);
1372   }
1373
1374   RetOps[0] = Chain;  // Update chain.
1375
1376   // Add the flag if we have it.
1377   if (Flag.getNode())
1378     RetOps.push_back(Flag);
1379
1380   return DAG.getNode(X86ISD::RET_FLAG, dl,
1381                      MVT::Other, &RetOps[0], RetOps.size());
1382 }
1383
1384 /// LowerCallResult - Lower the result values of a call into the
1385 /// appropriate copies out of appropriate physical registers.
1386 ///
1387 SDValue
1388 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1389                                    CallingConv::ID CallConv, bool isVarArg,
1390                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1391                                    DebugLoc dl, SelectionDAG &DAG,
1392                                    SmallVectorImpl<SDValue> &InVals) const {
1393
1394   // Assign locations to each value returned by this call.
1395   SmallVector<CCValAssign, 16> RVLocs;
1396   bool Is64Bit = Subtarget->is64Bit();
1397   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1398                  RVLocs, *DAG.getContext());
1399   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1400
1401   // Copy all of the result registers out of their specified physreg.
1402   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1403     CCValAssign &VA = RVLocs[i];
1404     EVT CopyVT = VA.getValVT();
1405
1406     // If this is x86-64, and we disabled SSE, we can't return FP values
1407     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1408         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1409       report_fatal_error("SSE register return with SSE disabled");
1410     }
1411
1412     SDValue Val;
1413
1414     // If this is a call to a function that returns an fp value on the floating
1415     // point stack, we must guarantee the the value is popped from the stack, so
1416     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1417     // if the return value is not used. We use the FpGET_ST0 instructions
1418     // instead.
1419     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1420       // If we prefer to use the value in xmm registers, copy it out as f80 and
1421       // use a truncate to move it from fp stack reg to xmm reg.
1422       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1423       bool isST0 = VA.getLocReg() == X86::ST0;
1424       unsigned Opc = 0;
1425       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1426       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1427       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1428       SDValue Ops[] = { Chain, InFlag };
1429       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1430                                          Ops, 2), 1);
1431       Val = Chain.getValue(0);
1432
1433       // Round the f80 to the right size, which also moves it to the appropriate
1434       // xmm register.
1435       if (CopyVT != VA.getValVT())
1436         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1437                           // This truncation won't change the value.
1438                           DAG.getIntPtrConstant(1));
1439     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1440       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1441       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1442         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1443                                    MVT::v2i64, InFlag).getValue(1);
1444         Val = Chain.getValue(0);
1445         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1446                           Val, DAG.getConstant(0, MVT::i64));
1447       } else {
1448         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1449                                    MVT::i64, InFlag).getValue(1);
1450         Val = Chain.getValue(0);
1451       }
1452       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1453     } else {
1454       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1455                                  CopyVT, InFlag).getValue(1);
1456       Val = Chain.getValue(0);
1457     }
1458     InFlag = Chain.getValue(2);
1459     InVals.push_back(Val);
1460   }
1461
1462   return Chain;
1463 }
1464
1465
1466 //===----------------------------------------------------------------------===//
1467 //                C & StdCall & Fast Calling Convention implementation
1468 //===----------------------------------------------------------------------===//
1469 //  StdCall calling convention seems to be standard for many Windows' API
1470 //  routines and around. It differs from C calling convention just a little:
1471 //  callee should clean up the stack, not caller. Symbols should be also
1472 //  decorated in some fancy way :) It doesn't support any vector arguments.
1473 //  For info on fast calling convention see Fast Calling Convention (tail call)
1474 //  implementation LowerX86_32FastCCCallTo.
1475
1476 /// CallIsStructReturn - Determines whether a call uses struct return
1477 /// semantics.
1478 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1479   if (Outs.empty())
1480     return false;
1481
1482   return Outs[0].Flags.isSRet();
1483 }
1484
1485 /// ArgsAreStructReturn - Determines whether a function uses struct
1486 /// return semantics.
1487 static bool
1488 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1489   if (Ins.empty())
1490     return false;
1491
1492   return Ins[0].Flags.isSRet();
1493 }
1494
1495 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1496 /// given CallingConvention value.
1497 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1498   if (Subtarget->is64Bit()) {
1499     if (CC == CallingConv::GHC)
1500       return CC_X86_64_GHC;
1501     else if (Subtarget->isTargetWin64())
1502       return CC_X86_Win64_C;
1503     else
1504       return CC_X86_64_C;
1505   }
1506
1507   if (CC == CallingConv::X86_FastCall)
1508     return CC_X86_32_FastCall;
1509   else if (CC == CallingConv::X86_ThisCall)
1510     return CC_X86_32_ThisCall;
1511   else if (CC == CallingConv::Fast)
1512     return CC_X86_32_FastCC;
1513   else if (CC == CallingConv::GHC)
1514     return CC_X86_32_GHC;
1515   else
1516     return CC_X86_32_C;
1517 }
1518
1519 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1520 /// by "Src" to address "Dst" with size and alignment information specified by
1521 /// the specific parameter attribute. The copy will be passed as a byval
1522 /// function parameter.
1523 static SDValue
1524 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1525                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1526                           DebugLoc dl) {
1527   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1528   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1529                        /*isVolatile*/false, /*AlwaysInline=*/true,
1530                        NULL, 0, NULL, 0);
1531 }
1532
1533 /// IsTailCallConvention - Return true if the calling convention is one that
1534 /// supports tail call optimization.
1535 static bool IsTailCallConvention(CallingConv::ID CC) {
1536   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1537 }
1538
1539 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1540 /// a tailcall target by changing its ABI.
1541 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1542   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1543 }
1544
1545 SDValue
1546 X86TargetLowering::LowerMemArgument(SDValue Chain,
1547                                     CallingConv::ID CallConv,
1548                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1549                                     DebugLoc dl, SelectionDAG &DAG,
1550                                     const CCValAssign &VA,
1551                                     MachineFrameInfo *MFI,
1552                                     unsigned i) const {
1553   // Create the nodes corresponding to a load from this parameter slot.
1554   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1555   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1556   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1557   EVT ValVT;
1558
1559   // If value is passed by pointer we have address passed instead of the value
1560   // itself.
1561   if (VA.getLocInfo() == CCValAssign::Indirect)
1562     ValVT = VA.getLocVT();
1563   else
1564     ValVT = VA.getValVT();
1565
1566   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1567   // changed with more analysis.
1568   // In case of tail call optimization mark all arguments mutable. Since they
1569   // could be overwritten by lowering of arguments in case of a tail call.
1570   if (Flags.isByVal()) {
1571     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1572                                     VA.getLocMemOffset(), isImmutable);
1573     return DAG.getFrameIndex(FI, getPointerTy());
1574   } else {
1575     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1576                                     VA.getLocMemOffset(), isImmutable);
1577     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1578     return DAG.getLoad(ValVT, dl, Chain, FIN,
1579                        PseudoSourceValue::getFixedStack(FI), 0,
1580                        false, false, 0);
1581   }
1582 }
1583
1584 SDValue
1585 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1586                                         CallingConv::ID CallConv,
1587                                         bool isVarArg,
1588                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1589                                         DebugLoc dl,
1590                                         SelectionDAG &DAG,
1591                                         SmallVectorImpl<SDValue> &InVals)
1592                                           const {
1593   MachineFunction &MF = DAG.getMachineFunction();
1594   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1595
1596   const Function* Fn = MF.getFunction();
1597   if (Fn->hasExternalLinkage() &&
1598       Subtarget->isTargetCygMing() &&
1599       Fn->getName() == "main")
1600     FuncInfo->setForceFramePointer(true);
1601
1602   MachineFrameInfo *MFI = MF.getFrameInfo();
1603   bool Is64Bit = Subtarget->is64Bit();
1604   bool IsWin64 = Subtarget->isTargetWin64();
1605
1606   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1607          "Var args not supported with calling convention fastcc or ghc");
1608
1609   // Assign locations to all of the incoming arguments.
1610   SmallVector<CCValAssign, 16> ArgLocs;
1611   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1612                  ArgLocs, *DAG.getContext());
1613   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1614
1615   unsigned LastVal = ~0U;
1616   SDValue ArgValue;
1617   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1618     CCValAssign &VA = ArgLocs[i];
1619     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1620     // places.
1621     assert(VA.getValNo() != LastVal &&
1622            "Don't support value assigned to multiple locs yet");
1623     LastVal = VA.getValNo();
1624
1625     if (VA.isRegLoc()) {
1626       EVT RegVT = VA.getLocVT();
1627       TargetRegisterClass *RC = NULL;
1628       if (RegVT == MVT::i32)
1629         RC = X86::GR32RegisterClass;
1630       else if (Is64Bit && RegVT == MVT::i64)
1631         RC = X86::GR64RegisterClass;
1632       else if (RegVT == MVT::f32)
1633         RC = X86::FR32RegisterClass;
1634       else if (RegVT == MVT::f64)
1635         RC = X86::FR64RegisterClass;
1636       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1637         RC = X86::VR128RegisterClass;
1638       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1639         RC = X86::VR64RegisterClass;
1640       else
1641         llvm_unreachable("Unknown argument type!");
1642
1643       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1644       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1645
1646       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1647       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1648       // right size.
1649       if (VA.getLocInfo() == CCValAssign::SExt)
1650         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1651                                DAG.getValueType(VA.getValVT()));
1652       else if (VA.getLocInfo() == CCValAssign::ZExt)
1653         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1654                                DAG.getValueType(VA.getValVT()));
1655       else if (VA.getLocInfo() == CCValAssign::BCvt)
1656         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1657
1658       if (VA.isExtInLoc()) {
1659         // Handle MMX values passed in XMM regs.
1660         if (RegVT.isVector()) {
1661           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1662                                  ArgValue, DAG.getConstant(0, MVT::i64));
1663           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1664         } else
1665           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1666       }
1667     } else {
1668       assert(VA.isMemLoc());
1669       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1670     }
1671
1672     // If value is passed via pointer - do a load.
1673     if (VA.getLocInfo() == CCValAssign::Indirect)
1674       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1675                              false, false, 0);
1676
1677     InVals.push_back(ArgValue);
1678   }
1679
1680   // The x86-64 ABI for returning structs by value requires that we copy
1681   // the sret argument into %rax for the return. Save the argument into
1682   // a virtual register so that we can access it from the return points.
1683   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1684     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1685     unsigned Reg = FuncInfo->getSRetReturnReg();
1686     if (!Reg) {
1687       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1688       FuncInfo->setSRetReturnReg(Reg);
1689     }
1690     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1691     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1692   }
1693
1694   unsigned StackSize = CCInfo.getNextStackOffset();
1695   // Align stack specially for tail calls.
1696   if (FuncIsMadeTailCallSafe(CallConv))
1697     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1698
1699   // If the function takes variable number of arguments, make a frame index for
1700   // the start of the first vararg value... for expansion of llvm.va_start.
1701   if (isVarArg) {
1702     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1703                     CallConv != CallingConv::X86_ThisCall)) {
1704       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1705     }
1706     if (Is64Bit) {
1707       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1708
1709       // FIXME: We should really autogenerate these arrays
1710       static const unsigned GPR64ArgRegsWin64[] = {
1711         X86::RCX, X86::RDX, X86::R8,  X86::R9
1712       };
1713       static const unsigned XMMArgRegsWin64[] = {
1714         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1715       };
1716       static const unsigned GPR64ArgRegs64Bit[] = {
1717         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1718       };
1719       static const unsigned XMMArgRegs64Bit[] = {
1720         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1721         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1722       };
1723       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1724
1725       if (IsWin64) {
1726         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1727         GPR64ArgRegs = GPR64ArgRegsWin64;
1728         XMMArgRegs = XMMArgRegsWin64;
1729       } else {
1730         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1731         GPR64ArgRegs = GPR64ArgRegs64Bit;
1732         XMMArgRegs = XMMArgRegs64Bit;
1733       }
1734       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1735                                                        TotalNumIntRegs);
1736       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1737                                                        TotalNumXMMRegs);
1738
1739       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1740       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1741              "SSE register cannot be used when SSE is disabled!");
1742       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1743              "SSE register cannot be used when SSE is disabled!");
1744       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1745         // Kernel mode asks for SSE to be disabled, so don't push them
1746         // on the stack.
1747         TotalNumXMMRegs = 0;
1748
1749       // For X86-64, if there are vararg parameters that are passed via
1750       // registers, then we must store them to their spots on the stack so they
1751       // may be loaded by deferencing the result of va_next.
1752       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1753       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1754       FuncInfo->setRegSaveFrameIndex(
1755         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1756                                false));
1757
1758       // Store the integer parameter registers.
1759       SmallVector<SDValue, 8> MemOps;
1760       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1761                                         getPointerTy());
1762       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1763       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1764         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1765                                   DAG.getIntPtrConstant(Offset));
1766         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1767                                      X86::GR64RegisterClass);
1768         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1769         SDValue Store =
1770           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1771                        PseudoSourceValue::getFixedStack(
1772                          FuncInfo->getRegSaveFrameIndex()),
1773                        Offset, false, false, 0);
1774         MemOps.push_back(Store);
1775         Offset += 8;
1776       }
1777
1778       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1779         // Now store the XMM (fp + vector) parameter registers.
1780         SmallVector<SDValue, 11> SaveXMMOps;
1781         SaveXMMOps.push_back(Chain);
1782
1783         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1784         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1785         SaveXMMOps.push_back(ALVal);
1786
1787         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1788                                FuncInfo->getRegSaveFrameIndex()));
1789         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1790                                FuncInfo->getVarArgsFPOffset()));
1791
1792         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1793           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1794                                        X86::VR128RegisterClass);
1795           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1796           SaveXMMOps.push_back(Val);
1797         }
1798         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1799                                      MVT::Other,
1800                                      &SaveXMMOps[0], SaveXMMOps.size()));
1801       }
1802
1803       if (!MemOps.empty())
1804         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1805                             &MemOps[0], MemOps.size());
1806     }
1807   }
1808
1809   // Some CCs need callee pop.
1810   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1811     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1812   } else {
1813     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1814     // If this is an sret function, the return should pop the hidden pointer.
1815     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1816       FuncInfo->setBytesToPopOnReturn(4);
1817   }
1818
1819   if (!Is64Bit) {
1820     // RegSaveFrameIndex is X86-64 only.
1821     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1822     if (CallConv == CallingConv::X86_FastCall ||
1823         CallConv == CallingConv::X86_ThisCall)
1824       // fastcc functions can't have varargs.
1825       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1826   }
1827
1828   return Chain;
1829 }
1830
1831 SDValue
1832 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1833                                     SDValue StackPtr, SDValue Arg,
1834                                     DebugLoc dl, SelectionDAG &DAG,
1835                                     const CCValAssign &VA,
1836                                     ISD::ArgFlagsTy Flags) const {
1837   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1838   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1839   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1840   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1841   if (Flags.isByVal()) {
1842     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1843   }
1844   return DAG.getStore(Chain, dl, Arg, PtrOff,
1845                       PseudoSourceValue::getStack(), LocMemOffset,
1846                       false, false, 0);
1847 }
1848
1849 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1850 /// optimization is performed and it is required.
1851 SDValue
1852 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1853                                            SDValue &OutRetAddr, SDValue Chain,
1854                                            bool IsTailCall, bool Is64Bit,
1855                                            int FPDiff, DebugLoc dl) const {
1856   // Adjust the Return address stack slot.
1857   EVT VT = getPointerTy();
1858   OutRetAddr = getReturnAddressFrameIndex(DAG);
1859
1860   // Load the "old" Return address.
1861   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1862   return SDValue(OutRetAddr.getNode(), 1);
1863 }
1864
1865 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1866 /// optimization is performed and it is required (FPDiff!=0).
1867 static SDValue
1868 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1869                          SDValue Chain, SDValue RetAddrFrIdx,
1870                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1871   // Store the return address to the appropriate stack slot.
1872   if (!FPDiff) return Chain;
1873   // Calculate the new stack slot for the return address.
1874   int SlotSize = Is64Bit ? 8 : 4;
1875   int NewReturnAddrFI =
1876     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1877   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1878   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1879   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1880                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1881                        false, false, 0);
1882   return Chain;
1883 }
1884
1885 SDValue
1886 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1887                              CallingConv::ID CallConv, bool isVarArg,
1888                              bool &isTailCall,
1889                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1890                              const SmallVectorImpl<SDValue> &OutVals,
1891                              const SmallVectorImpl<ISD::InputArg> &Ins,
1892                              DebugLoc dl, SelectionDAG &DAG,
1893                              SmallVectorImpl<SDValue> &InVals) const {
1894   MachineFunction &MF = DAG.getMachineFunction();
1895   bool Is64Bit        = Subtarget->is64Bit();
1896   bool IsStructRet    = CallIsStructReturn(Outs);
1897   bool IsSibcall      = false;
1898
1899   if (isTailCall) {
1900     // Check if it's really possible to do a tail call.
1901     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1902                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1903                                                    Outs, OutVals, Ins, DAG);
1904
1905     // Sibcalls are automatically detected tailcalls which do not require
1906     // ABI changes.
1907     if (!GuaranteedTailCallOpt && isTailCall)
1908       IsSibcall = true;
1909
1910     if (isTailCall)
1911       ++NumTailCalls;
1912   }
1913
1914   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1915          "Var args not supported with calling convention fastcc or ghc");
1916
1917   // Analyze operands of the call, assigning locations to each operand.
1918   SmallVector<CCValAssign, 16> ArgLocs;
1919   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1920                  ArgLocs, *DAG.getContext());
1921   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1922
1923   // Get a count of how many bytes are to be pushed on the stack.
1924   unsigned NumBytes = CCInfo.getNextStackOffset();
1925   if (IsSibcall)
1926     // This is a sibcall. The memory operands are available in caller's
1927     // own caller's stack.
1928     NumBytes = 0;
1929   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1930     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1931
1932   int FPDiff = 0;
1933   if (isTailCall && !IsSibcall) {
1934     // Lower arguments at fp - stackoffset + fpdiff.
1935     unsigned NumBytesCallerPushed =
1936       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1937     FPDiff = NumBytesCallerPushed - NumBytes;
1938
1939     // Set the delta of movement of the returnaddr stackslot.
1940     // But only set if delta is greater than previous delta.
1941     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1942       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1943   }
1944
1945   if (!IsSibcall)
1946     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1947
1948   SDValue RetAddrFrIdx;
1949   // Load return adress for tail calls.
1950   if (isTailCall && FPDiff)
1951     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1952                                     Is64Bit, FPDiff, dl);
1953
1954   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1955   SmallVector<SDValue, 8> MemOpChains;
1956   SDValue StackPtr;
1957
1958   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1959   // of tail call optimization arguments are handle later.
1960   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1961     CCValAssign &VA = ArgLocs[i];
1962     EVT RegVT = VA.getLocVT();
1963     SDValue Arg = OutVals[i];
1964     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1965     bool isByVal = Flags.isByVal();
1966
1967     // Promote the value if needed.
1968     switch (VA.getLocInfo()) {
1969     default: llvm_unreachable("Unknown loc info!");
1970     case CCValAssign::Full: break;
1971     case CCValAssign::SExt:
1972       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1973       break;
1974     case CCValAssign::ZExt:
1975       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1976       break;
1977     case CCValAssign::AExt:
1978       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1979         // Special case: passing MMX values in XMM registers.
1980         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1981         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1982         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1983       } else
1984         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1985       break;
1986     case CCValAssign::BCvt:
1987       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1988       break;
1989     case CCValAssign::Indirect: {
1990       // Store the argument.
1991       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1992       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1993       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1994                            PseudoSourceValue::getFixedStack(FI), 0,
1995                            false, false, 0);
1996       Arg = SpillSlot;
1997       break;
1998     }
1999     }
2000
2001     if (VA.isRegLoc()) {
2002       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2003     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2004       assert(VA.isMemLoc());
2005       if (StackPtr.getNode() == 0)
2006         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2007       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2008                                              dl, DAG, VA, Flags));
2009     }
2010   }
2011
2012   if (!MemOpChains.empty())
2013     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2014                         &MemOpChains[0], MemOpChains.size());
2015
2016   // Build a sequence of copy-to-reg nodes chained together with token chain
2017   // and flag operands which copy the outgoing args into registers.
2018   SDValue InFlag;
2019   // Tail call byval lowering might overwrite argument registers so in case of
2020   // tail call optimization the copies to registers are lowered later.
2021   if (!isTailCall)
2022     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2023       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2024                                RegsToPass[i].second, InFlag);
2025       InFlag = Chain.getValue(1);
2026     }
2027
2028   if (Subtarget->isPICStyleGOT()) {
2029     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2030     // GOT pointer.
2031     if (!isTailCall) {
2032       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2033                                DAG.getNode(X86ISD::GlobalBaseReg,
2034                                            DebugLoc(), getPointerTy()),
2035                                InFlag);
2036       InFlag = Chain.getValue(1);
2037     } else {
2038       // If we are tail calling and generating PIC/GOT style code load the
2039       // address of the callee into ECX. The value in ecx is used as target of
2040       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2041       // for tail calls on PIC/GOT architectures. Normally we would just put the
2042       // address of GOT into ebx and then call target@PLT. But for tail calls
2043       // ebx would be restored (since ebx is callee saved) before jumping to the
2044       // target@PLT.
2045
2046       // Note: The actual moving to ECX is done further down.
2047       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2048       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2049           !G->getGlobal()->hasProtectedVisibility())
2050         Callee = LowerGlobalAddress(Callee, DAG);
2051       else if (isa<ExternalSymbolSDNode>(Callee))
2052         Callee = LowerExternalSymbol(Callee, DAG);
2053     }
2054   }
2055
2056   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2057     // From AMD64 ABI document:
2058     // For calls that may call functions that use varargs or stdargs
2059     // (prototype-less calls or calls to functions containing ellipsis (...) in
2060     // the declaration) %al is used as hidden argument to specify the number
2061     // of SSE registers used. The contents of %al do not need to match exactly
2062     // the number of registers, but must be an ubound on the number of SSE
2063     // registers used and is in the range 0 - 8 inclusive.
2064
2065     // Count the number of XMM registers allocated.
2066     static const unsigned XMMArgRegs[] = {
2067       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2068       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2069     };
2070     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2071     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2072            && "SSE registers cannot be used when SSE is disabled");
2073
2074     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2075                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2076     InFlag = Chain.getValue(1);
2077   }
2078
2079
2080   // For tail calls lower the arguments to the 'real' stack slot.
2081   if (isTailCall) {
2082     // Force all the incoming stack arguments to be loaded from the stack
2083     // before any new outgoing arguments are stored to the stack, because the
2084     // outgoing stack slots may alias the incoming argument stack slots, and
2085     // the alias isn't otherwise explicit. This is slightly more conservative
2086     // than necessary, because it means that each store effectively depends
2087     // on every argument instead of just those arguments it would clobber.
2088     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2089
2090     SmallVector<SDValue, 8> MemOpChains2;
2091     SDValue FIN;
2092     int FI = 0;
2093     // Do not flag preceeding copytoreg stuff together with the following stuff.
2094     InFlag = SDValue();
2095     if (GuaranteedTailCallOpt) {
2096       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2097         CCValAssign &VA = ArgLocs[i];
2098         if (VA.isRegLoc())
2099           continue;
2100         assert(VA.isMemLoc());
2101         SDValue Arg = OutVals[i];
2102         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2103         // Create frame index.
2104         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2105         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2106         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2107         FIN = DAG.getFrameIndex(FI, getPointerTy());
2108
2109         if (Flags.isByVal()) {
2110           // Copy relative to framepointer.
2111           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2112           if (StackPtr.getNode() == 0)
2113             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2114                                           getPointerTy());
2115           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2116
2117           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2118                                                            ArgChain,
2119                                                            Flags, DAG, dl));
2120         } else {
2121           // Store relative to framepointer.
2122           MemOpChains2.push_back(
2123             DAG.getStore(ArgChain, dl, Arg, FIN,
2124                          PseudoSourceValue::getFixedStack(FI), 0,
2125                          false, false, 0));
2126         }
2127       }
2128     }
2129
2130     if (!MemOpChains2.empty())
2131       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2132                           &MemOpChains2[0], MemOpChains2.size());
2133
2134     // Copy arguments to their registers.
2135     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2136       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2137                                RegsToPass[i].second, InFlag);
2138       InFlag = Chain.getValue(1);
2139     }
2140     InFlag =SDValue();
2141
2142     // Store the return address to the appropriate stack slot.
2143     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2144                                      FPDiff, dl);
2145   }
2146
2147   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2148     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2149     // In the 64-bit large code model, we have to make all calls
2150     // through a register, since the call instruction's 32-bit
2151     // pc-relative offset may not be large enough to hold the whole
2152     // address.
2153   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2154     // If the callee is a GlobalAddress node (quite common, every direct call
2155     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2156     // it.
2157
2158     // We should use extra load for direct calls to dllimported functions in
2159     // non-JIT mode.
2160     const GlobalValue *GV = G->getGlobal();
2161     if (!GV->hasDLLImportLinkage()) {
2162       unsigned char OpFlags = 0;
2163
2164       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2165       // external symbols most go through the PLT in PIC mode.  If the symbol
2166       // has hidden or protected visibility, or if it is static or local, then
2167       // we don't need to use the PLT - we can directly call it.
2168       if (Subtarget->isTargetELF() &&
2169           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2170           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2171         OpFlags = X86II::MO_PLT;
2172       } else if (Subtarget->isPICStyleStubAny() &&
2173                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2174                Subtarget->getDarwinVers() < 9) {
2175         // PC-relative references to external symbols should go through $stub,
2176         // unless we're building with the leopard linker or later, which
2177         // automatically synthesizes these stubs.
2178         OpFlags = X86II::MO_DARWIN_STUB;
2179       }
2180
2181       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2182                                           G->getOffset(), OpFlags);
2183     }
2184   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2185     unsigned char OpFlags = 0;
2186
2187     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2188     // symbols should go through the PLT.
2189     if (Subtarget->isTargetELF() &&
2190         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2191       OpFlags = X86II::MO_PLT;
2192     } else if (Subtarget->isPICStyleStubAny() &&
2193              Subtarget->getDarwinVers() < 9) {
2194       // PC-relative references to external symbols should go through $stub,
2195       // unless we're building with the leopard linker or later, which
2196       // automatically synthesizes these stubs.
2197       OpFlags = X86II::MO_DARWIN_STUB;
2198     }
2199
2200     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2201                                          OpFlags);
2202   }
2203
2204   // Returns a chain & a flag for retval copy to use.
2205   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2206   SmallVector<SDValue, 8> Ops;
2207
2208   if (!IsSibcall && isTailCall) {
2209     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2210                            DAG.getIntPtrConstant(0, true), InFlag);
2211     InFlag = Chain.getValue(1);
2212   }
2213
2214   Ops.push_back(Chain);
2215   Ops.push_back(Callee);
2216
2217   if (isTailCall)
2218     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2219
2220   // Add argument registers to the end of the list so that they are known live
2221   // into the call.
2222   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2223     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2224                                   RegsToPass[i].second.getValueType()));
2225
2226   // Add an implicit use GOT pointer in EBX.
2227   if (!isTailCall && Subtarget->isPICStyleGOT())
2228     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2229
2230   // Add an implicit use of AL for x86 vararg functions.
2231   if (Is64Bit && isVarArg)
2232     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2233
2234   if (InFlag.getNode())
2235     Ops.push_back(InFlag);
2236
2237   if (isTailCall) {
2238     // We used to do:
2239     //// If this is the first return lowered for this function, add the regs
2240     //// to the liveout set for the function.
2241     // This isn't right, although it's probably harmless on x86; liveouts
2242     // should be computed from returns not tail calls.  Consider a void
2243     // function making a tail call to a function returning int.
2244     return DAG.getNode(X86ISD::TC_RETURN, dl,
2245                        NodeTys, &Ops[0], Ops.size());
2246   }
2247
2248   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2249   InFlag = Chain.getValue(1);
2250
2251   // Create the CALLSEQ_END node.
2252   unsigned NumBytesForCalleeToPush;
2253   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2254     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2255   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2256     // If this is a call to a struct-return function, the callee
2257     // pops the hidden struct pointer, so we have to push it back.
2258     // This is common for Darwin/X86, Linux & Mingw32 targets.
2259     NumBytesForCalleeToPush = 4;
2260   else
2261     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2262
2263   // Returns a flag for retval copy to use.
2264   if (!IsSibcall) {
2265     Chain = DAG.getCALLSEQ_END(Chain,
2266                                DAG.getIntPtrConstant(NumBytes, true),
2267                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2268                                                      true),
2269                                InFlag);
2270     InFlag = Chain.getValue(1);
2271   }
2272
2273   // Handle result values, copying them out of physregs into vregs that we
2274   // return.
2275   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2276                          Ins, dl, DAG, InVals);
2277 }
2278
2279
2280 //===----------------------------------------------------------------------===//
2281 //                Fast Calling Convention (tail call) implementation
2282 //===----------------------------------------------------------------------===//
2283
2284 //  Like std call, callee cleans arguments, convention except that ECX is
2285 //  reserved for storing the tail called function address. Only 2 registers are
2286 //  free for argument passing (inreg). Tail call optimization is performed
2287 //  provided:
2288 //                * tailcallopt is enabled
2289 //                * caller/callee are fastcc
2290 //  On X86_64 architecture with GOT-style position independent code only local
2291 //  (within module) calls are supported at the moment.
2292 //  To keep the stack aligned according to platform abi the function
2293 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2294 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2295 //  If a tail called function callee has more arguments than the caller the
2296 //  caller needs to make sure that there is room to move the RETADDR to. This is
2297 //  achieved by reserving an area the size of the argument delta right after the
2298 //  original REtADDR, but before the saved framepointer or the spilled registers
2299 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2300 //  stack layout:
2301 //    arg1
2302 //    arg2
2303 //    RETADDR
2304 //    [ new RETADDR
2305 //      move area ]
2306 //    (possible EBP)
2307 //    ESI
2308 //    EDI
2309 //    local1 ..
2310
2311 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2312 /// for a 16 byte align requirement.
2313 unsigned
2314 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2315                                                SelectionDAG& DAG) const {
2316   MachineFunction &MF = DAG.getMachineFunction();
2317   const TargetMachine &TM = MF.getTarget();
2318   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2319   unsigned StackAlignment = TFI.getStackAlignment();
2320   uint64_t AlignMask = StackAlignment - 1;
2321   int64_t Offset = StackSize;
2322   uint64_t SlotSize = TD->getPointerSize();
2323   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2324     // Number smaller than 12 so just add the difference.
2325     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2326   } else {
2327     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2328     Offset = ((~AlignMask) & Offset) + StackAlignment +
2329       (StackAlignment-SlotSize);
2330   }
2331   return Offset;
2332 }
2333
2334 /// MatchingStackOffset - Return true if the given stack call argument is
2335 /// already available in the same position (relatively) of the caller's
2336 /// incoming argument stack.
2337 static
2338 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2339                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2340                          const X86InstrInfo *TII) {
2341   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2342   int FI = INT_MAX;
2343   if (Arg.getOpcode() == ISD::CopyFromReg) {
2344     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2345     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2346       return false;
2347     MachineInstr *Def = MRI->getVRegDef(VR);
2348     if (!Def)
2349       return false;
2350     if (!Flags.isByVal()) {
2351       if (!TII->isLoadFromStackSlot(Def, FI))
2352         return false;
2353     } else {
2354       unsigned Opcode = Def->getOpcode();
2355       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2356           Def->getOperand(1).isFI()) {
2357         FI = Def->getOperand(1).getIndex();
2358         Bytes = Flags.getByValSize();
2359       } else
2360         return false;
2361     }
2362   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2363     if (Flags.isByVal())
2364       // ByVal argument is passed in as a pointer but it's now being
2365       // dereferenced. e.g.
2366       // define @foo(%struct.X* %A) {
2367       //   tail call @bar(%struct.X* byval %A)
2368       // }
2369       return false;
2370     SDValue Ptr = Ld->getBasePtr();
2371     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2372     if (!FINode)
2373       return false;
2374     FI = FINode->getIndex();
2375   } else
2376     return false;
2377
2378   assert(FI != INT_MAX);
2379   if (!MFI->isFixedObjectIndex(FI))
2380     return false;
2381   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2382 }
2383
2384 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2385 /// for tail call optimization. Targets which want to do tail call
2386 /// optimization should implement this function.
2387 bool
2388 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2389                                                      CallingConv::ID CalleeCC,
2390                                                      bool isVarArg,
2391                                                      bool isCalleeStructRet,
2392                                                      bool isCallerStructRet,
2393                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2394                                     const SmallVectorImpl<SDValue> &OutVals,
2395                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2396                                                      SelectionDAG& DAG) const {
2397   if (!IsTailCallConvention(CalleeCC) &&
2398       CalleeCC != CallingConv::C)
2399     return false;
2400
2401   // If -tailcallopt is specified, make fastcc functions tail-callable.
2402   const MachineFunction &MF = DAG.getMachineFunction();
2403   const Function *CallerF = DAG.getMachineFunction().getFunction();
2404   CallingConv::ID CallerCC = CallerF->getCallingConv();
2405   bool CCMatch = CallerCC == CalleeCC;
2406
2407   if (GuaranteedTailCallOpt) {
2408     if (IsTailCallConvention(CalleeCC) && CCMatch)
2409       return true;
2410     return false;
2411   }
2412
2413   // Look for obvious safe cases to perform tail call optimization that do not
2414   // require ABI changes. This is what gcc calls sibcall.
2415
2416   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2417   // emit a special epilogue.
2418   if (RegInfo->needsStackRealignment(MF))
2419     return false;
2420
2421   // Do not sibcall optimize vararg calls unless the call site is not passing
2422   // any arguments.
2423   if (isVarArg && !Outs.empty())
2424     return false;
2425
2426   // Also avoid sibcall optimization if either caller or callee uses struct
2427   // return semantics.
2428   if (isCalleeStructRet || isCallerStructRet)
2429     return false;
2430
2431   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2432   // Therefore if it's not used by the call it is not safe to optimize this into
2433   // a sibcall.
2434   bool Unused = false;
2435   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2436     if (!Ins[i].Used) {
2437       Unused = true;
2438       break;
2439     }
2440   }
2441   if (Unused) {
2442     SmallVector<CCValAssign, 16> RVLocs;
2443     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2444                    RVLocs, *DAG.getContext());
2445     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2446     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2447       CCValAssign &VA = RVLocs[i];
2448       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2449         return false;
2450     }
2451   }
2452
2453   // If the calling conventions do not match, then we'd better make sure the
2454   // results are returned in the same way as what the caller expects.
2455   if (!CCMatch) {
2456     SmallVector<CCValAssign, 16> RVLocs1;
2457     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2458                     RVLocs1, *DAG.getContext());
2459     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2460
2461     SmallVector<CCValAssign, 16> RVLocs2;
2462     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2463                     RVLocs2, *DAG.getContext());
2464     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2465
2466     if (RVLocs1.size() != RVLocs2.size())
2467       return false;
2468     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2469       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2470         return false;
2471       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2472         return false;
2473       if (RVLocs1[i].isRegLoc()) {
2474         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2475           return false;
2476       } else {
2477         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2478           return false;
2479       }
2480     }
2481   }
2482
2483   // If the callee takes no arguments then go on to check the results of the
2484   // call.
2485   if (!Outs.empty()) {
2486     // Check if stack adjustment is needed. For now, do not do this if any
2487     // argument is passed on the stack.
2488     SmallVector<CCValAssign, 16> ArgLocs;
2489     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2490                    ArgLocs, *DAG.getContext());
2491     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2492     if (CCInfo.getNextStackOffset()) {
2493       MachineFunction &MF = DAG.getMachineFunction();
2494       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2495         return false;
2496       if (Subtarget->isTargetWin64())
2497         // Win64 ABI has additional complications.
2498         return false;
2499
2500       // Check if the arguments are already laid out in the right way as
2501       // the caller's fixed stack objects.
2502       MachineFrameInfo *MFI = MF.getFrameInfo();
2503       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2504       const X86InstrInfo *TII =
2505         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2506       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2507         CCValAssign &VA = ArgLocs[i];
2508         SDValue Arg = OutVals[i];
2509         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2510         if (VA.getLocInfo() == CCValAssign::Indirect)
2511           return false;
2512         if (!VA.isRegLoc()) {
2513           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2514                                    MFI, MRI, TII))
2515             return false;
2516         }
2517       }
2518     }
2519
2520     // If the tailcall address may be in a register, then make sure it's
2521     // possible to register allocate for it. In 32-bit, the call address can
2522     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2523     // callee-saved registers are restored. These happen to be the same
2524     // registers used to pass 'inreg' arguments so watch out for those.
2525     if (!Subtarget->is64Bit() &&
2526         !isa<GlobalAddressSDNode>(Callee) &&
2527         !isa<ExternalSymbolSDNode>(Callee)) {
2528       unsigned NumInRegs = 0;
2529       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2530         CCValAssign &VA = ArgLocs[i];
2531         if (!VA.isRegLoc())
2532           continue;
2533         unsigned Reg = VA.getLocReg();
2534         switch (Reg) {
2535         default: break;
2536         case X86::EAX: case X86::EDX: case X86::ECX:
2537           if (++NumInRegs == 3)
2538             return false;
2539           break;
2540         }
2541       }
2542     }
2543   }
2544
2545   return true;
2546 }
2547
2548 FastISel *
2549 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2550   return X86::createFastISel(funcInfo);
2551 }
2552
2553
2554 //===----------------------------------------------------------------------===//
2555 //                           Other Lowering Hooks
2556 //===----------------------------------------------------------------------===//
2557
2558
2559 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2560   MachineFunction &MF = DAG.getMachineFunction();
2561   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2562   int ReturnAddrIndex = FuncInfo->getRAIndex();
2563
2564   if (ReturnAddrIndex == 0) {
2565     // Set up a frame object for the return address.
2566     uint64_t SlotSize = TD->getPointerSize();
2567     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2568                                                            false);
2569     FuncInfo->setRAIndex(ReturnAddrIndex);
2570   }
2571
2572   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2573 }
2574
2575
2576 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2577                                        bool hasSymbolicDisplacement) {
2578   // Offset should fit into 32 bit immediate field.
2579   if (!isInt<32>(Offset))
2580     return false;
2581
2582   // If we don't have a symbolic displacement - we don't have any extra
2583   // restrictions.
2584   if (!hasSymbolicDisplacement)
2585     return true;
2586
2587   // FIXME: Some tweaks might be needed for medium code model.
2588   if (M != CodeModel::Small && M != CodeModel::Kernel)
2589     return false;
2590
2591   // For small code model we assume that latest object is 16MB before end of 31
2592   // bits boundary. We may also accept pretty large negative constants knowing
2593   // that all objects are in the positive half of address space.
2594   if (M == CodeModel::Small && Offset < 16*1024*1024)
2595     return true;
2596
2597   // For kernel code model we know that all object resist in the negative half
2598   // of 32bits address space. We may not accept negative offsets, since they may
2599   // be just off and we may accept pretty large positive ones.
2600   if (M == CodeModel::Kernel && Offset > 0)
2601     return true;
2602
2603   return false;
2604 }
2605
2606 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2607 /// specific condition code, returning the condition code and the LHS/RHS of the
2608 /// comparison to make.
2609 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2610                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2611   if (!isFP) {
2612     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2613       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2614         // X > -1   -> X == 0, jump !sign.
2615         RHS = DAG.getConstant(0, RHS.getValueType());
2616         return X86::COND_NS;
2617       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2618         // X < 0   -> X == 0, jump on sign.
2619         return X86::COND_S;
2620       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2621         // X < 1   -> X <= 0
2622         RHS = DAG.getConstant(0, RHS.getValueType());
2623         return X86::COND_LE;
2624       }
2625     }
2626
2627     switch (SetCCOpcode) {
2628     default: llvm_unreachable("Invalid integer condition!");
2629     case ISD::SETEQ:  return X86::COND_E;
2630     case ISD::SETGT:  return X86::COND_G;
2631     case ISD::SETGE:  return X86::COND_GE;
2632     case ISD::SETLT:  return X86::COND_L;
2633     case ISD::SETLE:  return X86::COND_LE;
2634     case ISD::SETNE:  return X86::COND_NE;
2635     case ISD::SETULT: return X86::COND_B;
2636     case ISD::SETUGT: return X86::COND_A;
2637     case ISD::SETULE: return X86::COND_BE;
2638     case ISD::SETUGE: return X86::COND_AE;
2639     }
2640   }
2641
2642   // First determine if it is required or is profitable to flip the operands.
2643
2644   // If LHS is a foldable load, but RHS is not, flip the condition.
2645   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2646       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2647     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2648     std::swap(LHS, RHS);
2649   }
2650
2651   switch (SetCCOpcode) {
2652   default: break;
2653   case ISD::SETOLT:
2654   case ISD::SETOLE:
2655   case ISD::SETUGT:
2656   case ISD::SETUGE:
2657     std::swap(LHS, RHS);
2658     break;
2659   }
2660
2661   // On a floating point condition, the flags are set as follows:
2662   // ZF  PF  CF   op
2663   //  0 | 0 | 0 | X > Y
2664   //  0 | 0 | 1 | X < Y
2665   //  1 | 0 | 0 | X == Y
2666   //  1 | 1 | 1 | unordered
2667   switch (SetCCOpcode) {
2668   default: llvm_unreachable("Condcode should be pre-legalized away");
2669   case ISD::SETUEQ:
2670   case ISD::SETEQ:   return X86::COND_E;
2671   case ISD::SETOLT:              // flipped
2672   case ISD::SETOGT:
2673   case ISD::SETGT:   return X86::COND_A;
2674   case ISD::SETOLE:              // flipped
2675   case ISD::SETOGE:
2676   case ISD::SETGE:   return X86::COND_AE;
2677   case ISD::SETUGT:              // flipped
2678   case ISD::SETULT:
2679   case ISD::SETLT:   return X86::COND_B;
2680   case ISD::SETUGE:              // flipped
2681   case ISD::SETULE:
2682   case ISD::SETLE:   return X86::COND_BE;
2683   case ISD::SETONE:
2684   case ISD::SETNE:   return X86::COND_NE;
2685   case ISD::SETUO:   return X86::COND_P;
2686   case ISD::SETO:    return X86::COND_NP;
2687   case ISD::SETOEQ:
2688   case ISD::SETUNE:  return X86::COND_INVALID;
2689   }
2690 }
2691
2692 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2693 /// code. Current x86 isa includes the following FP cmov instructions:
2694 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2695 static bool hasFPCMov(unsigned X86CC) {
2696   switch (X86CC) {
2697   default:
2698     return false;
2699   case X86::COND_B:
2700   case X86::COND_BE:
2701   case X86::COND_E:
2702   case X86::COND_P:
2703   case X86::COND_A:
2704   case X86::COND_AE:
2705   case X86::COND_NE:
2706   case X86::COND_NP:
2707     return true;
2708   }
2709 }
2710
2711 /// isFPImmLegal - Returns true if the target can instruction select the
2712 /// specified FP immediate natively. If false, the legalizer will
2713 /// materialize the FP immediate as a load from a constant pool.
2714 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2715   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2716     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2717       return true;
2718   }
2719   return false;
2720 }
2721
2722 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2723 /// the specified range (L, H].
2724 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2725   return (Val < 0) || (Val >= Low && Val < Hi);
2726 }
2727
2728 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2729 /// specified value.
2730 static bool isUndefOrEqual(int Val, int CmpVal) {
2731   if (Val < 0 || Val == CmpVal)
2732     return true;
2733   return false;
2734 }
2735
2736 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2737 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2738 /// the second operand.
2739 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2740   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2741     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2742   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2743     return (Mask[0] < 2 && Mask[1] < 2);
2744   return false;
2745 }
2746
2747 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2748   SmallVector<int, 8> M;
2749   N->getMask(M);
2750   return ::isPSHUFDMask(M, N->getValueType(0));
2751 }
2752
2753 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2754 /// is suitable for input to PSHUFHW.
2755 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2756   if (VT != MVT::v8i16)
2757     return false;
2758
2759   // Lower quadword copied in order or undef.
2760   for (int i = 0; i != 4; ++i)
2761     if (Mask[i] >= 0 && Mask[i] != i)
2762       return false;
2763
2764   // Upper quadword shuffled.
2765   for (int i = 4; i != 8; ++i)
2766     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2767       return false;
2768
2769   return true;
2770 }
2771
2772 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2773   SmallVector<int, 8> M;
2774   N->getMask(M);
2775   return ::isPSHUFHWMask(M, N->getValueType(0));
2776 }
2777
2778 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2779 /// is suitable for input to PSHUFLW.
2780 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2781   if (VT != MVT::v8i16)
2782     return false;
2783
2784   // Upper quadword copied in order.
2785   for (int i = 4; i != 8; ++i)
2786     if (Mask[i] >= 0 && Mask[i] != i)
2787       return false;
2788
2789   // Lower quadword shuffled.
2790   for (int i = 0; i != 4; ++i)
2791     if (Mask[i] >= 4)
2792       return false;
2793
2794   return true;
2795 }
2796
2797 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2798   SmallVector<int, 8> M;
2799   N->getMask(M);
2800   return ::isPSHUFLWMask(M, N->getValueType(0));
2801 }
2802
2803 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2804 /// is suitable for input to PALIGNR.
2805 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2806                           bool hasSSSE3) {
2807   int i, e = VT.getVectorNumElements();
2808   
2809   // Do not handle v2i64 / v2f64 shuffles with palignr.
2810   if (e < 4 || !hasSSSE3)
2811     return false;
2812   
2813   for (i = 0; i != e; ++i)
2814     if (Mask[i] >= 0)
2815       break;
2816   
2817   // All undef, not a palignr.
2818   if (i == e)
2819     return false;
2820
2821   // Determine if it's ok to perform a palignr with only the LHS, since we
2822   // don't have access to the actual shuffle elements to see if RHS is undef.
2823   bool Unary = Mask[i] < (int)e;
2824   bool NeedsUnary = false;
2825
2826   int s = Mask[i] - i;
2827   
2828   // Check the rest of the elements to see if they are consecutive.
2829   for (++i; i != e; ++i) {
2830     int m = Mask[i];
2831     if (m < 0) 
2832       continue;
2833     
2834     Unary = Unary && (m < (int)e);
2835     NeedsUnary = NeedsUnary || (m < s);
2836
2837     if (NeedsUnary && !Unary)
2838       return false;
2839     if (Unary && m != ((s+i) & (e-1)))
2840       return false;
2841     if (!Unary && m != (s+i))
2842       return false;
2843   }
2844   return true;
2845 }
2846
2847 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2848   SmallVector<int, 8> M;
2849   N->getMask(M);
2850   return ::isPALIGNRMask(M, N->getValueType(0), true);
2851 }
2852
2853 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2854 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2855 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2856   int NumElems = VT.getVectorNumElements();
2857   if (NumElems != 2 && NumElems != 4)
2858     return false;
2859
2860   int Half = NumElems / 2;
2861   for (int i = 0; i < Half; ++i)
2862     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2863       return false;
2864   for (int i = Half; i < NumElems; ++i)
2865     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2866       return false;
2867
2868   return true;
2869 }
2870
2871 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2872   SmallVector<int, 8> M;
2873   N->getMask(M);
2874   return ::isSHUFPMask(M, N->getValueType(0));
2875 }
2876
2877 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2878 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2879 /// half elements to come from vector 1 (which would equal the dest.) and
2880 /// the upper half to come from vector 2.
2881 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2882   int NumElems = VT.getVectorNumElements();
2883
2884   if (NumElems != 2 && NumElems != 4)
2885     return false;
2886
2887   int Half = NumElems / 2;
2888   for (int i = 0; i < Half; ++i)
2889     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2890       return false;
2891   for (int i = Half; i < NumElems; ++i)
2892     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2893       return false;
2894   return true;
2895 }
2896
2897 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2898   SmallVector<int, 8> M;
2899   N->getMask(M);
2900   return isCommutedSHUFPMask(M, N->getValueType(0));
2901 }
2902
2903 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2904 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2905 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2906   if (N->getValueType(0).getVectorNumElements() != 4)
2907     return false;
2908
2909   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2910   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2911          isUndefOrEqual(N->getMaskElt(1), 7) &&
2912          isUndefOrEqual(N->getMaskElt(2), 2) &&
2913          isUndefOrEqual(N->getMaskElt(3), 3);
2914 }
2915
2916 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2917 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2918 /// <2, 3, 2, 3>
2919 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2920   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2921   
2922   if (NumElems != 4)
2923     return false;
2924   
2925   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2926   isUndefOrEqual(N->getMaskElt(1), 3) &&
2927   isUndefOrEqual(N->getMaskElt(2), 2) &&
2928   isUndefOrEqual(N->getMaskElt(3), 3);
2929 }
2930
2931 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2932 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2933 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2934   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2935
2936   if (NumElems != 2 && NumElems != 4)
2937     return false;
2938
2939   for (unsigned i = 0; i < NumElems/2; ++i)
2940     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2941       return false;
2942
2943   for (unsigned i = NumElems/2; i < NumElems; ++i)
2944     if (!isUndefOrEqual(N->getMaskElt(i), i))
2945       return false;
2946
2947   return true;
2948 }
2949
2950 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2951 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2952 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2953   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2954
2955   if (NumElems != 2 && NumElems != 4)
2956     return false;
2957
2958   for (unsigned i = 0; i < NumElems/2; ++i)
2959     if (!isUndefOrEqual(N->getMaskElt(i), i))
2960       return false;
2961
2962   for (unsigned i = 0; i < NumElems/2; ++i)
2963     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2964       return false;
2965
2966   return true;
2967 }
2968
2969 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2970 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2971 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2972                          bool V2IsSplat = false) {
2973   int NumElts = VT.getVectorNumElements();
2974   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2975     return false;
2976
2977   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2978     int BitI  = Mask[i];
2979     int BitI1 = Mask[i+1];
2980     if (!isUndefOrEqual(BitI, j))
2981       return false;
2982     if (V2IsSplat) {
2983       if (!isUndefOrEqual(BitI1, NumElts))
2984         return false;
2985     } else {
2986       if (!isUndefOrEqual(BitI1, j + NumElts))
2987         return false;
2988     }
2989   }
2990   return true;
2991 }
2992
2993 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2994   SmallVector<int, 8> M;
2995   N->getMask(M);
2996   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2997 }
2998
2999 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3000 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3001 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3002                          bool V2IsSplat = false) {
3003   int NumElts = VT.getVectorNumElements();
3004   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3005     return false;
3006
3007   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3008     int BitI  = Mask[i];
3009     int BitI1 = Mask[i+1];
3010     if (!isUndefOrEqual(BitI, j + NumElts/2))
3011       return false;
3012     if (V2IsSplat) {
3013       if (isUndefOrEqual(BitI1, NumElts))
3014         return false;
3015     } else {
3016       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3017         return false;
3018     }
3019   }
3020   return true;
3021 }
3022
3023 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3024   SmallVector<int, 8> M;
3025   N->getMask(M);
3026   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3027 }
3028
3029 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3030 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3031 /// <0, 0, 1, 1>
3032 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3033   int NumElems = VT.getVectorNumElements();
3034   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3035     return false;
3036
3037   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3038     int BitI  = Mask[i];
3039     int BitI1 = Mask[i+1];
3040     if (!isUndefOrEqual(BitI, j))
3041       return false;
3042     if (!isUndefOrEqual(BitI1, j))
3043       return false;
3044   }
3045   return true;
3046 }
3047
3048 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3049   SmallVector<int, 8> M;
3050   N->getMask(M);
3051   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3052 }
3053
3054 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3055 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3056 /// <2, 2, 3, 3>
3057 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3058   int NumElems = VT.getVectorNumElements();
3059   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3060     return false;
3061
3062   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3063     int BitI  = Mask[i];
3064     int BitI1 = Mask[i+1];
3065     if (!isUndefOrEqual(BitI, j))
3066       return false;
3067     if (!isUndefOrEqual(BitI1, j))
3068       return false;
3069   }
3070   return true;
3071 }
3072
3073 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3074   SmallVector<int, 8> M;
3075   N->getMask(M);
3076   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3077 }
3078
3079 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3080 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3081 /// MOVSD, and MOVD, i.e. setting the lowest element.
3082 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3083   if (VT.getVectorElementType().getSizeInBits() < 32)
3084     return false;
3085
3086   int NumElts = VT.getVectorNumElements();
3087
3088   if (!isUndefOrEqual(Mask[0], NumElts))
3089     return false;
3090
3091   for (int i = 1; i < NumElts; ++i)
3092     if (!isUndefOrEqual(Mask[i], i))
3093       return false;
3094
3095   return true;
3096 }
3097
3098 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3099   SmallVector<int, 8> M;
3100   N->getMask(M);
3101   return ::isMOVLMask(M, N->getValueType(0));
3102 }
3103
3104 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3105 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3106 /// element of vector 2 and the other elements to come from vector 1 in order.
3107 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3108                                bool V2IsSplat = false, bool V2IsUndef = false) {
3109   int NumOps = VT.getVectorNumElements();
3110   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3111     return false;
3112
3113   if (!isUndefOrEqual(Mask[0], 0))
3114     return false;
3115
3116   for (int i = 1; i < NumOps; ++i)
3117     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3118           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3119           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3120       return false;
3121
3122   return true;
3123 }
3124
3125 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3126                            bool V2IsUndef = false) {
3127   SmallVector<int, 8> M;
3128   N->getMask(M);
3129   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3130 }
3131
3132 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3133 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3134 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3135   if (N->getValueType(0).getVectorNumElements() != 4)
3136     return false;
3137
3138   // Expect 1, 1, 3, 3
3139   for (unsigned i = 0; i < 2; ++i) {
3140     int Elt = N->getMaskElt(i);
3141     if (Elt >= 0 && Elt != 1)
3142       return false;
3143   }
3144
3145   bool HasHi = false;
3146   for (unsigned i = 2; i < 4; ++i) {
3147     int Elt = N->getMaskElt(i);
3148     if (Elt >= 0 && Elt != 3)
3149       return false;
3150     if (Elt == 3)
3151       HasHi = true;
3152   }
3153   // Don't use movshdup if it can be done with a shufps.
3154   // FIXME: verify that matching u, u, 3, 3 is what we want.
3155   return HasHi;
3156 }
3157
3158 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3159 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3160 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3161   if (N->getValueType(0).getVectorNumElements() != 4)
3162     return false;
3163
3164   // Expect 0, 0, 2, 2
3165   for (unsigned i = 0; i < 2; ++i)
3166     if (N->getMaskElt(i) > 0)
3167       return false;
3168
3169   bool HasHi = false;
3170   for (unsigned i = 2; i < 4; ++i) {
3171     int Elt = N->getMaskElt(i);
3172     if (Elt >= 0 && Elt != 2)
3173       return false;
3174     if (Elt == 2)
3175       HasHi = true;
3176   }
3177   // Don't use movsldup if it can be done with a shufps.
3178   return HasHi;
3179 }
3180
3181 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3182 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3183 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3184   int e = N->getValueType(0).getVectorNumElements() / 2;
3185
3186   for (int i = 0; i < e; ++i)
3187     if (!isUndefOrEqual(N->getMaskElt(i), i))
3188       return false;
3189   for (int i = 0; i < e; ++i)
3190     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3191       return false;
3192   return true;
3193 }
3194
3195 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3196 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3197 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3198   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3199   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3200
3201   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3202   unsigned Mask = 0;
3203   for (int i = 0; i < NumOperands; ++i) {
3204     int Val = SVOp->getMaskElt(NumOperands-i-1);
3205     if (Val < 0) Val = 0;
3206     if (Val >= NumOperands) Val -= NumOperands;
3207     Mask |= Val;
3208     if (i != NumOperands - 1)
3209       Mask <<= Shift;
3210   }
3211   return Mask;
3212 }
3213
3214 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3215 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3216 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3217   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3218   unsigned Mask = 0;
3219   // 8 nodes, but we only care about the last 4.
3220   for (unsigned i = 7; i >= 4; --i) {
3221     int Val = SVOp->getMaskElt(i);
3222     if (Val >= 0)
3223       Mask |= (Val - 4);
3224     if (i != 4)
3225       Mask <<= 2;
3226   }
3227   return Mask;
3228 }
3229
3230 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3231 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3232 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3233   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3234   unsigned Mask = 0;
3235   // 8 nodes, but we only care about the first 4.
3236   for (int i = 3; i >= 0; --i) {
3237     int Val = SVOp->getMaskElt(i);
3238     if (Val >= 0)
3239       Mask |= Val;
3240     if (i != 0)
3241       Mask <<= 2;
3242   }
3243   return Mask;
3244 }
3245
3246 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3247 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3248 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3249   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3250   EVT VVT = N->getValueType(0);
3251   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3252   int Val = 0;
3253
3254   unsigned i, e;
3255   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3256     Val = SVOp->getMaskElt(i);
3257     if (Val >= 0)
3258       break;
3259   }
3260   return (Val - i) * EltSize;
3261 }
3262
3263 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3264 /// constant +0.0.
3265 bool X86::isZeroNode(SDValue Elt) {
3266   return ((isa<ConstantSDNode>(Elt) &&
3267            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3268           (isa<ConstantFPSDNode>(Elt) &&
3269            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3270 }
3271
3272 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3273 /// their permute mask.
3274 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3275                                     SelectionDAG &DAG) {
3276   EVT VT = SVOp->getValueType(0);
3277   unsigned NumElems = VT.getVectorNumElements();
3278   SmallVector<int, 8> MaskVec;
3279
3280   for (unsigned i = 0; i != NumElems; ++i) {
3281     int idx = SVOp->getMaskElt(i);
3282     if (idx < 0)
3283       MaskVec.push_back(idx);
3284     else if (idx < (int)NumElems)
3285       MaskVec.push_back(idx + NumElems);
3286     else
3287       MaskVec.push_back(idx - NumElems);
3288   }
3289   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3290                               SVOp->getOperand(0), &MaskVec[0]);
3291 }
3292
3293 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3294 /// the two vector operands have swapped position.
3295 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3296   unsigned NumElems = VT.getVectorNumElements();
3297   for (unsigned i = 0; i != NumElems; ++i) {
3298     int idx = Mask[i];
3299     if (idx < 0)
3300       continue;
3301     else if (idx < (int)NumElems)
3302       Mask[i] = idx + NumElems;
3303     else
3304       Mask[i] = idx - NumElems;
3305   }
3306 }
3307
3308 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3309 /// match movhlps. The lower half elements should come from upper half of
3310 /// V1 (and in order), and the upper half elements should come from the upper
3311 /// half of V2 (and in order).
3312 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3313   if (Op->getValueType(0).getVectorNumElements() != 4)
3314     return false;
3315   for (unsigned i = 0, e = 2; i != e; ++i)
3316     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3317       return false;
3318   for (unsigned i = 2; i != 4; ++i)
3319     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3320       return false;
3321   return true;
3322 }
3323
3324 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3325 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3326 /// required.
3327 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3328   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3329     return false;
3330   N = N->getOperand(0).getNode();
3331   if (!ISD::isNON_EXTLoad(N))
3332     return false;
3333   if (LD)
3334     *LD = cast<LoadSDNode>(N);
3335   return true;
3336 }
3337
3338 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3339 /// match movlp{s|d}. The lower half elements should come from lower half of
3340 /// V1 (and in order), and the upper half elements should come from the upper
3341 /// half of V2 (and in order). And since V1 will become the source of the
3342 /// MOVLP, it must be either a vector load or a scalar load to vector.
3343 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3344                                ShuffleVectorSDNode *Op) {
3345   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3346     return false;
3347   // Is V2 is a vector load, don't do this transformation. We will try to use
3348   // load folding shufps op.
3349   if (ISD::isNON_EXTLoad(V2))
3350     return false;
3351
3352   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3353
3354   if (NumElems != 2 && NumElems != 4)
3355     return false;
3356   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3357     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3358       return false;
3359   for (unsigned i = NumElems/2; i != NumElems; ++i)
3360     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3361       return false;
3362   return true;
3363 }
3364
3365 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3366 /// all the same.
3367 static bool isSplatVector(SDNode *N) {
3368   if (N->getOpcode() != ISD::BUILD_VECTOR)
3369     return false;
3370
3371   SDValue SplatValue = N->getOperand(0);
3372   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3373     if (N->getOperand(i) != SplatValue)
3374       return false;
3375   return true;
3376 }
3377
3378 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3379 /// to an zero vector.
3380 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3381 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3382   SDValue V1 = N->getOperand(0);
3383   SDValue V2 = N->getOperand(1);
3384   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3385   for (unsigned i = 0; i != NumElems; ++i) {
3386     int Idx = N->getMaskElt(i);
3387     if (Idx >= (int)NumElems) {
3388       unsigned Opc = V2.getOpcode();
3389       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3390         continue;
3391       if (Opc != ISD::BUILD_VECTOR ||
3392           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3393         return false;
3394     } else if (Idx >= 0) {
3395       unsigned Opc = V1.getOpcode();
3396       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3397         continue;
3398       if (Opc != ISD::BUILD_VECTOR ||
3399           !X86::isZeroNode(V1.getOperand(Idx)))
3400         return false;
3401     }
3402   }
3403   return true;
3404 }
3405
3406 /// getZeroVector - Returns a vector of specified type with all zero elements.
3407 ///
3408 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3409                              DebugLoc dl) {
3410   assert(VT.isVector() && "Expected a vector type");
3411
3412   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3413   // type.  This ensures they get CSE'd.
3414   SDValue Vec;
3415   if (VT.getSizeInBits() == 64) { // MMX
3416     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3417     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3418   } else if (HasSSE2) {  // SSE2
3419     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3420     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3421   } else { // SSE1
3422     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3423     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3424   }
3425   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3426 }
3427
3428 /// getOnesVector - Returns a vector of specified type with all bits set.
3429 ///
3430 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3431   assert(VT.isVector() && "Expected a vector type");
3432
3433   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3434   // type.  This ensures they get CSE'd.
3435   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3436   SDValue Vec;
3437   if (VT.getSizeInBits() == 64)  // MMX
3438     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3439   else                                              // SSE
3440     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3441   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3442 }
3443
3444
3445 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3446 /// that point to V2 points to its first element.
3447 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3448   EVT VT = SVOp->getValueType(0);
3449   unsigned NumElems = VT.getVectorNumElements();
3450
3451   bool Changed = false;
3452   SmallVector<int, 8> MaskVec;
3453   SVOp->getMask(MaskVec);
3454
3455   for (unsigned i = 0; i != NumElems; ++i) {
3456     if (MaskVec[i] > (int)NumElems) {
3457       MaskVec[i] = NumElems;
3458       Changed = true;
3459     }
3460   }
3461   if (Changed)
3462     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3463                                 SVOp->getOperand(1), &MaskVec[0]);
3464   return SDValue(SVOp, 0);
3465 }
3466
3467 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3468 /// operation of specified width.
3469 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3470                        SDValue V2) {
3471   unsigned NumElems = VT.getVectorNumElements();
3472   SmallVector<int, 8> Mask;
3473   Mask.push_back(NumElems);
3474   for (unsigned i = 1; i != NumElems; ++i)
3475     Mask.push_back(i);
3476   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3477 }
3478
3479 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3480 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3481                           SDValue V2) {
3482   unsigned NumElems = VT.getVectorNumElements();
3483   SmallVector<int, 8> Mask;
3484   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3485     Mask.push_back(i);
3486     Mask.push_back(i + NumElems);
3487   }
3488   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3489 }
3490
3491 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3492 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3493                           SDValue V2) {
3494   unsigned NumElems = VT.getVectorNumElements();
3495   unsigned Half = NumElems/2;
3496   SmallVector<int, 8> Mask;
3497   for (unsigned i = 0; i != Half; ++i) {
3498     Mask.push_back(i + Half);
3499     Mask.push_back(i + NumElems + Half);
3500   }
3501   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3502 }
3503
3504 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3505 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3506                             bool HasSSE2) {
3507   if (SV->getValueType(0).getVectorNumElements() <= 4)
3508     return SDValue(SV, 0);
3509
3510   EVT PVT = MVT::v4f32;
3511   EVT VT = SV->getValueType(0);
3512   DebugLoc dl = SV->getDebugLoc();
3513   SDValue V1 = SV->getOperand(0);
3514   int NumElems = VT.getVectorNumElements();
3515   int EltNo = SV->getSplatIndex();
3516
3517   // unpack elements to the correct location
3518   while (NumElems > 4) {
3519     if (EltNo < NumElems/2) {
3520       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3521     } else {
3522       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3523       EltNo -= NumElems/2;
3524     }
3525     NumElems >>= 1;
3526   }
3527
3528   // Perform the splat.
3529   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3530   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3531   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3532   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3533 }
3534
3535 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3536 /// vector of zero or undef vector.  This produces a shuffle where the low
3537 /// element of V2 is swizzled into the zero/undef vector, landing at element
3538 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3539 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3540                                              bool isZero, bool HasSSE2,
3541                                              SelectionDAG &DAG) {
3542   EVT VT = V2.getValueType();
3543   SDValue V1 = isZero
3544     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3545   unsigned NumElems = VT.getVectorNumElements();
3546   SmallVector<int, 16> MaskVec;
3547   for (unsigned i = 0; i != NumElems; ++i)
3548     // If this is the insertion idx, put the low elt of V2 here.
3549     MaskVec.push_back(i == Idx ? NumElems : i);
3550   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3551 }
3552
3553 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3554 /// a shuffle that is zero.
3555 static
3556 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3557                                   bool Low, SelectionDAG &DAG) {
3558   unsigned NumZeros = 0;
3559   for (int i = 0; i < NumElems; ++i) {
3560     unsigned Index = Low ? i : NumElems-i-1;
3561     int Idx = SVOp->getMaskElt(Index);
3562     if (Idx < 0) {
3563       ++NumZeros;
3564       continue;
3565     }
3566     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3567     if (Elt.getNode() && X86::isZeroNode(Elt))
3568       ++NumZeros;
3569     else
3570       break;
3571   }
3572   return NumZeros;
3573 }
3574
3575 /// isVectorShift - Returns true if the shuffle can be implemented as a
3576 /// logical left or right shift of a vector.
3577 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3578 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3579                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3580   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3581
3582   isLeft = true;
3583   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3584   if (!NumZeros) {
3585     isLeft = false;
3586     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3587     if (!NumZeros)
3588       return false;
3589   }
3590   bool SeenV1 = false;
3591   bool SeenV2 = false;
3592   for (unsigned i = NumZeros; i < NumElems; ++i) {
3593     unsigned Val = isLeft ? (i - NumZeros) : i;
3594     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3595     if (Idx_ < 0)
3596       continue;
3597     unsigned Idx = (unsigned) Idx_;
3598     if (Idx < NumElems)
3599       SeenV1 = true;
3600     else {
3601       Idx -= NumElems;
3602       SeenV2 = true;
3603     }
3604     if (Idx != Val)
3605       return false;
3606   }
3607   if (SeenV1 && SeenV2)
3608     return false;
3609
3610   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3611   ShAmt = NumZeros;
3612   return true;
3613 }
3614
3615
3616 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3617 ///
3618 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3619                                        unsigned NumNonZero, unsigned NumZero,
3620                                        SelectionDAG &DAG,
3621                                        const TargetLowering &TLI) {
3622   if (NumNonZero > 8)
3623     return SDValue();
3624
3625   DebugLoc dl = Op.getDebugLoc();
3626   SDValue V(0, 0);
3627   bool First = true;
3628   for (unsigned i = 0; i < 16; ++i) {
3629     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3630     if (ThisIsNonZero && First) {
3631       if (NumZero)
3632         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3633       else
3634         V = DAG.getUNDEF(MVT::v8i16);
3635       First = false;
3636     }
3637
3638     if ((i & 1) != 0) {
3639       SDValue ThisElt(0, 0), LastElt(0, 0);
3640       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3641       if (LastIsNonZero) {
3642         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3643                               MVT::i16, Op.getOperand(i-1));
3644       }
3645       if (ThisIsNonZero) {
3646         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3647         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3648                               ThisElt, DAG.getConstant(8, MVT::i8));
3649         if (LastIsNonZero)
3650           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3651       } else
3652         ThisElt = LastElt;
3653
3654       if (ThisElt.getNode())
3655         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3656                         DAG.getIntPtrConstant(i/2));
3657     }
3658   }
3659
3660   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3661 }
3662
3663 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3664 ///
3665 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3666                                      unsigned NumNonZero, unsigned NumZero,
3667                                      SelectionDAG &DAG,
3668                                      const TargetLowering &TLI) {
3669   if (NumNonZero > 4)
3670     return SDValue();
3671
3672   DebugLoc dl = Op.getDebugLoc();
3673   SDValue V(0, 0);
3674   bool First = true;
3675   for (unsigned i = 0; i < 8; ++i) {
3676     bool isNonZero = (NonZeros & (1 << i)) != 0;
3677     if (isNonZero) {
3678       if (First) {
3679         if (NumZero)
3680           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3681         else
3682           V = DAG.getUNDEF(MVT::v8i16);
3683         First = false;
3684       }
3685       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3686                       MVT::v8i16, V, Op.getOperand(i),
3687                       DAG.getIntPtrConstant(i));
3688     }
3689   }
3690
3691   return V;
3692 }
3693
3694 /// getVShift - Return a vector logical shift node.
3695 ///
3696 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3697                          unsigned NumBits, SelectionDAG &DAG,
3698                          const TargetLowering &TLI, DebugLoc dl) {
3699   bool isMMX = VT.getSizeInBits() == 64;
3700   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3701   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3702   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3703   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3704                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3705                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3706 }
3707
3708 SDValue
3709 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3710                                           SelectionDAG &DAG) const {
3711   
3712   // Check if the scalar load can be widened into a vector load. And if
3713   // the address is "base + cst" see if the cst can be "absorbed" into
3714   // the shuffle mask.
3715   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3716     SDValue Ptr = LD->getBasePtr();
3717     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3718       return SDValue();
3719     EVT PVT = LD->getValueType(0);
3720     if (PVT != MVT::i32 && PVT != MVT::f32)
3721       return SDValue();
3722
3723     int FI = -1;
3724     int64_t Offset = 0;
3725     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3726       FI = FINode->getIndex();
3727       Offset = 0;
3728     } else if (Ptr.getOpcode() == ISD::ADD &&
3729                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3730                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3731       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3732       Offset = Ptr.getConstantOperandVal(1);
3733       Ptr = Ptr.getOperand(0);
3734     } else {
3735       return SDValue();
3736     }
3737
3738     SDValue Chain = LD->getChain();
3739     // Make sure the stack object alignment is at least 16.
3740     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3741     if (DAG.InferPtrAlignment(Ptr) < 16) {
3742       if (MFI->isFixedObjectIndex(FI)) {
3743         // Can't change the alignment. FIXME: It's possible to compute
3744         // the exact stack offset and reference FI + adjust offset instead.
3745         // If someone *really* cares about this. That's the way to implement it.
3746         return SDValue();
3747       } else {
3748         MFI->setObjectAlignment(FI, 16);
3749       }
3750     }
3751
3752     // (Offset % 16) must be multiple of 4. Then address is then
3753     // Ptr + (Offset & ~15).
3754     if (Offset < 0)
3755       return SDValue();
3756     if ((Offset % 16) & 3)
3757       return SDValue();
3758     int64_t StartOffset = Offset & ~15;
3759     if (StartOffset)
3760       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3761                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3762
3763     int EltNo = (Offset - StartOffset) >> 2;
3764     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3765     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3766     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3767                              false, false, 0);
3768     // Canonicalize it to a v4i32 shuffle.
3769     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3770     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3771                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3772                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3773   }
3774
3775   return SDValue();
3776 }
3777
3778 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3779 /// vector of type 'VT', see if the elements can be replaced by a single large 
3780 /// load which has the same value as a build_vector whose operands are 'elts'.
3781 ///
3782 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3783 /// 
3784 /// FIXME: we'd also like to handle the case where the last elements are zero
3785 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3786 /// There's even a handy isZeroNode for that purpose.
3787 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3788                                         DebugLoc &dl, SelectionDAG &DAG) {
3789   EVT EltVT = VT.getVectorElementType();
3790   unsigned NumElems = Elts.size();
3791   
3792   LoadSDNode *LDBase = NULL;
3793   unsigned LastLoadedElt = -1U;
3794   
3795   // For each element in the initializer, see if we've found a load or an undef.
3796   // If we don't find an initial load element, or later load elements are 
3797   // non-consecutive, bail out.
3798   for (unsigned i = 0; i < NumElems; ++i) {
3799     SDValue Elt = Elts[i];
3800     
3801     if (!Elt.getNode() ||
3802         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3803       return SDValue();
3804     if (!LDBase) {
3805       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3806         return SDValue();
3807       LDBase = cast<LoadSDNode>(Elt.getNode());
3808       LastLoadedElt = i;
3809       continue;
3810     }
3811     if (Elt.getOpcode() == ISD::UNDEF)
3812       continue;
3813
3814     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3815     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3816       return SDValue();
3817     LastLoadedElt = i;
3818   }
3819
3820   // If we have found an entire vector of loads and undefs, then return a large
3821   // load of the entire vector width starting at the base pointer.  If we found
3822   // consecutive loads for the low half, generate a vzext_load node.
3823   if (LastLoadedElt == NumElems - 1) {
3824     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3825       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3826                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3827                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3828     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3829                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3830                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3831                        LDBase->getAlignment());
3832   } else if (NumElems == 4 && LastLoadedElt == 1) {
3833     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3834     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3835     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3836     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3837   }
3838   return SDValue();
3839 }
3840
3841 SDValue
3842 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3843   DebugLoc dl = Op.getDebugLoc();
3844   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3845   if (ISD::isBuildVectorAllZeros(Op.getNode())
3846       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3847     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3848     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3849     // eliminated on x86-32 hosts.
3850     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3851       return Op;
3852
3853     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3854       return getOnesVector(Op.getValueType(), DAG, dl);
3855     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3856   }
3857
3858   EVT VT = Op.getValueType();
3859   EVT ExtVT = VT.getVectorElementType();
3860   unsigned EVTBits = ExtVT.getSizeInBits();
3861
3862   unsigned NumElems = Op.getNumOperands();
3863   unsigned NumZero  = 0;
3864   unsigned NumNonZero = 0;
3865   unsigned NonZeros = 0;
3866   bool IsAllConstants = true;
3867   SmallSet<SDValue, 8> Values;
3868   for (unsigned i = 0; i < NumElems; ++i) {
3869     SDValue Elt = Op.getOperand(i);
3870     if (Elt.getOpcode() == ISD::UNDEF)
3871       continue;
3872     Values.insert(Elt);
3873     if (Elt.getOpcode() != ISD::Constant &&
3874         Elt.getOpcode() != ISD::ConstantFP)
3875       IsAllConstants = false;
3876     if (X86::isZeroNode(Elt))
3877       NumZero++;
3878     else {
3879       NonZeros |= (1 << i);
3880       NumNonZero++;
3881     }
3882   }
3883
3884   if (NumNonZero == 0) {
3885     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3886     return DAG.getUNDEF(VT);
3887   }
3888
3889   // Special case for single non-zero, non-undef, element.
3890   if (NumNonZero == 1) {
3891     unsigned Idx = CountTrailingZeros_32(NonZeros);
3892     SDValue Item = Op.getOperand(Idx);
3893
3894     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3895     // the value are obviously zero, truncate the value to i32 and do the
3896     // insertion that way.  Only do this if the value is non-constant or if the
3897     // value is a constant being inserted into element 0.  It is cheaper to do
3898     // a constant pool load than it is to do a movd + shuffle.
3899     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3900         (!IsAllConstants || Idx == 0)) {
3901       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3902         // Handle MMX and SSE both.
3903         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3904         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3905
3906         // Truncate the value (which may itself be a constant) to i32, and
3907         // convert it to a vector with movd (S2V+shuffle to zero extend).
3908         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3909         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3910         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3911                                            Subtarget->hasSSE2(), DAG);
3912
3913         // Now we have our 32-bit value zero extended in the low element of
3914         // a vector.  If Idx != 0, swizzle it into place.
3915         if (Idx != 0) {
3916           SmallVector<int, 4> Mask;
3917           Mask.push_back(Idx);
3918           for (unsigned i = 1; i != VecElts; ++i)
3919             Mask.push_back(i);
3920           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3921                                       DAG.getUNDEF(Item.getValueType()),
3922                                       &Mask[0]);
3923         }
3924         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3925       }
3926     }
3927
3928     // If we have a constant or non-constant insertion into the low element of
3929     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3930     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3931     // depending on what the source datatype is.
3932     if (Idx == 0) {
3933       if (NumZero == 0) {
3934         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3935       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3936           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3937         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3938         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3939         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3940                                            DAG);
3941       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3942         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3943         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3944         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3945         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3946                                            Subtarget->hasSSE2(), DAG);
3947         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3948       }
3949     }
3950
3951     // Is it a vector logical left shift?
3952     if (NumElems == 2 && Idx == 1 &&
3953         X86::isZeroNode(Op.getOperand(0)) &&
3954         !X86::isZeroNode(Op.getOperand(1))) {
3955       unsigned NumBits = VT.getSizeInBits();
3956       return getVShift(true, VT,
3957                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3958                                    VT, Op.getOperand(1)),
3959                        NumBits/2, DAG, *this, dl);
3960     }
3961
3962     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3963       return SDValue();
3964
3965     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3966     // is a non-constant being inserted into an element other than the low one,
3967     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3968     // movd/movss) to move this into the low element, then shuffle it into
3969     // place.
3970     if (EVTBits == 32) {
3971       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3972
3973       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3974       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3975                                          Subtarget->hasSSE2(), DAG);
3976       SmallVector<int, 8> MaskVec;
3977       for (unsigned i = 0; i < NumElems; i++)
3978         MaskVec.push_back(i == Idx ? 0 : 1);
3979       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3980     }
3981   }
3982
3983   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3984   if (Values.size() == 1) {
3985     if (EVTBits == 32) {
3986       // Instead of a shuffle like this:
3987       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3988       // Check if it's possible to issue this instead.
3989       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3990       unsigned Idx = CountTrailingZeros_32(NonZeros);
3991       SDValue Item = Op.getOperand(Idx);
3992       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3993         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3994     }
3995     return SDValue();
3996   }
3997
3998   // A vector full of immediates; various special cases are already
3999   // handled, so this is best done with a single constant-pool load.
4000   if (IsAllConstants)
4001     return SDValue();
4002
4003   // Let legalizer expand 2-wide build_vectors.
4004   if (EVTBits == 64) {
4005     if (NumNonZero == 1) {
4006       // One half is zero or undef.
4007       unsigned Idx = CountTrailingZeros_32(NonZeros);
4008       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4009                                  Op.getOperand(Idx));
4010       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4011                                          Subtarget->hasSSE2(), DAG);
4012     }
4013     return SDValue();
4014   }
4015
4016   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4017   if (EVTBits == 8 && NumElems == 16) {
4018     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4019                                         *this);
4020     if (V.getNode()) return V;
4021   }
4022
4023   if (EVTBits == 16 && NumElems == 8) {
4024     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4025                                         *this);
4026     if (V.getNode()) return V;
4027   }
4028
4029   // If element VT is == 32 bits, turn it into a number of shuffles.
4030   SmallVector<SDValue, 8> V;
4031   V.resize(NumElems);
4032   if (NumElems == 4 && NumZero > 0) {
4033     for (unsigned i = 0; i < 4; ++i) {
4034       bool isZero = !(NonZeros & (1 << i));
4035       if (isZero)
4036         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4037       else
4038         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4039     }
4040
4041     for (unsigned i = 0; i < 2; ++i) {
4042       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4043         default: break;
4044         case 0:
4045           V[i] = V[i*2];  // Must be a zero vector.
4046           break;
4047         case 1:
4048           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4049           break;
4050         case 2:
4051           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4052           break;
4053         case 3:
4054           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4055           break;
4056       }
4057     }
4058
4059     SmallVector<int, 8> MaskVec;
4060     bool Reverse = (NonZeros & 0x3) == 2;
4061     for (unsigned i = 0; i < 2; ++i)
4062       MaskVec.push_back(Reverse ? 1-i : i);
4063     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4064     for (unsigned i = 0; i < 2; ++i)
4065       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4066     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4067   }
4068
4069   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4070     // Check for a build vector of consecutive loads.
4071     for (unsigned i = 0; i < NumElems; ++i)
4072       V[i] = Op.getOperand(i);
4073     
4074     // Check for elements which are consecutive loads.
4075     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4076     if (LD.getNode())
4077       return LD;
4078     
4079     // For SSE 4.1, use inserts into undef.  
4080     if (getSubtarget()->hasSSE41()) {
4081       V[0] = DAG.getUNDEF(VT);
4082       for (unsigned i = 0; i < NumElems; ++i)
4083         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4084           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
4085                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4086       return V[0];
4087     }
4088     
4089     // Otherwise, expand into a number of unpckl*
4090     // e.g. for v4f32
4091     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4092     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4093     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4094     for (unsigned i = 0; i < NumElems; ++i)
4095       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4096     NumElems >>= 1;
4097     while (NumElems != 0) {
4098       for (unsigned i = 0; i < NumElems; ++i)
4099         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4100       NumElems >>= 1;
4101     }
4102     return V[0];
4103   }
4104   return SDValue();
4105 }
4106
4107 SDValue
4108 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4109   // We support concatenate two MMX registers and place them in a MMX
4110   // register.  This is better than doing a stack convert.
4111   DebugLoc dl = Op.getDebugLoc();
4112   EVT ResVT = Op.getValueType();
4113   assert(Op.getNumOperands() == 2);
4114   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4115          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4116   int Mask[2];
4117   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4118   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4119   InVec = Op.getOperand(1);
4120   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4121     unsigned NumElts = ResVT.getVectorNumElements();
4122     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4123     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4124                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4125   } else {
4126     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4127     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4128     Mask[0] = 0; Mask[1] = 2;
4129     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4130   }
4131   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4132 }
4133
4134 // v8i16 shuffles - Prefer shuffles in the following order:
4135 // 1. [all]   pshuflw, pshufhw, optional move
4136 // 2. [ssse3] 1 x pshufb
4137 // 3. [ssse3] 2 x pshufb + 1 x por
4138 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4139 static
4140 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4141                                  SelectionDAG &DAG,
4142                                  const X86TargetLowering &TLI) {
4143   SDValue V1 = SVOp->getOperand(0);
4144   SDValue V2 = SVOp->getOperand(1);
4145   DebugLoc dl = SVOp->getDebugLoc();
4146   SmallVector<int, 8> MaskVals;
4147
4148   // Determine if more than 1 of the words in each of the low and high quadwords
4149   // of the result come from the same quadword of one of the two inputs.  Undef
4150   // mask values count as coming from any quadword, for better codegen.
4151   SmallVector<unsigned, 4> LoQuad(4);
4152   SmallVector<unsigned, 4> HiQuad(4);
4153   BitVector InputQuads(4);
4154   for (unsigned i = 0; i < 8; ++i) {
4155     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4156     int EltIdx = SVOp->getMaskElt(i);
4157     MaskVals.push_back(EltIdx);
4158     if (EltIdx < 0) {
4159       ++Quad[0];
4160       ++Quad[1];
4161       ++Quad[2];
4162       ++Quad[3];
4163       continue;
4164     }
4165     ++Quad[EltIdx / 4];
4166     InputQuads.set(EltIdx / 4);
4167   }
4168
4169   int BestLoQuad = -1;
4170   unsigned MaxQuad = 1;
4171   for (unsigned i = 0; i < 4; ++i) {
4172     if (LoQuad[i] > MaxQuad) {
4173       BestLoQuad = i;
4174       MaxQuad = LoQuad[i];
4175     }
4176   }
4177
4178   int BestHiQuad = -1;
4179   MaxQuad = 1;
4180   for (unsigned i = 0; i < 4; ++i) {
4181     if (HiQuad[i] > MaxQuad) {
4182       BestHiQuad = i;
4183       MaxQuad = HiQuad[i];
4184     }
4185   }
4186
4187   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4188   // of the two input vectors, shuffle them into one input vector so only a
4189   // single pshufb instruction is necessary. If There are more than 2 input
4190   // quads, disable the next transformation since it does not help SSSE3.
4191   bool V1Used = InputQuads[0] || InputQuads[1];
4192   bool V2Used = InputQuads[2] || InputQuads[3];
4193   if (TLI.getSubtarget()->hasSSSE3()) {
4194     if (InputQuads.count() == 2 && V1Used && V2Used) {
4195       BestLoQuad = InputQuads.find_first();
4196       BestHiQuad = InputQuads.find_next(BestLoQuad);
4197     }
4198     if (InputQuads.count() > 2) {
4199       BestLoQuad = -1;
4200       BestHiQuad = -1;
4201     }
4202   }
4203
4204   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4205   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4206   // words from all 4 input quadwords.
4207   SDValue NewV;
4208   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4209     SmallVector<int, 8> MaskV;
4210     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4211     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4212     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4213                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4214                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4215     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4216
4217     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4218     // source words for the shuffle, to aid later transformations.
4219     bool AllWordsInNewV = true;
4220     bool InOrder[2] = { true, true };
4221     for (unsigned i = 0; i != 8; ++i) {
4222       int idx = MaskVals[i];
4223       if (idx != (int)i)
4224         InOrder[i/4] = false;
4225       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4226         continue;
4227       AllWordsInNewV = false;
4228       break;
4229     }
4230
4231     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4232     if (AllWordsInNewV) {
4233       for (int i = 0; i != 8; ++i) {
4234         int idx = MaskVals[i];
4235         if (idx < 0)
4236           continue;
4237         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4238         if ((idx != i) && idx < 4)
4239           pshufhw = false;
4240         if ((idx != i) && idx > 3)
4241           pshuflw = false;
4242       }
4243       V1 = NewV;
4244       V2Used = false;
4245       BestLoQuad = 0;
4246       BestHiQuad = 1;
4247     }
4248
4249     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4250     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4251     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4252       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4253                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4254     }
4255   }
4256
4257   // If we have SSSE3, and all words of the result are from 1 input vector,
4258   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4259   // is present, fall back to case 4.
4260   if (TLI.getSubtarget()->hasSSSE3()) {
4261     SmallVector<SDValue,16> pshufbMask;
4262
4263     // If we have elements from both input vectors, set the high bit of the
4264     // shuffle mask element to zero out elements that come from V2 in the V1
4265     // mask, and elements that come from V1 in the V2 mask, so that the two
4266     // results can be OR'd together.
4267     bool TwoInputs = V1Used && V2Used;
4268     for (unsigned i = 0; i != 8; ++i) {
4269       int EltIdx = MaskVals[i] * 2;
4270       if (TwoInputs && (EltIdx >= 16)) {
4271         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4272         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4273         continue;
4274       }
4275       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4276       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4277     }
4278     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4279     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4280                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4281                                  MVT::v16i8, &pshufbMask[0], 16));
4282     if (!TwoInputs)
4283       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4284
4285     // Calculate the shuffle mask for the second input, shuffle it, and
4286     // OR it with the first shuffled input.
4287     pshufbMask.clear();
4288     for (unsigned i = 0; i != 8; ++i) {
4289       int EltIdx = MaskVals[i] * 2;
4290       if (EltIdx < 16) {
4291         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4292         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4293         continue;
4294       }
4295       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4296       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4297     }
4298     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4299     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4300                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4301                                  MVT::v16i8, &pshufbMask[0], 16));
4302     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4303     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4304   }
4305
4306   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4307   // and update MaskVals with new element order.
4308   BitVector InOrder(8);
4309   if (BestLoQuad >= 0) {
4310     SmallVector<int, 8> MaskV;
4311     for (int i = 0; i != 4; ++i) {
4312       int idx = MaskVals[i];
4313       if (idx < 0) {
4314         MaskV.push_back(-1);
4315         InOrder.set(i);
4316       } else if ((idx / 4) == BestLoQuad) {
4317         MaskV.push_back(idx & 3);
4318         InOrder.set(i);
4319       } else {
4320         MaskV.push_back(-1);
4321       }
4322     }
4323     for (unsigned i = 4; i != 8; ++i)
4324       MaskV.push_back(i);
4325     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4326                                 &MaskV[0]);
4327   }
4328
4329   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4330   // and update MaskVals with the new element order.
4331   if (BestHiQuad >= 0) {
4332     SmallVector<int, 8> MaskV;
4333     for (unsigned i = 0; i != 4; ++i)
4334       MaskV.push_back(i);
4335     for (unsigned i = 4; i != 8; ++i) {
4336       int idx = MaskVals[i];
4337       if (idx < 0) {
4338         MaskV.push_back(-1);
4339         InOrder.set(i);
4340       } else if ((idx / 4) == BestHiQuad) {
4341         MaskV.push_back((idx & 3) + 4);
4342         InOrder.set(i);
4343       } else {
4344         MaskV.push_back(-1);
4345       }
4346     }
4347     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4348                                 &MaskV[0]);
4349   }
4350
4351   // In case BestHi & BestLo were both -1, which means each quadword has a word
4352   // from each of the four input quadwords, calculate the InOrder bitvector now
4353   // before falling through to the insert/extract cleanup.
4354   if (BestLoQuad == -1 && BestHiQuad == -1) {
4355     NewV = V1;
4356     for (int i = 0; i != 8; ++i)
4357       if (MaskVals[i] < 0 || MaskVals[i] == i)
4358         InOrder.set(i);
4359   }
4360
4361   // The other elements are put in the right place using pextrw and pinsrw.
4362   for (unsigned i = 0; i != 8; ++i) {
4363     if (InOrder[i])
4364       continue;
4365     int EltIdx = MaskVals[i];
4366     if (EltIdx < 0)
4367       continue;
4368     SDValue ExtOp = (EltIdx < 8)
4369     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4370                   DAG.getIntPtrConstant(EltIdx))
4371     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4372                   DAG.getIntPtrConstant(EltIdx - 8));
4373     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4374                        DAG.getIntPtrConstant(i));
4375   }
4376   return NewV;
4377 }
4378
4379 // v16i8 shuffles - Prefer shuffles in the following order:
4380 // 1. [ssse3] 1 x pshufb
4381 // 2. [ssse3] 2 x pshufb + 1 x por
4382 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4383 static
4384 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4385                                  SelectionDAG &DAG,
4386                                  const X86TargetLowering &TLI) {
4387   SDValue V1 = SVOp->getOperand(0);
4388   SDValue V2 = SVOp->getOperand(1);
4389   DebugLoc dl = SVOp->getDebugLoc();
4390   SmallVector<int, 16> MaskVals;
4391   SVOp->getMask(MaskVals);
4392
4393   // If we have SSSE3, case 1 is generated when all result bytes come from
4394   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4395   // present, fall back to case 3.
4396   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4397   bool V1Only = true;
4398   bool V2Only = true;
4399   for (unsigned i = 0; i < 16; ++i) {
4400     int EltIdx = MaskVals[i];
4401     if (EltIdx < 0)
4402       continue;
4403     if (EltIdx < 16)
4404       V2Only = false;
4405     else
4406       V1Only = false;
4407   }
4408
4409   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4410   if (TLI.getSubtarget()->hasSSSE3()) {
4411     SmallVector<SDValue,16> pshufbMask;
4412
4413     // If all result elements are from one input vector, then only translate
4414     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4415     //
4416     // Otherwise, we have elements from both input vectors, and must zero out
4417     // elements that come from V2 in the first mask, and V1 in the second mask
4418     // so that we can OR them together.
4419     bool TwoInputs = !(V1Only || V2Only);
4420     for (unsigned i = 0; i != 16; ++i) {
4421       int EltIdx = MaskVals[i];
4422       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4423         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4424         continue;
4425       }
4426       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4427     }
4428     // If all the elements are from V2, assign it to V1 and return after
4429     // building the first pshufb.
4430     if (V2Only)
4431       V1 = V2;
4432     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4433                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4434                                  MVT::v16i8, &pshufbMask[0], 16));
4435     if (!TwoInputs)
4436       return V1;
4437
4438     // Calculate the shuffle mask for the second input, shuffle it, and
4439     // OR it with the first shuffled input.
4440     pshufbMask.clear();
4441     for (unsigned i = 0; i != 16; ++i) {
4442       int EltIdx = MaskVals[i];
4443       if (EltIdx < 16) {
4444         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4445         continue;
4446       }
4447       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4448     }
4449     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4450                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4451                                  MVT::v16i8, &pshufbMask[0], 16));
4452     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4453   }
4454
4455   // No SSSE3 - Calculate in place words and then fix all out of place words
4456   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4457   // the 16 different words that comprise the two doublequadword input vectors.
4458   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4459   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4460   SDValue NewV = V2Only ? V2 : V1;
4461   for (int i = 0; i != 8; ++i) {
4462     int Elt0 = MaskVals[i*2];
4463     int Elt1 = MaskVals[i*2+1];
4464
4465     // This word of the result is all undef, skip it.
4466     if (Elt0 < 0 && Elt1 < 0)
4467       continue;
4468
4469     // This word of the result is already in the correct place, skip it.
4470     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4471       continue;
4472     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4473       continue;
4474
4475     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4476     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4477     SDValue InsElt;
4478
4479     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4480     // using a single extract together, load it and store it.
4481     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4482       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4483                            DAG.getIntPtrConstant(Elt1 / 2));
4484       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4485                         DAG.getIntPtrConstant(i));
4486       continue;
4487     }
4488
4489     // If Elt1 is defined, extract it from the appropriate source.  If the
4490     // source byte is not also odd, shift the extracted word left 8 bits
4491     // otherwise clear the bottom 8 bits if we need to do an or.
4492     if (Elt1 >= 0) {
4493       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4494                            DAG.getIntPtrConstant(Elt1 / 2));
4495       if ((Elt1 & 1) == 0)
4496         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4497                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4498       else if (Elt0 >= 0)
4499         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4500                              DAG.getConstant(0xFF00, MVT::i16));
4501     }
4502     // If Elt0 is defined, extract it from the appropriate source.  If the
4503     // source byte is not also even, shift the extracted word right 8 bits. If
4504     // Elt1 was also defined, OR the extracted values together before
4505     // inserting them in the result.
4506     if (Elt0 >= 0) {
4507       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4508                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4509       if ((Elt0 & 1) != 0)
4510         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4511                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4512       else if (Elt1 >= 0)
4513         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4514                              DAG.getConstant(0x00FF, MVT::i16));
4515       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4516                          : InsElt0;
4517     }
4518     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4519                        DAG.getIntPtrConstant(i));
4520   }
4521   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4522 }
4523
4524 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4525 /// ones, or rewriting v4i32 / v2i32 as 2 wide ones if possible. This can be
4526 /// done when every pair / quad of shuffle mask elements point to elements in
4527 /// the right sequence. e.g.
4528 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4529 static
4530 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4531                                  SelectionDAG &DAG,
4532                                  const TargetLowering &TLI, DebugLoc dl) {
4533   EVT VT = SVOp->getValueType(0);
4534   SDValue V1 = SVOp->getOperand(0);
4535   SDValue V2 = SVOp->getOperand(1);
4536   unsigned NumElems = VT.getVectorNumElements();
4537   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4538   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4539   EVT NewVT = MaskVT;
4540   switch (VT.getSimpleVT().SimpleTy) {
4541   default: assert(false && "Unexpected!");
4542   case MVT::v4f32: NewVT = MVT::v2f64; break;
4543   case MVT::v4i32: NewVT = MVT::v2i64; break;
4544   case MVT::v8i16: NewVT = MVT::v4i32; break;
4545   case MVT::v16i8: NewVT = MVT::v4i32; break;
4546   }
4547
4548   if (NewWidth == 2) {
4549     if (VT.isInteger())
4550       NewVT = MVT::v2i64;
4551     else
4552       NewVT = MVT::v2f64;
4553   }
4554   int Scale = NumElems / NewWidth;
4555   SmallVector<int, 8> MaskVec;
4556   for (unsigned i = 0; i < NumElems; i += Scale) {
4557     int StartIdx = -1;
4558     for (int j = 0; j < Scale; ++j) {
4559       int EltIdx = SVOp->getMaskElt(i+j);
4560       if (EltIdx < 0)
4561         continue;
4562       if (StartIdx == -1)
4563         StartIdx = EltIdx - (EltIdx % Scale);
4564       if (EltIdx != StartIdx + j)
4565         return SDValue();
4566     }
4567     if (StartIdx == -1)
4568       MaskVec.push_back(-1);
4569     else
4570       MaskVec.push_back(StartIdx / Scale);
4571   }
4572
4573   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4574   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4575   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4576 }
4577
4578 /// getVZextMovL - Return a zero-extending vector move low node.
4579 ///
4580 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4581                             SDValue SrcOp, SelectionDAG &DAG,
4582                             const X86Subtarget *Subtarget, DebugLoc dl) {
4583   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4584     LoadSDNode *LD = NULL;
4585     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4586       LD = dyn_cast<LoadSDNode>(SrcOp);
4587     if (!LD) {
4588       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4589       // instead.
4590       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4591       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4592           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4593           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4594           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4595         // PR2108
4596         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4597         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4598                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4599                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4600                                                    OpVT,
4601                                                    SrcOp.getOperand(0)
4602                                                           .getOperand(0))));
4603       }
4604     }
4605   }
4606
4607   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4608                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4609                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4610                                              OpVT, SrcOp)));
4611 }
4612
4613 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4614 /// shuffles.
4615 static SDValue
4616 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4617   SDValue V1 = SVOp->getOperand(0);
4618   SDValue V2 = SVOp->getOperand(1);
4619   DebugLoc dl = SVOp->getDebugLoc();
4620   EVT VT = SVOp->getValueType(0);
4621
4622   SmallVector<std::pair<int, int>, 8> Locs;
4623   Locs.resize(4);
4624   SmallVector<int, 8> Mask1(4U, -1);
4625   SmallVector<int, 8> PermMask;
4626   SVOp->getMask(PermMask);
4627
4628   unsigned NumHi = 0;
4629   unsigned NumLo = 0;
4630   for (unsigned i = 0; i != 4; ++i) {
4631     int Idx = PermMask[i];
4632     if (Idx < 0) {
4633       Locs[i] = std::make_pair(-1, -1);
4634     } else {
4635       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4636       if (Idx < 4) {
4637         Locs[i] = std::make_pair(0, NumLo);
4638         Mask1[NumLo] = Idx;
4639         NumLo++;
4640       } else {
4641         Locs[i] = std::make_pair(1, NumHi);
4642         if (2+NumHi < 4)
4643           Mask1[2+NumHi] = Idx;
4644         NumHi++;
4645       }
4646     }
4647   }
4648
4649   if (NumLo <= 2 && NumHi <= 2) {
4650     // If no more than two elements come from either vector. This can be
4651     // implemented with two shuffles. First shuffle gather the elements.
4652     // The second shuffle, which takes the first shuffle as both of its
4653     // vector operands, put the elements into the right order.
4654     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4655
4656     SmallVector<int, 8> Mask2(4U, -1);
4657
4658     for (unsigned i = 0; i != 4; ++i) {
4659       if (Locs[i].first == -1)
4660         continue;
4661       else {
4662         unsigned Idx = (i < 2) ? 0 : 4;
4663         Idx += Locs[i].first * 2 + Locs[i].second;
4664         Mask2[i] = Idx;
4665       }
4666     }
4667
4668     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4669   } else if (NumLo == 3 || NumHi == 3) {
4670     // Otherwise, we must have three elements from one vector, call it X, and
4671     // one element from the other, call it Y.  First, use a shufps to build an
4672     // intermediate vector with the one element from Y and the element from X
4673     // that will be in the same half in the final destination (the indexes don't
4674     // matter). Then, use a shufps to build the final vector, taking the half
4675     // containing the element from Y from the intermediate, and the other half
4676     // from X.
4677     if (NumHi == 3) {
4678       // Normalize it so the 3 elements come from V1.
4679       CommuteVectorShuffleMask(PermMask, VT);
4680       std::swap(V1, V2);
4681     }
4682
4683     // Find the element from V2.
4684     unsigned HiIndex;
4685     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4686       int Val = PermMask[HiIndex];
4687       if (Val < 0)
4688         continue;
4689       if (Val >= 4)
4690         break;
4691     }
4692
4693     Mask1[0] = PermMask[HiIndex];
4694     Mask1[1] = -1;
4695     Mask1[2] = PermMask[HiIndex^1];
4696     Mask1[3] = -1;
4697     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4698
4699     if (HiIndex >= 2) {
4700       Mask1[0] = PermMask[0];
4701       Mask1[1] = PermMask[1];
4702       Mask1[2] = HiIndex & 1 ? 6 : 4;
4703       Mask1[3] = HiIndex & 1 ? 4 : 6;
4704       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4705     } else {
4706       Mask1[0] = HiIndex & 1 ? 2 : 0;
4707       Mask1[1] = HiIndex & 1 ? 0 : 2;
4708       Mask1[2] = PermMask[2];
4709       Mask1[3] = PermMask[3];
4710       if (Mask1[2] >= 0)
4711         Mask1[2] += 4;
4712       if (Mask1[3] >= 0)
4713         Mask1[3] += 4;
4714       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4715     }
4716   }
4717
4718   // Break it into (shuffle shuffle_hi, shuffle_lo).
4719   Locs.clear();
4720   SmallVector<int,8> LoMask(4U, -1);
4721   SmallVector<int,8> HiMask(4U, -1);
4722
4723   SmallVector<int,8> *MaskPtr = &LoMask;
4724   unsigned MaskIdx = 0;
4725   unsigned LoIdx = 0;
4726   unsigned HiIdx = 2;
4727   for (unsigned i = 0; i != 4; ++i) {
4728     if (i == 2) {
4729       MaskPtr = &HiMask;
4730       MaskIdx = 1;
4731       LoIdx = 0;
4732       HiIdx = 2;
4733     }
4734     int Idx = PermMask[i];
4735     if (Idx < 0) {
4736       Locs[i] = std::make_pair(-1, -1);
4737     } else if (Idx < 4) {
4738       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4739       (*MaskPtr)[LoIdx] = Idx;
4740       LoIdx++;
4741     } else {
4742       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4743       (*MaskPtr)[HiIdx] = Idx;
4744       HiIdx++;
4745     }
4746   }
4747
4748   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4749   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4750   SmallVector<int, 8> MaskOps;
4751   for (unsigned i = 0; i != 4; ++i) {
4752     if (Locs[i].first == -1) {
4753       MaskOps.push_back(-1);
4754     } else {
4755       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4756       MaskOps.push_back(Idx);
4757     }
4758   }
4759   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4760 }
4761
4762 SDValue
4763 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4764   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4765   SDValue V1 = Op.getOperand(0);
4766   SDValue V2 = Op.getOperand(1);
4767   EVT VT = Op.getValueType();
4768   DebugLoc dl = Op.getDebugLoc();
4769   unsigned NumElems = VT.getVectorNumElements();
4770   bool isMMX = VT.getSizeInBits() == 64;
4771   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4772   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4773   bool V1IsSplat = false;
4774   bool V2IsSplat = false;
4775
4776   if (isZeroShuffle(SVOp))
4777     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4778
4779   // Promote splats to v4f32.
4780   if (SVOp->isSplat()) {
4781     if (isMMX || NumElems < 4)
4782       return Op;
4783     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4784   }
4785
4786   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4787   // do it!
4788   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4789     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4790     if (NewOp.getNode())
4791       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4792                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4793   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4794     // FIXME: Figure out a cleaner way to do this.
4795     // Try to make use of movq to zero out the top part.
4796     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4797       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4798       if (NewOp.getNode()) {
4799         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4800           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4801                               DAG, Subtarget, dl);
4802       }
4803     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4804       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4805       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4806         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4807                             DAG, Subtarget, dl);
4808     }
4809   }
4810
4811   if (X86::isPSHUFDMask(SVOp))
4812     return Op;
4813
4814   // Check if this can be converted into a logical shift.
4815   bool isLeft = false;
4816   unsigned ShAmt = 0;
4817   SDValue ShVal;
4818   bool isShift = getSubtarget()->hasSSE2() &&
4819     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4820   if (isShift && ShVal.hasOneUse()) {
4821     // If the shifted value has multiple uses, it may be cheaper to use
4822     // v_set0 + movlhps or movhlps, etc.
4823     EVT EltVT = VT.getVectorElementType();
4824     ShAmt *= EltVT.getSizeInBits();
4825     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4826   }
4827
4828   if (X86::isMOVLMask(SVOp)) {
4829     if (V1IsUndef)
4830       return V2;
4831     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4832       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4833     if (!isMMX)
4834       return Op;
4835   }
4836
4837   // FIXME: fold these into legal mask.
4838   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4839                  X86::isMOVSLDUPMask(SVOp) ||
4840                  X86::isMOVHLPSMask(SVOp) ||
4841                  X86::isMOVLHPSMask(SVOp) ||
4842                  X86::isMOVLPMask(SVOp)))
4843     return Op;
4844
4845   if (ShouldXformToMOVHLPS(SVOp) ||
4846       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4847     return CommuteVectorShuffle(SVOp, DAG);
4848
4849   if (isShift) {
4850     // No better options. Use a vshl / vsrl.
4851     EVT EltVT = VT.getVectorElementType();
4852     ShAmt *= EltVT.getSizeInBits();
4853     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4854   }
4855
4856   bool Commuted = false;
4857   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4858   // 1,1,1,1 -> v8i16 though.
4859   V1IsSplat = isSplatVector(V1.getNode());
4860   V2IsSplat = isSplatVector(V2.getNode());
4861
4862   // Canonicalize the splat or undef, if present, to be on the RHS.
4863   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4864     Op = CommuteVectorShuffle(SVOp, DAG);
4865     SVOp = cast<ShuffleVectorSDNode>(Op);
4866     V1 = SVOp->getOperand(0);
4867     V2 = SVOp->getOperand(1);
4868     std::swap(V1IsSplat, V2IsSplat);
4869     std::swap(V1IsUndef, V2IsUndef);
4870     Commuted = true;
4871   }
4872
4873   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4874     // Shuffling low element of v1 into undef, just return v1.
4875     if (V2IsUndef)
4876       return V1;
4877     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4878     // the instruction selector will not match, so get a canonical MOVL with
4879     // swapped operands to undo the commute.
4880     return getMOVL(DAG, dl, VT, V2, V1);
4881   }
4882
4883   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4884       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4885       X86::isUNPCKLMask(SVOp) ||
4886       X86::isUNPCKHMask(SVOp))
4887     return Op;
4888
4889   if (V2IsSplat) {
4890     // Normalize mask so all entries that point to V2 points to its first
4891     // element then try to match unpck{h|l} again. If match, return a
4892     // new vector_shuffle with the corrected mask.
4893     SDValue NewMask = NormalizeMask(SVOp, DAG);
4894     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4895     if (NSVOp != SVOp) {
4896       if (X86::isUNPCKLMask(NSVOp, true)) {
4897         return NewMask;
4898       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4899         return NewMask;
4900       }
4901     }
4902   }
4903
4904   if (Commuted) {
4905     // Commute is back and try unpck* again.
4906     // FIXME: this seems wrong.
4907     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4908     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4909     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4910         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4911         X86::isUNPCKLMask(NewSVOp) ||
4912         X86::isUNPCKHMask(NewSVOp))
4913       return NewOp;
4914   }
4915
4916   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4917
4918   // Normalize the node to match x86 shuffle ops if needed
4919   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4920     return CommuteVectorShuffle(SVOp, DAG);
4921
4922   // Check for legal shuffle and return?
4923   SmallVector<int, 16> PermMask;
4924   SVOp->getMask(PermMask);
4925   if (isShuffleMaskLegal(PermMask, VT))
4926     return Op;
4927
4928   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4929   if (VT == MVT::v8i16) {
4930     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4931     if (NewOp.getNode())
4932       return NewOp;
4933   }
4934
4935   if (VT == MVT::v16i8) {
4936     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4937     if (NewOp.getNode())
4938       return NewOp;
4939   }
4940
4941   // Handle all 4 wide cases with a number of shuffles except for MMX.
4942   if (NumElems == 4 && !isMMX)
4943     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4944
4945   return SDValue();
4946 }
4947
4948 SDValue
4949 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4950                                                 SelectionDAG &DAG) const {
4951   EVT VT = Op.getValueType();
4952   DebugLoc dl = Op.getDebugLoc();
4953   if (VT.getSizeInBits() == 8) {
4954     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4955                                     Op.getOperand(0), Op.getOperand(1));
4956     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4957                                     DAG.getValueType(VT));
4958     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4959   } else if (VT.getSizeInBits() == 16) {
4960     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4961     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4962     if (Idx == 0)
4963       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4964                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4965                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4966                                                  MVT::v4i32,
4967                                                  Op.getOperand(0)),
4968                                      Op.getOperand(1)));
4969     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4970                                     Op.getOperand(0), Op.getOperand(1));
4971     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4972                                     DAG.getValueType(VT));
4973     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4974   } else if (VT == MVT::f32) {
4975     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4976     // the result back to FR32 register. It's only worth matching if the
4977     // result has a single use which is a store or a bitcast to i32.  And in
4978     // the case of a store, it's not worth it if the index is a constant 0,
4979     // because a MOVSSmr can be used instead, which is smaller and faster.
4980     if (!Op.hasOneUse())
4981       return SDValue();
4982     SDNode *User = *Op.getNode()->use_begin();
4983     if ((User->getOpcode() != ISD::STORE ||
4984          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4985           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4986         (User->getOpcode() != ISD::BIT_CONVERT ||
4987          User->getValueType(0) != MVT::i32))
4988       return SDValue();
4989     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4990                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4991                                               Op.getOperand(0)),
4992                                               Op.getOperand(1));
4993     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4994   } else if (VT == MVT::i32) {
4995     // ExtractPS works with constant index.
4996     if (isa<ConstantSDNode>(Op.getOperand(1)))
4997       return Op;
4998   }
4999   return SDValue();
5000 }
5001
5002
5003 SDValue
5004 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5005                                            SelectionDAG &DAG) const {
5006   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5007     return SDValue();
5008
5009   if (Subtarget->hasSSE41()) {
5010     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5011     if (Res.getNode())
5012       return Res;
5013   }
5014
5015   EVT VT = Op.getValueType();
5016   DebugLoc dl = Op.getDebugLoc();
5017   // TODO: handle v16i8.
5018   if (VT.getSizeInBits() == 16) {
5019     SDValue Vec = Op.getOperand(0);
5020     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5021     if (Idx == 0)
5022       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5023                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5024                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5025                                                  MVT::v4i32, Vec),
5026                                      Op.getOperand(1)));
5027     // Transform it so it match pextrw which produces a 32-bit result.
5028     EVT EltVT = MVT::i32;
5029     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5030                                     Op.getOperand(0), Op.getOperand(1));
5031     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5032                                     DAG.getValueType(VT));
5033     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5034   } else if (VT.getSizeInBits() == 32) {
5035     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5036     if (Idx == 0)
5037       return Op;
5038
5039     // SHUFPS the element to the lowest double word, then movss.
5040     int Mask[4] = { Idx, -1, -1, -1 };
5041     EVT VVT = Op.getOperand(0).getValueType();
5042     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5043                                        DAG.getUNDEF(VVT), Mask);
5044     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5045                        DAG.getIntPtrConstant(0));
5046   } else if (VT.getSizeInBits() == 64) {
5047     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5048     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5049     //        to match extract_elt for f64.
5050     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5051     if (Idx == 0)
5052       return Op;
5053
5054     // UNPCKHPD the element to the lowest double word, then movsd.
5055     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5056     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5057     int Mask[2] = { 1, -1 };
5058     EVT VVT = Op.getOperand(0).getValueType();
5059     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5060                                        DAG.getUNDEF(VVT), Mask);
5061     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5062                        DAG.getIntPtrConstant(0));
5063   }
5064
5065   return SDValue();
5066 }
5067
5068 SDValue
5069 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5070                                                SelectionDAG &DAG) const {
5071   EVT VT = Op.getValueType();
5072   EVT EltVT = VT.getVectorElementType();
5073   DebugLoc dl = Op.getDebugLoc();
5074
5075   SDValue N0 = Op.getOperand(0);
5076   SDValue N1 = Op.getOperand(1);
5077   SDValue N2 = Op.getOperand(2);
5078
5079   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5080       isa<ConstantSDNode>(N2)) {
5081     unsigned Opc;
5082     if (VT == MVT::v8i16)
5083       Opc = X86ISD::PINSRW;
5084     else if (VT == MVT::v4i16)
5085       Opc = X86ISD::MMX_PINSRW;
5086     else if (VT == MVT::v16i8)
5087       Opc = X86ISD::PINSRB;
5088     else
5089       Opc = X86ISD::PINSRB;
5090
5091     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5092     // argument.
5093     if (N1.getValueType() != MVT::i32)
5094       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5095     if (N2.getValueType() != MVT::i32)
5096       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5097     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5098   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5099     // Bits [7:6] of the constant are the source select.  This will always be
5100     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5101     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5102     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5103     // Bits [5:4] of the constant are the destination select.  This is the
5104     //  value of the incoming immediate.
5105     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5106     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5107     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5108     // Create this as a scalar to vector..
5109     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5110     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5111   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5112     // PINSR* works with constant index.
5113     return Op;
5114   }
5115   return SDValue();
5116 }
5117
5118 SDValue
5119 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5120   EVT VT = Op.getValueType();
5121   EVT EltVT = VT.getVectorElementType();
5122
5123   if (Subtarget->hasSSE41())
5124     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5125
5126   if (EltVT == MVT::i8)
5127     return SDValue();
5128
5129   DebugLoc dl = Op.getDebugLoc();
5130   SDValue N0 = Op.getOperand(0);
5131   SDValue N1 = Op.getOperand(1);
5132   SDValue N2 = Op.getOperand(2);
5133
5134   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5135     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5136     // as its second argument.
5137     if (N1.getValueType() != MVT::i32)
5138       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5139     if (N2.getValueType() != MVT::i32)
5140       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5141     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5142                        dl, VT, N0, N1, N2);
5143   }
5144   return SDValue();
5145 }
5146
5147 SDValue
5148 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5149   DebugLoc dl = Op.getDebugLoc();
5150   
5151   if (Op.getValueType() == MVT::v1i64 &&
5152       Op.getOperand(0).getValueType() == MVT::i64)
5153     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5154
5155   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5156   EVT VT = MVT::v2i32;
5157   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5158   default: break;
5159   case MVT::v16i8:
5160   case MVT::v8i16:
5161     VT = MVT::v4i32;
5162     break;
5163   }
5164   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5165                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5166 }
5167
5168 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5169 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5170 // one of the above mentioned nodes. It has to be wrapped because otherwise
5171 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5172 // be used to form addressing mode. These wrapped nodes will be selected
5173 // into MOV32ri.
5174 SDValue
5175 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5176   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5177
5178   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5179   // global base reg.
5180   unsigned char OpFlag = 0;
5181   unsigned WrapperKind = X86ISD::Wrapper;
5182   CodeModel::Model M = getTargetMachine().getCodeModel();
5183
5184   if (Subtarget->isPICStyleRIPRel() &&
5185       (M == CodeModel::Small || M == CodeModel::Kernel))
5186     WrapperKind = X86ISD::WrapperRIP;
5187   else if (Subtarget->isPICStyleGOT())
5188     OpFlag = X86II::MO_GOTOFF;
5189   else if (Subtarget->isPICStyleStubPIC())
5190     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5191
5192   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5193                                              CP->getAlignment(),
5194                                              CP->getOffset(), OpFlag);
5195   DebugLoc DL = CP->getDebugLoc();
5196   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5197   // With PIC, the address is actually $g + Offset.
5198   if (OpFlag) {
5199     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5200                          DAG.getNode(X86ISD::GlobalBaseReg,
5201                                      DebugLoc(), getPointerTy()),
5202                          Result);
5203   }
5204
5205   return Result;
5206 }
5207
5208 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5209   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5210
5211   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5212   // global base reg.
5213   unsigned char OpFlag = 0;
5214   unsigned WrapperKind = X86ISD::Wrapper;
5215   CodeModel::Model M = getTargetMachine().getCodeModel();
5216
5217   if (Subtarget->isPICStyleRIPRel() &&
5218       (M == CodeModel::Small || M == CodeModel::Kernel))
5219     WrapperKind = X86ISD::WrapperRIP;
5220   else if (Subtarget->isPICStyleGOT())
5221     OpFlag = X86II::MO_GOTOFF;
5222   else if (Subtarget->isPICStyleStubPIC())
5223     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5224
5225   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5226                                           OpFlag);
5227   DebugLoc DL = JT->getDebugLoc();
5228   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5229
5230   // With PIC, the address is actually $g + Offset.
5231   if (OpFlag) {
5232     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5233                          DAG.getNode(X86ISD::GlobalBaseReg,
5234                                      DebugLoc(), getPointerTy()),
5235                          Result);
5236   }
5237
5238   return Result;
5239 }
5240
5241 SDValue
5242 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5243   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5244
5245   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5246   // global base reg.
5247   unsigned char OpFlag = 0;
5248   unsigned WrapperKind = X86ISD::Wrapper;
5249   CodeModel::Model M = getTargetMachine().getCodeModel();
5250
5251   if (Subtarget->isPICStyleRIPRel() &&
5252       (M == CodeModel::Small || M == CodeModel::Kernel))
5253     WrapperKind = X86ISD::WrapperRIP;
5254   else if (Subtarget->isPICStyleGOT())
5255     OpFlag = X86II::MO_GOTOFF;
5256   else if (Subtarget->isPICStyleStubPIC())
5257     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5258
5259   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5260
5261   DebugLoc DL = Op.getDebugLoc();
5262   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5263
5264
5265   // With PIC, the address is actually $g + Offset.
5266   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5267       !Subtarget->is64Bit()) {
5268     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5269                          DAG.getNode(X86ISD::GlobalBaseReg,
5270                                      DebugLoc(), getPointerTy()),
5271                          Result);
5272   }
5273
5274   return Result;
5275 }
5276
5277 SDValue
5278 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5279   // Create the TargetBlockAddressAddress node.
5280   unsigned char OpFlags =
5281     Subtarget->ClassifyBlockAddressReference();
5282   CodeModel::Model M = getTargetMachine().getCodeModel();
5283   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5284   DebugLoc dl = Op.getDebugLoc();
5285   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5286                                        /*isTarget=*/true, OpFlags);
5287
5288   if (Subtarget->isPICStyleRIPRel() &&
5289       (M == CodeModel::Small || M == CodeModel::Kernel))
5290     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5291   else
5292     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5293
5294   // With PIC, the address is actually $g + Offset.
5295   if (isGlobalRelativeToPICBase(OpFlags)) {
5296     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5297                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5298                          Result);
5299   }
5300
5301   return Result;
5302 }
5303
5304 SDValue
5305 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5306                                       int64_t Offset,
5307                                       SelectionDAG &DAG) const {
5308   // Create the TargetGlobalAddress node, folding in the constant
5309   // offset if it is legal.
5310   unsigned char OpFlags =
5311     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5312   CodeModel::Model M = getTargetMachine().getCodeModel();
5313   SDValue Result;
5314   if (OpFlags == X86II::MO_NO_FLAG &&
5315       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5316     // A direct static reference to a global.
5317     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5318     Offset = 0;
5319   } else {
5320     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5321   }
5322
5323   if (Subtarget->isPICStyleRIPRel() &&
5324       (M == CodeModel::Small || M == CodeModel::Kernel))
5325     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5326   else
5327     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5328
5329   // With PIC, the address is actually $g + Offset.
5330   if (isGlobalRelativeToPICBase(OpFlags)) {
5331     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5332                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5333                          Result);
5334   }
5335
5336   // For globals that require a load from a stub to get the address, emit the
5337   // load.
5338   if (isGlobalStubReference(OpFlags))
5339     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5340                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5341
5342   // If there was a non-zero offset that we didn't fold, create an explicit
5343   // addition for it.
5344   if (Offset != 0)
5345     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5346                          DAG.getConstant(Offset, getPointerTy()));
5347
5348   return Result;
5349 }
5350
5351 SDValue
5352 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5353   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5354   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5355   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5356 }
5357
5358 static SDValue
5359 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5360            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5361            unsigned char OperandFlags) {
5362   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5363   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5364   DebugLoc dl = GA->getDebugLoc();
5365   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
5366                                            GA->getValueType(0),
5367                                            GA->getOffset(),
5368                                            OperandFlags);
5369   if (InFlag) {
5370     SDValue Ops[] = { Chain,  TGA, *InFlag };
5371     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5372   } else {
5373     SDValue Ops[]  = { Chain, TGA };
5374     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5375   }
5376
5377   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5378   MFI->setAdjustsStack(true);
5379
5380   SDValue Flag = Chain.getValue(1);
5381   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5382 }
5383
5384 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5385 static SDValue
5386 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5387                                 const EVT PtrVT) {
5388   SDValue InFlag;
5389   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5390   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5391                                      DAG.getNode(X86ISD::GlobalBaseReg,
5392                                                  DebugLoc(), PtrVT), InFlag);
5393   InFlag = Chain.getValue(1);
5394
5395   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5396 }
5397
5398 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5399 static SDValue
5400 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5401                                 const EVT PtrVT) {
5402   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5403                     X86::RAX, X86II::MO_TLSGD);
5404 }
5405
5406 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5407 // "local exec" model.
5408 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5409                                    const EVT PtrVT, TLSModel::Model model,
5410                                    bool is64Bit) {
5411   DebugLoc dl = GA->getDebugLoc();
5412   // Get the Thread Pointer
5413   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5414                              DebugLoc(), PtrVT,
5415                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5416                                              MVT::i32));
5417
5418   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5419                                       NULL, 0, false, false, 0);
5420
5421   unsigned char OperandFlags = 0;
5422   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5423   // initialexec.
5424   unsigned WrapperKind = X86ISD::Wrapper;
5425   if (model == TLSModel::LocalExec) {
5426     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5427   } else if (is64Bit) {
5428     assert(model == TLSModel::InitialExec);
5429     OperandFlags = X86II::MO_GOTTPOFF;
5430     WrapperKind = X86ISD::WrapperRIP;
5431   } else {
5432     assert(model == TLSModel::InitialExec);
5433     OperandFlags = X86II::MO_INDNTPOFF;
5434   }
5435
5436   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5437   // exec)
5438   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 
5439                                            GA->getValueType(0),
5440                                            GA->getOffset(), OperandFlags);
5441   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5442
5443   if (model == TLSModel::InitialExec)
5444     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5445                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5446
5447   // The address of the thread local variable is the add of the thread
5448   // pointer with the offset of the variable.
5449   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5450 }
5451
5452 SDValue
5453 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5454   
5455   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5456   const GlobalValue *GV = GA->getGlobal();
5457
5458   if (Subtarget->isTargetELF()) {
5459     // TODO: implement the "local dynamic" model
5460     // TODO: implement the "initial exec"model for pic executables
5461     
5462     // If GV is an alias then use the aliasee for determining
5463     // thread-localness.
5464     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5465       GV = GA->resolveAliasedGlobal(false);
5466     
5467     TLSModel::Model model 
5468       = getTLSModel(GV, getTargetMachine().getRelocationModel());
5469     
5470     switch (model) {
5471       case TLSModel::GeneralDynamic:
5472       case TLSModel::LocalDynamic: // not implemented
5473         if (Subtarget->is64Bit())
5474           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5475         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5476         
5477       case TLSModel::InitialExec:
5478       case TLSModel::LocalExec:
5479         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5480                                    Subtarget->is64Bit());
5481     }
5482   } else if (Subtarget->isTargetDarwin()) {
5483     // Darwin only has one model of TLS.  Lower to that.
5484     unsigned char OpFlag = 0;
5485     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
5486                            X86ISD::WrapperRIP : X86ISD::Wrapper;
5487     
5488     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5489     // global base reg.
5490     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
5491                   !Subtarget->is64Bit();
5492     if (PIC32)
5493       OpFlag = X86II::MO_TLVP_PIC_BASE;
5494     else
5495       OpFlag = X86II::MO_TLVP;
5496     DebugLoc DL = Op.getDebugLoc();    
5497     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
5498                                                 getPointerTy(),
5499                                                 GA->getOffset(), OpFlag);
5500     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5501   
5502     // With PIC32, the address is actually $g + Offset.
5503     if (PIC32)
5504       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5505                            DAG.getNode(X86ISD::GlobalBaseReg,
5506                                        DebugLoc(), getPointerTy()),
5507                            Offset);
5508     
5509     // Lowering the machine isd will make sure everything is in the right
5510     // location.
5511     SDValue Args[] = { Offset };
5512     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
5513     
5514     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
5515     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5516     MFI->setAdjustsStack(true);
5517
5518     // And our return value (tls address) is in the standard call return value
5519     // location.
5520     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
5521     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
5522   }
5523   
5524   assert(false &&
5525          "TLS not implemented for this target.");
5526
5527   llvm_unreachable("Unreachable");
5528   return SDValue();
5529 }
5530
5531
5532 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5533 /// take a 2 x i32 value to shift plus a shift amount.
5534 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5535   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5536   EVT VT = Op.getValueType();
5537   unsigned VTBits = VT.getSizeInBits();
5538   DebugLoc dl = Op.getDebugLoc();
5539   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5540   SDValue ShOpLo = Op.getOperand(0);
5541   SDValue ShOpHi = Op.getOperand(1);
5542   SDValue ShAmt  = Op.getOperand(2);
5543   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5544                                      DAG.getConstant(VTBits - 1, MVT::i8))
5545                        : DAG.getConstant(0, VT);
5546
5547   SDValue Tmp2, Tmp3;
5548   if (Op.getOpcode() == ISD::SHL_PARTS) {
5549     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5550     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5551   } else {
5552     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5553     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5554   }
5555
5556   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5557                                 DAG.getConstant(VTBits, MVT::i8));
5558   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5559                              AndNode, DAG.getConstant(0, MVT::i8));
5560
5561   SDValue Hi, Lo;
5562   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5563   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5564   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5565
5566   if (Op.getOpcode() == ISD::SHL_PARTS) {
5567     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5568     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5569   } else {
5570     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5571     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5572   }
5573
5574   SDValue Ops[2] = { Lo, Hi };
5575   return DAG.getMergeValues(Ops, 2, dl);
5576 }
5577
5578 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5579                                            SelectionDAG &DAG) const {
5580   EVT SrcVT = Op.getOperand(0).getValueType();
5581
5582   if (SrcVT.isVector()) {
5583     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5584       return Op;
5585     }
5586     return SDValue();
5587   }
5588
5589   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5590          "Unknown SINT_TO_FP to lower!");
5591
5592   // These are really Legal; return the operand so the caller accepts it as
5593   // Legal.
5594   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5595     return Op;
5596   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5597       Subtarget->is64Bit()) {
5598     return Op;
5599   }
5600
5601   DebugLoc dl = Op.getDebugLoc();
5602   unsigned Size = SrcVT.getSizeInBits()/8;
5603   MachineFunction &MF = DAG.getMachineFunction();
5604   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5605   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5606   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5607                                StackSlot,
5608                                PseudoSourceValue::getFixedStack(SSFI), 0,
5609                                false, false, 0);
5610   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5611 }
5612
5613 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5614                                      SDValue StackSlot, 
5615                                      SelectionDAG &DAG) const {
5616   // Build the FILD
5617   DebugLoc dl = Op.getDebugLoc();
5618   SDVTList Tys;
5619   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5620   if (useSSE)
5621     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5622   else
5623     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5624   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5625   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5626                                Tys, Ops, array_lengthof(Ops));
5627
5628   if (useSSE) {
5629     Chain = Result.getValue(1);
5630     SDValue InFlag = Result.getValue(2);
5631
5632     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5633     // shouldn't be necessary except that RFP cannot be live across
5634     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5635     MachineFunction &MF = DAG.getMachineFunction();
5636     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5637     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5638     Tys = DAG.getVTList(MVT::Other);
5639     SDValue Ops[] = {
5640       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5641     };
5642     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5643     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5644                          PseudoSourceValue::getFixedStack(SSFI), 0,
5645                          false, false, 0);
5646   }
5647
5648   return Result;
5649 }
5650
5651 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5652 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5653                                                SelectionDAG &DAG) const {
5654   // This algorithm is not obvious. Here it is in C code, more or less:
5655   /*
5656     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5657       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5658       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5659
5660       // Copy ints to xmm registers.
5661       __m128i xh = _mm_cvtsi32_si128( hi );
5662       __m128i xl = _mm_cvtsi32_si128( lo );
5663
5664       // Combine into low half of a single xmm register.
5665       __m128i x = _mm_unpacklo_epi32( xh, xl );
5666       __m128d d;
5667       double sd;
5668
5669       // Merge in appropriate exponents to give the integer bits the right
5670       // magnitude.
5671       x = _mm_unpacklo_epi32( x, exp );
5672
5673       // Subtract away the biases to deal with the IEEE-754 double precision
5674       // implicit 1.
5675       d = _mm_sub_pd( (__m128d) x, bias );
5676
5677       // All conversions up to here are exact. The correctly rounded result is
5678       // calculated using the current rounding mode using the following
5679       // horizontal add.
5680       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5681       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5682                                 // store doesn't really need to be here (except
5683                                 // maybe to zero the other double)
5684       return sd;
5685     }
5686   */
5687
5688   DebugLoc dl = Op.getDebugLoc();
5689   LLVMContext *Context = DAG.getContext();
5690
5691   // Build some magic constants.
5692   std::vector<Constant*> CV0;
5693   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5694   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5695   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5696   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5697   Constant *C0 = ConstantVector::get(CV0);
5698   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5699
5700   std::vector<Constant*> CV1;
5701   CV1.push_back(
5702     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5703   CV1.push_back(
5704     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5705   Constant *C1 = ConstantVector::get(CV1);
5706   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5707
5708   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5709                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5710                                         Op.getOperand(0),
5711                                         DAG.getIntPtrConstant(1)));
5712   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5713                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5714                                         Op.getOperand(0),
5715                                         DAG.getIntPtrConstant(0)));
5716   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5717   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5718                               PseudoSourceValue::getConstantPool(), 0,
5719                               false, false, 16);
5720   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5721   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5722   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5723                               PseudoSourceValue::getConstantPool(), 0,
5724                               false, false, 16);
5725   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5726
5727   // Add the halves; easiest way is to swap them into another reg first.
5728   int ShufMask[2] = { 1, -1 };
5729   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5730                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5731   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5732   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5733                      DAG.getIntPtrConstant(0));
5734 }
5735
5736 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5737 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5738                                                SelectionDAG &DAG) const {
5739   DebugLoc dl = Op.getDebugLoc();
5740   // FP constant to bias correct the final result.
5741   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5742                                    MVT::f64);
5743
5744   // Load the 32-bit value into an XMM register.
5745   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5746                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5747                                          Op.getOperand(0),
5748                                          DAG.getIntPtrConstant(0)));
5749
5750   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5751                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5752                      DAG.getIntPtrConstant(0));
5753
5754   // Or the load with the bias.
5755   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5756                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5757                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5758                                                    MVT::v2f64, Load)),
5759                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5760                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5761                                                    MVT::v2f64, Bias)));
5762   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5763                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5764                    DAG.getIntPtrConstant(0));
5765
5766   // Subtract the bias.
5767   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5768
5769   // Handle final rounding.
5770   EVT DestVT = Op.getValueType();
5771
5772   if (DestVT.bitsLT(MVT::f64)) {
5773     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5774                        DAG.getIntPtrConstant(0));
5775   } else if (DestVT.bitsGT(MVT::f64)) {
5776     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5777   }
5778
5779   // Handle final rounding.
5780   return Sub;
5781 }
5782
5783 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5784                                            SelectionDAG &DAG) const {
5785   SDValue N0 = Op.getOperand(0);
5786   DebugLoc dl = Op.getDebugLoc();
5787
5788   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5789   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5790   // the optimization here.
5791   if (DAG.SignBitIsZero(N0))
5792     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5793
5794   EVT SrcVT = N0.getValueType();
5795   EVT DstVT = Op.getValueType();
5796   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5797     return LowerUINT_TO_FP_i64(Op, DAG);
5798   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5799     return LowerUINT_TO_FP_i32(Op, DAG);
5800
5801   // Make a 64-bit buffer, and use it to build an FILD.
5802   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5803   if (SrcVT == MVT::i32) {
5804     SDValue WordOff = DAG.getConstant(4, getPointerTy());
5805     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5806                                      getPointerTy(), StackSlot, WordOff);
5807     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5808                                   StackSlot, NULL, 0, false, false, 0);
5809     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5810                                   OffsetSlot, NULL, 0, false, false, 0);
5811     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5812     return Fild;
5813   }
5814
5815   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5816   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5817                                 StackSlot, NULL, 0, false, false, 0);
5818   // For i64 source, we need to add the appropriate power of 2 if the input
5819   // was negative.  This is the same as the optimization in
5820   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5821   // we must be careful to do the computation in x87 extended precision, not
5822   // in SSE. (The generic code can't know it's OK to do this, or how to.)
5823   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5824   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5825   SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5826
5827   APInt FF(32, 0x5F800000ULL);
5828
5829   // Check whether the sign bit is set.
5830   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5831                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5832                                  ISD::SETLT);
5833
5834   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5835   SDValue FudgePtr = DAG.getConstantPool(
5836                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5837                                          getPointerTy());
5838
5839   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5840   SDValue Zero = DAG.getIntPtrConstant(0);
5841   SDValue Four = DAG.getIntPtrConstant(4);
5842   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5843                                Zero, Four);
5844   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5845
5846   // Load the value out, extending it from f32 to f80.
5847   // FIXME: Avoid the extend by constructing the right constant pool?
5848   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
5849                                  FudgePtr, PseudoSourceValue::getConstantPool(),
5850                                  0, MVT::f32, false, false, 4);
5851   // Extend everything to 80 bits to force it to be done on x87.
5852   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5853   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5854 }
5855
5856 std::pair<SDValue,SDValue> X86TargetLowering::
5857 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5858   DebugLoc dl = Op.getDebugLoc();
5859
5860   EVT DstTy = Op.getValueType();
5861
5862   if (!IsSigned) {
5863     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5864     DstTy = MVT::i64;
5865   }
5866
5867   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5868          DstTy.getSimpleVT() >= MVT::i16 &&
5869          "Unknown FP_TO_SINT to lower!");
5870
5871   // These are really Legal.
5872   if (DstTy == MVT::i32 &&
5873       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5874     return std::make_pair(SDValue(), SDValue());
5875   if (Subtarget->is64Bit() &&
5876       DstTy == MVT::i64 &&
5877       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5878     return std::make_pair(SDValue(), SDValue());
5879
5880   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5881   // stack slot.
5882   MachineFunction &MF = DAG.getMachineFunction();
5883   unsigned MemSize = DstTy.getSizeInBits()/8;
5884   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5885   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5886
5887   unsigned Opc;
5888   switch (DstTy.getSimpleVT().SimpleTy) {
5889   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5890   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5891   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5892   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5893   }
5894
5895   SDValue Chain = DAG.getEntryNode();
5896   SDValue Value = Op.getOperand(0);
5897   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5898     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5899     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5900                          PseudoSourceValue::getFixedStack(SSFI), 0,
5901                          false, false, 0);
5902     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5903     SDValue Ops[] = {
5904       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5905     };
5906     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5907     Chain = Value.getValue(1);
5908     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5909     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5910   }
5911
5912   // Build the FP_TO_INT*_IN_MEM
5913   SDValue Ops[] = { Chain, Value, StackSlot };
5914   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5915
5916   return std::make_pair(FIST, StackSlot);
5917 }
5918
5919 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5920                                            SelectionDAG &DAG) const {
5921   if (Op.getValueType().isVector()) {
5922     if (Op.getValueType() == MVT::v2i32 &&
5923         Op.getOperand(0).getValueType() == MVT::v2f64) {
5924       return Op;
5925     }
5926     return SDValue();
5927   }
5928
5929   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5930   SDValue FIST = Vals.first, StackSlot = Vals.second;
5931   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5932   if (FIST.getNode() == 0) return Op;
5933
5934   // Load the result.
5935   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5936                      FIST, StackSlot, NULL, 0, false, false, 0);
5937 }
5938
5939 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5940                                            SelectionDAG &DAG) const {
5941   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5942   SDValue FIST = Vals.first, StackSlot = Vals.second;
5943   assert(FIST.getNode() && "Unexpected failure");
5944
5945   // Load the result.
5946   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5947                      FIST, StackSlot, NULL, 0, false, false, 0);
5948 }
5949
5950 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5951                                      SelectionDAG &DAG) const {
5952   LLVMContext *Context = DAG.getContext();
5953   DebugLoc dl = Op.getDebugLoc();
5954   EVT VT = Op.getValueType();
5955   EVT EltVT = VT;
5956   if (VT.isVector())
5957     EltVT = VT.getVectorElementType();
5958   std::vector<Constant*> CV;
5959   if (EltVT == MVT::f64) {
5960     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5961     CV.push_back(C);
5962     CV.push_back(C);
5963   } else {
5964     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5965     CV.push_back(C);
5966     CV.push_back(C);
5967     CV.push_back(C);
5968     CV.push_back(C);
5969   }
5970   Constant *C = ConstantVector::get(CV);
5971   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5972   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5973                              PseudoSourceValue::getConstantPool(), 0,
5974                              false, false, 16);
5975   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5976 }
5977
5978 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5979   LLVMContext *Context = DAG.getContext();
5980   DebugLoc dl = Op.getDebugLoc();
5981   EVT VT = Op.getValueType();
5982   EVT EltVT = VT;
5983   if (VT.isVector())
5984     EltVT = VT.getVectorElementType();
5985   std::vector<Constant*> CV;
5986   if (EltVT == MVT::f64) {
5987     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5988     CV.push_back(C);
5989     CV.push_back(C);
5990   } else {
5991     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5992     CV.push_back(C);
5993     CV.push_back(C);
5994     CV.push_back(C);
5995     CV.push_back(C);
5996   }
5997   Constant *C = ConstantVector::get(CV);
5998   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5999   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6000                              PseudoSourceValue::getConstantPool(), 0,
6001                              false, false, 16);
6002   if (VT.isVector()) {
6003     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6004                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6005                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6006                                 Op.getOperand(0)),
6007                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6008   } else {
6009     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6010   }
6011 }
6012
6013 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6014   LLVMContext *Context = DAG.getContext();
6015   SDValue Op0 = Op.getOperand(0);
6016   SDValue Op1 = Op.getOperand(1);
6017   DebugLoc dl = Op.getDebugLoc();
6018   EVT VT = Op.getValueType();
6019   EVT SrcVT = Op1.getValueType();
6020
6021   // If second operand is smaller, extend it first.
6022   if (SrcVT.bitsLT(VT)) {
6023     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6024     SrcVT = VT;
6025   }
6026   // And if it is bigger, shrink it first.
6027   if (SrcVT.bitsGT(VT)) {
6028     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6029     SrcVT = VT;
6030   }
6031
6032   // At this point the operands and the result should have the same
6033   // type, and that won't be f80 since that is not custom lowered.
6034
6035   // First get the sign bit of second operand.
6036   std::vector<Constant*> CV;
6037   if (SrcVT == MVT::f64) {
6038     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6039     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6040   } else {
6041     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6042     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6043     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6044     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6045   }
6046   Constant *C = ConstantVector::get(CV);
6047   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6048   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6049                               PseudoSourceValue::getConstantPool(), 0,
6050                               false, false, 16);
6051   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6052
6053   // Shift sign bit right or left if the two operands have different types.
6054   if (SrcVT.bitsGT(VT)) {
6055     // Op0 is MVT::f32, Op1 is MVT::f64.
6056     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6057     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6058                           DAG.getConstant(32, MVT::i32));
6059     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6060     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6061                           DAG.getIntPtrConstant(0));
6062   }
6063
6064   // Clear first operand sign bit.
6065   CV.clear();
6066   if (VT == MVT::f64) {
6067     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6068     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6069   } else {
6070     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6071     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6072     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6073     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6074   }
6075   C = ConstantVector::get(CV);
6076   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6077   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6078                               PseudoSourceValue::getConstantPool(), 0,
6079                               false, false, 16);
6080   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6081
6082   // Or the value with the sign bit.
6083   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6084 }
6085
6086 /// Emit nodes that will be selected as "test Op0,Op0", or something
6087 /// equivalent.
6088 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6089                                     SelectionDAG &DAG) const {
6090   DebugLoc dl = Op.getDebugLoc();
6091
6092   // CF and OF aren't always set the way we want. Determine which
6093   // of these we need.
6094   bool NeedCF = false;
6095   bool NeedOF = false;
6096   switch (X86CC) {
6097   default: break;
6098   case X86::COND_A: case X86::COND_AE:
6099   case X86::COND_B: case X86::COND_BE:
6100     NeedCF = true;
6101     break;
6102   case X86::COND_G: case X86::COND_GE:
6103   case X86::COND_L: case X86::COND_LE:
6104   case X86::COND_O: case X86::COND_NO:
6105     NeedOF = true;
6106     break;
6107   }
6108
6109   // See if we can use the EFLAGS value from the operand instead of
6110   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6111   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6112   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6113     // Emit a CMP with 0, which is the TEST pattern.
6114     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6115                        DAG.getConstant(0, Op.getValueType()));
6116
6117   unsigned Opcode = 0;
6118   unsigned NumOperands = 0;
6119   switch (Op.getNode()->getOpcode()) {
6120   case ISD::ADD:
6121     // Due to an isel shortcoming, be conservative if this add is likely to be
6122     // selected as part of a load-modify-store instruction. When the root node
6123     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6124     // uses of other nodes in the match, such as the ADD in this case. This
6125     // leads to the ADD being left around and reselected, with the result being
6126     // two adds in the output.  Alas, even if none our users are stores, that
6127     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6128     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6129     // climbing the DAG back to the root, and it doesn't seem to be worth the
6130     // effort.
6131     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6132            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6133       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6134         goto default_case;
6135
6136     if (ConstantSDNode *C =
6137         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6138       // An add of one will be selected as an INC.
6139       if (C->getAPIntValue() == 1) {
6140         Opcode = X86ISD::INC;
6141         NumOperands = 1;
6142         break;
6143       }
6144
6145       // An add of negative one (subtract of one) will be selected as a DEC.
6146       if (C->getAPIntValue().isAllOnesValue()) {
6147         Opcode = X86ISD::DEC;
6148         NumOperands = 1;
6149         break;
6150       }
6151     }
6152
6153     // Otherwise use a regular EFLAGS-setting add.
6154     Opcode = X86ISD::ADD;
6155     NumOperands = 2;
6156     break;
6157   case ISD::AND: {
6158     // If the primary and result isn't used, don't bother using X86ISD::AND,
6159     // because a TEST instruction will be better.
6160     bool NonFlagUse = false;
6161     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6162            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6163       SDNode *User = *UI;
6164       unsigned UOpNo = UI.getOperandNo();
6165       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6166         // Look pass truncate.
6167         UOpNo = User->use_begin().getOperandNo();
6168         User = *User->use_begin();
6169       }
6170
6171       if (User->getOpcode() != ISD::BRCOND &&
6172           User->getOpcode() != ISD::SETCC &&
6173           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6174         NonFlagUse = true;
6175         break;
6176       }
6177     }
6178
6179     if (!NonFlagUse)
6180       break;
6181   }
6182     // FALL THROUGH
6183   case ISD::SUB:
6184   case ISD::OR:
6185   case ISD::XOR:
6186     // Due to the ISEL shortcoming noted above, be conservative if this op is
6187     // likely to be selected as part of a load-modify-store instruction.
6188     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6189            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6190       if (UI->getOpcode() == ISD::STORE)
6191         goto default_case;
6192
6193     // Otherwise use a regular EFLAGS-setting instruction.
6194     switch (Op.getNode()->getOpcode()) {
6195     default: llvm_unreachable("unexpected operator!");
6196     case ISD::SUB: Opcode = X86ISD::SUB; break;
6197     case ISD::OR:  Opcode = X86ISD::OR;  break;
6198     case ISD::XOR: Opcode = X86ISD::XOR; break;
6199     case ISD::AND: Opcode = X86ISD::AND; break;
6200     }
6201
6202     NumOperands = 2;
6203     break;
6204   case X86ISD::ADD:
6205   case X86ISD::SUB:
6206   case X86ISD::INC:
6207   case X86ISD::DEC:
6208   case X86ISD::OR:
6209   case X86ISD::XOR:
6210   case X86ISD::AND:
6211     return SDValue(Op.getNode(), 1);
6212   default:
6213   default_case:
6214     break;
6215   }
6216
6217   if (Opcode == 0)
6218     // Emit a CMP with 0, which is the TEST pattern.
6219     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6220                        DAG.getConstant(0, Op.getValueType()));
6221
6222   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6223   SmallVector<SDValue, 4> Ops;
6224   for (unsigned i = 0; i != NumOperands; ++i)
6225     Ops.push_back(Op.getOperand(i));
6226
6227   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6228   DAG.ReplaceAllUsesWith(Op, New);
6229   return SDValue(New.getNode(), 1);
6230 }
6231
6232 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6233 /// equivalent.
6234 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6235                                    SelectionDAG &DAG) const {
6236   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6237     if (C->getAPIntValue() == 0)
6238       return EmitTest(Op0, X86CC, DAG);
6239
6240   DebugLoc dl = Op0.getDebugLoc();
6241   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6242 }
6243
6244 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6245 /// if it's possible.
6246 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6247                                      DebugLoc dl, SelectionDAG &DAG) const {
6248   SDValue Op0 = And.getOperand(0);
6249   SDValue Op1 = And.getOperand(1);
6250   if (Op0.getOpcode() == ISD::TRUNCATE)
6251     Op0 = Op0.getOperand(0);
6252   if (Op1.getOpcode() == ISD::TRUNCATE)
6253     Op1 = Op1.getOperand(0);
6254
6255   SDValue LHS, RHS;
6256   if (Op1.getOpcode() == ISD::SHL)
6257     std::swap(Op0, Op1);
6258   if (Op0.getOpcode() == ISD::SHL) {
6259     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6260       if (And00C->getZExtValue() == 1) {
6261         // If we looked past a truncate, check that it's only truncating away
6262         // known zeros.
6263         unsigned BitWidth = Op0.getValueSizeInBits();
6264         unsigned AndBitWidth = And.getValueSizeInBits();
6265         if (BitWidth > AndBitWidth) {
6266           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6267           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6268           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6269             return SDValue();
6270         }
6271         LHS = Op1;
6272         RHS = Op0.getOperand(1);
6273       }
6274   } else if (Op1.getOpcode() == ISD::Constant) {
6275     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6276     SDValue AndLHS = Op0;
6277     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6278       LHS = AndLHS.getOperand(0);
6279       RHS = AndLHS.getOperand(1);
6280     }
6281   }
6282
6283   if (LHS.getNode()) {
6284     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6285     // instruction.  Since the shift amount is in-range-or-undefined, we know
6286     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6287     // the encoding for the i16 version is larger than the i32 version.
6288     // Also promote i16 to i32 for performance / code size reason.
6289     if (LHS.getValueType() == MVT::i8 ||
6290         LHS.getValueType() == MVT::i16)
6291       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6292
6293     // If the operand types disagree, extend the shift amount to match.  Since
6294     // BT ignores high bits (like shifts) we can use anyextend.
6295     if (LHS.getValueType() != RHS.getValueType())
6296       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6297
6298     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6299     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6300     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6301                        DAG.getConstant(Cond, MVT::i8), BT);
6302   }
6303
6304   return SDValue();
6305 }
6306
6307 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6308   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6309   SDValue Op0 = Op.getOperand(0);
6310   SDValue Op1 = Op.getOperand(1);
6311   DebugLoc dl = Op.getDebugLoc();
6312   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6313
6314   // Optimize to BT if possible.
6315   // Lower (X & (1 << N)) == 0 to BT(X, N).
6316   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6317   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6318   if (Op0.getOpcode() == ISD::AND &&
6319       Op0.hasOneUse() &&
6320       Op1.getOpcode() == ISD::Constant &&
6321       cast<ConstantSDNode>(Op1)->isNullValue() &&
6322       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6323     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6324     if (NewSetCC.getNode())
6325       return NewSetCC;
6326   }
6327
6328   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6329   if (Op0.getOpcode() == X86ISD::SETCC &&
6330       Op1.getOpcode() == ISD::Constant &&
6331       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6332        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6333       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6334     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6335     bool Invert = (CC == ISD::SETNE) ^
6336       cast<ConstantSDNode>(Op1)->isNullValue();
6337     if (Invert)
6338       CCode = X86::GetOppositeBranchCondition(CCode);
6339     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6340                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6341   }
6342
6343   bool isFP = Op1.getValueType().isFloatingPoint();
6344   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6345   if (X86CC == X86::COND_INVALID)
6346     return SDValue();
6347
6348   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6349
6350   // Use sbb x, x to materialize carry bit into a GPR.
6351   if (X86CC == X86::COND_B)
6352     return DAG.getNode(ISD::AND, dl, MVT::i8,
6353                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6354                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6355                        DAG.getConstant(1, MVT::i8));
6356
6357   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6358                      DAG.getConstant(X86CC, MVT::i8), Cond);
6359 }
6360
6361 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6362   SDValue Cond;
6363   SDValue Op0 = Op.getOperand(0);
6364   SDValue Op1 = Op.getOperand(1);
6365   SDValue CC = Op.getOperand(2);
6366   EVT VT = Op.getValueType();
6367   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6368   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6369   DebugLoc dl = Op.getDebugLoc();
6370
6371   if (isFP) {
6372     unsigned SSECC = 8;
6373     EVT VT0 = Op0.getValueType();
6374     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6375     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6376     bool Swap = false;
6377
6378     switch (SetCCOpcode) {
6379     default: break;
6380     case ISD::SETOEQ:
6381     case ISD::SETEQ:  SSECC = 0; break;
6382     case ISD::SETOGT:
6383     case ISD::SETGT: Swap = true; // Fallthrough
6384     case ISD::SETLT:
6385     case ISD::SETOLT: SSECC = 1; break;
6386     case ISD::SETOGE:
6387     case ISD::SETGE: Swap = true; // Fallthrough
6388     case ISD::SETLE:
6389     case ISD::SETOLE: SSECC = 2; break;
6390     case ISD::SETUO:  SSECC = 3; break;
6391     case ISD::SETUNE:
6392     case ISD::SETNE:  SSECC = 4; break;
6393     case ISD::SETULE: Swap = true;
6394     case ISD::SETUGE: SSECC = 5; break;
6395     case ISD::SETULT: Swap = true;
6396     case ISD::SETUGT: SSECC = 6; break;
6397     case ISD::SETO:   SSECC = 7; break;
6398     }
6399     if (Swap)
6400       std::swap(Op0, Op1);
6401
6402     // In the two special cases we can't handle, emit two comparisons.
6403     if (SSECC == 8) {
6404       if (SetCCOpcode == ISD::SETUEQ) {
6405         SDValue UNORD, EQ;
6406         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6407         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6408         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6409       }
6410       else if (SetCCOpcode == ISD::SETONE) {
6411         SDValue ORD, NEQ;
6412         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6413         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6414         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6415       }
6416       llvm_unreachable("Illegal FP comparison");
6417     }
6418     // Handle all other FP comparisons here.
6419     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6420   }
6421
6422   // We are handling one of the integer comparisons here.  Since SSE only has
6423   // GT and EQ comparisons for integer, swapping operands and multiple
6424   // operations may be required for some comparisons.
6425   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6426   bool Swap = false, Invert = false, FlipSigns = false;
6427
6428   switch (VT.getSimpleVT().SimpleTy) {
6429   default: break;
6430   case MVT::v8i8:
6431   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6432   case MVT::v4i16:
6433   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6434   case MVT::v2i32:
6435   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6436   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6437   }
6438
6439   switch (SetCCOpcode) {
6440   default: break;
6441   case ISD::SETNE:  Invert = true;
6442   case ISD::SETEQ:  Opc = EQOpc; break;
6443   case ISD::SETLT:  Swap = true;
6444   case ISD::SETGT:  Opc = GTOpc; break;
6445   case ISD::SETGE:  Swap = true;
6446   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6447   case ISD::SETULT: Swap = true;
6448   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6449   case ISD::SETUGE: Swap = true;
6450   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6451   }
6452   if (Swap)
6453     std::swap(Op0, Op1);
6454
6455   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6456   // bits of the inputs before performing those operations.
6457   if (FlipSigns) {
6458     EVT EltVT = VT.getVectorElementType();
6459     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6460                                       EltVT);
6461     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6462     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6463                                     SignBits.size());
6464     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6465     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6466   }
6467
6468   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6469
6470   // If the logical-not of the result is required, perform that now.
6471   if (Invert)
6472     Result = DAG.getNOT(dl, Result, VT);
6473
6474   return Result;
6475 }
6476
6477 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6478 static bool isX86LogicalCmp(SDValue Op) {
6479   unsigned Opc = Op.getNode()->getOpcode();
6480   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6481     return true;
6482   if (Op.getResNo() == 1 &&
6483       (Opc == X86ISD::ADD ||
6484        Opc == X86ISD::SUB ||
6485        Opc == X86ISD::SMUL ||
6486        Opc == X86ISD::UMUL ||
6487        Opc == X86ISD::INC ||
6488        Opc == X86ISD::DEC ||
6489        Opc == X86ISD::OR ||
6490        Opc == X86ISD::XOR ||
6491        Opc == X86ISD::AND))
6492     return true;
6493
6494   return false;
6495 }
6496
6497 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6498   bool addTest = true;
6499   SDValue Cond  = Op.getOperand(0);
6500   DebugLoc dl = Op.getDebugLoc();
6501   SDValue CC;
6502
6503   if (Cond.getOpcode() == ISD::SETCC) {
6504     SDValue NewCond = LowerSETCC(Cond, DAG);
6505     if (NewCond.getNode())
6506       Cond = NewCond;
6507   }
6508
6509   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6510   SDValue Op1 = Op.getOperand(1);
6511   SDValue Op2 = Op.getOperand(2);
6512   if (Cond.getOpcode() == X86ISD::SETCC &&
6513       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6514     SDValue Cmp = Cond.getOperand(1);
6515     if (Cmp.getOpcode() == X86ISD::CMP) {
6516       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6517       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6518       ConstantSDNode *RHSC =
6519         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6520       if (N1C && N1C->isAllOnesValue() &&
6521           N2C && N2C->isNullValue() &&
6522           RHSC && RHSC->isNullValue()) {
6523         SDValue CmpOp0 = Cmp.getOperand(0);
6524         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6525                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6526         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6527                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6528       }
6529     }
6530   }
6531
6532   // Look pass (and (setcc_carry (cmp ...)), 1).
6533   if (Cond.getOpcode() == ISD::AND &&
6534       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6535     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6536     if (C && C->getAPIntValue() == 1) 
6537       Cond = Cond.getOperand(0);
6538   }
6539
6540   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6541   // setting operand in place of the X86ISD::SETCC.
6542   if (Cond.getOpcode() == X86ISD::SETCC ||
6543       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6544     CC = Cond.getOperand(0);
6545
6546     SDValue Cmp = Cond.getOperand(1);
6547     unsigned Opc = Cmp.getOpcode();
6548     EVT VT = Op.getValueType();
6549
6550     bool IllegalFPCMov = false;
6551     if (VT.isFloatingPoint() && !VT.isVector() &&
6552         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6553       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6554
6555     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6556         Opc == X86ISD::BT) { // FIXME
6557       Cond = Cmp;
6558       addTest = false;
6559     }
6560   }
6561
6562   if (addTest) {
6563     // Look pass the truncate.
6564     if (Cond.getOpcode() == ISD::TRUNCATE)
6565       Cond = Cond.getOperand(0);
6566
6567     // We know the result of AND is compared against zero. Try to match
6568     // it to BT.
6569     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6570       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6571       if (NewSetCC.getNode()) {
6572         CC = NewSetCC.getOperand(0);
6573         Cond = NewSetCC.getOperand(1);
6574         addTest = false;
6575       }
6576     }
6577   }
6578
6579   if (addTest) {
6580     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6581     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6582   }
6583
6584   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6585   // condition is true.
6586   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6587   SDValue Ops[] = { Op2, Op1, CC, Cond };
6588   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6589 }
6590
6591 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6592 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6593 // from the AND / OR.
6594 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6595   Opc = Op.getOpcode();
6596   if (Opc != ISD::OR && Opc != ISD::AND)
6597     return false;
6598   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6599           Op.getOperand(0).hasOneUse() &&
6600           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6601           Op.getOperand(1).hasOneUse());
6602 }
6603
6604 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6605 // 1 and that the SETCC node has a single use.
6606 static bool isXor1OfSetCC(SDValue Op) {
6607   if (Op.getOpcode() != ISD::XOR)
6608     return false;
6609   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6610   if (N1C && N1C->getAPIntValue() == 1) {
6611     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6612       Op.getOperand(0).hasOneUse();
6613   }
6614   return false;
6615 }
6616
6617 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6618   bool addTest = true;
6619   SDValue Chain = Op.getOperand(0);
6620   SDValue Cond  = Op.getOperand(1);
6621   SDValue Dest  = Op.getOperand(2);
6622   DebugLoc dl = Op.getDebugLoc();
6623   SDValue CC;
6624
6625   if (Cond.getOpcode() == ISD::SETCC) {
6626     SDValue NewCond = LowerSETCC(Cond, DAG);
6627     if (NewCond.getNode())
6628       Cond = NewCond;
6629   }
6630 #if 0
6631   // FIXME: LowerXALUO doesn't handle these!!
6632   else if (Cond.getOpcode() == X86ISD::ADD  ||
6633            Cond.getOpcode() == X86ISD::SUB  ||
6634            Cond.getOpcode() == X86ISD::SMUL ||
6635            Cond.getOpcode() == X86ISD::UMUL)
6636     Cond = LowerXALUO(Cond, DAG);
6637 #endif
6638
6639   // Look pass (and (setcc_carry (cmp ...)), 1).
6640   if (Cond.getOpcode() == ISD::AND &&
6641       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6642     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6643     if (C && C->getAPIntValue() == 1) 
6644       Cond = Cond.getOperand(0);
6645   }
6646
6647   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6648   // setting operand in place of the X86ISD::SETCC.
6649   if (Cond.getOpcode() == X86ISD::SETCC ||
6650       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6651     CC = Cond.getOperand(0);
6652
6653     SDValue Cmp = Cond.getOperand(1);
6654     unsigned Opc = Cmp.getOpcode();
6655     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6656     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6657       Cond = Cmp;
6658       addTest = false;
6659     } else {
6660       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6661       default: break;
6662       case X86::COND_O:
6663       case X86::COND_B:
6664         // These can only come from an arithmetic instruction with overflow,
6665         // e.g. SADDO, UADDO.
6666         Cond = Cond.getNode()->getOperand(1);
6667         addTest = false;
6668         break;
6669       }
6670     }
6671   } else {
6672     unsigned CondOpc;
6673     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6674       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6675       if (CondOpc == ISD::OR) {
6676         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6677         // two branches instead of an explicit OR instruction with a
6678         // separate test.
6679         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6680             isX86LogicalCmp(Cmp)) {
6681           CC = Cond.getOperand(0).getOperand(0);
6682           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6683                               Chain, Dest, CC, Cmp);
6684           CC = Cond.getOperand(1).getOperand(0);
6685           Cond = Cmp;
6686           addTest = false;
6687         }
6688       } else { // ISD::AND
6689         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6690         // two branches instead of an explicit AND instruction with a
6691         // separate test. However, we only do this if this block doesn't
6692         // have a fall-through edge, because this requires an explicit
6693         // jmp when the condition is false.
6694         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6695             isX86LogicalCmp(Cmp) &&
6696             Op.getNode()->hasOneUse()) {
6697           X86::CondCode CCode =
6698             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6699           CCode = X86::GetOppositeBranchCondition(CCode);
6700           CC = DAG.getConstant(CCode, MVT::i8);
6701           SDNode *User = *Op.getNode()->use_begin();
6702           // Look for an unconditional branch following this conditional branch.
6703           // We need this because we need to reverse the successors in order
6704           // to implement FCMP_OEQ.
6705           if (User->getOpcode() == ISD::BR) {
6706             SDValue FalseBB = User->getOperand(1);
6707             SDNode *NewBR =
6708               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
6709             assert(NewBR == User);
6710             (void)NewBR;
6711             Dest = FalseBB;
6712
6713             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6714                                 Chain, Dest, CC, Cmp);
6715             X86::CondCode CCode =
6716               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6717             CCode = X86::GetOppositeBranchCondition(CCode);
6718             CC = DAG.getConstant(CCode, MVT::i8);
6719             Cond = Cmp;
6720             addTest = false;
6721           }
6722         }
6723       }
6724     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6725       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6726       // It should be transformed during dag combiner except when the condition
6727       // is set by a arithmetics with overflow node.
6728       X86::CondCode CCode =
6729         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6730       CCode = X86::GetOppositeBranchCondition(CCode);
6731       CC = DAG.getConstant(CCode, MVT::i8);
6732       Cond = Cond.getOperand(0).getOperand(1);
6733       addTest = false;
6734     }
6735   }
6736
6737   if (addTest) {
6738     // Look pass the truncate.
6739     if (Cond.getOpcode() == ISD::TRUNCATE)
6740       Cond = Cond.getOperand(0);
6741
6742     // We know the result of AND is compared against zero. Try to match
6743     // it to BT.
6744     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6745       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6746       if (NewSetCC.getNode()) {
6747         CC = NewSetCC.getOperand(0);
6748         Cond = NewSetCC.getOperand(1);
6749         addTest = false;
6750       }
6751     }
6752   }
6753
6754   if (addTest) {
6755     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6756     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6757   }
6758   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6759                      Chain, Dest, CC, Cond);
6760 }
6761
6762
6763 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6764 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6765 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6766 // that the guard pages used by the OS virtual memory manager are allocated in
6767 // correct sequence.
6768 SDValue
6769 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6770                                            SelectionDAG &DAG) const {
6771   assert(Subtarget->isTargetCygMing() &&
6772          "This should be used only on Cygwin/Mingw targets");
6773   DebugLoc dl = Op.getDebugLoc();
6774
6775   // Get the inputs.
6776   SDValue Chain = Op.getOperand(0);
6777   SDValue Size  = Op.getOperand(1);
6778   // FIXME: Ensure alignment here
6779
6780   SDValue Flag;
6781
6782   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6783
6784   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6785   Flag = Chain.getValue(1);
6786
6787   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6788
6789   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6790   Flag = Chain.getValue(1);
6791
6792   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6793
6794   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6795   return DAG.getMergeValues(Ops1, 2, dl);
6796 }
6797
6798 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6799   MachineFunction &MF = DAG.getMachineFunction();
6800   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6801
6802   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6803   DebugLoc dl = Op.getDebugLoc();
6804
6805   if (!Subtarget->is64Bit()) {
6806     // vastart just stores the address of the VarArgsFrameIndex slot into the
6807     // memory location argument.
6808     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6809                                    getPointerTy());
6810     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6811                         false, false, 0);
6812   }
6813
6814   // __va_list_tag:
6815   //   gp_offset         (0 - 6 * 8)
6816   //   fp_offset         (48 - 48 + 8 * 16)
6817   //   overflow_arg_area (point to parameters coming in memory).
6818   //   reg_save_area
6819   SmallVector<SDValue, 8> MemOps;
6820   SDValue FIN = Op.getOperand(1);
6821   // Store gp_offset
6822   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6823                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6824                                                MVT::i32),
6825                                FIN, SV, 0, false, false, 0);
6826   MemOps.push_back(Store);
6827
6828   // Store fp_offset
6829   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6830                     FIN, DAG.getIntPtrConstant(4));
6831   Store = DAG.getStore(Op.getOperand(0), dl,
6832                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6833                                        MVT::i32),
6834                        FIN, SV, 4, false, false, 0);
6835   MemOps.push_back(Store);
6836
6837   // Store ptr to overflow_arg_area
6838   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6839                     FIN, DAG.getIntPtrConstant(4));
6840   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6841                                     getPointerTy());
6842   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 8,
6843                        false, false, 0);
6844   MemOps.push_back(Store);
6845
6846   // Store ptr to reg_save_area.
6847   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6848                     FIN, DAG.getIntPtrConstant(8));
6849   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6850                                     getPointerTy());
6851   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 16,
6852                        false, false, 0);
6853   MemOps.push_back(Store);
6854   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6855                      &MemOps[0], MemOps.size());
6856 }
6857
6858 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6859   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6860   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6861
6862   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6863   return SDValue();
6864 }
6865
6866 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6867   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6868   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6869   SDValue Chain = Op.getOperand(0);
6870   SDValue DstPtr = Op.getOperand(1);
6871   SDValue SrcPtr = Op.getOperand(2);
6872   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6873   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6874   DebugLoc dl = Op.getDebugLoc();
6875
6876   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6877                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6878                        false, DstSV, 0, SrcSV, 0);
6879 }
6880
6881 SDValue
6882 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6883   DebugLoc dl = Op.getDebugLoc();
6884   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6885   switch (IntNo) {
6886   default: return SDValue();    // Don't custom lower most intrinsics.
6887   // Comparison intrinsics.
6888   case Intrinsic::x86_sse_comieq_ss:
6889   case Intrinsic::x86_sse_comilt_ss:
6890   case Intrinsic::x86_sse_comile_ss:
6891   case Intrinsic::x86_sse_comigt_ss:
6892   case Intrinsic::x86_sse_comige_ss:
6893   case Intrinsic::x86_sse_comineq_ss:
6894   case Intrinsic::x86_sse_ucomieq_ss:
6895   case Intrinsic::x86_sse_ucomilt_ss:
6896   case Intrinsic::x86_sse_ucomile_ss:
6897   case Intrinsic::x86_sse_ucomigt_ss:
6898   case Intrinsic::x86_sse_ucomige_ss:
6899   case Intrinsic::x86_sse_ucomineq_ss:
6900   case Intrinsic::x86_sse2_comieq_sd:
6901   case Intrinsic::x86_sse2_comilt_sd:
6902   case Intrinsic::x86_sse2_comile_sd:
6903   case Intrinsic::x86_sse2_comigt_sd:
6904   case Intrinsic::x86_sse2_comige_sd:
6905   case Intrinsic::x86_sse2_comineq_sd:
6906   case Intrinsic::x86_sse2_ucomieq_sd:
6907   case Intrinsic::x86_sse2_ucomilt_sd:
6908   case Intrinsic::x86_sse2_ucomile_sd:
6909   case Intrinsic::x86_sse2_ucomigt_sd:
6910   case Intrinsic::x86_sse2_ucomige_sd:
6911   case Intrinsic::x86_sse2_ucomineq_sd: {
6912     unsigned Opc = 0;
6913     ISD::CondCode CC = ISD::SETCC_INVALID;
6914     switch (IntNo) {
6915     default: break;
6916     case Intrinsic::x86_sse_comieq_ss:
6917     case Intrinsic::x86_sse2_comieq_sd:
6918       Opc = X86ISD::COMI;
6919       CC = ISD::SETEQ;
6920       break;
6921     case Intrinsic::x86_sse_comilt_ss:
6922     case Intrinsic::x86_sse2_comilt_sd:
6923       Opc = X86ISD::COMI;
6924       CC = ISD::SETLT;
6925       break;
6926     case Intrinsic::x86_sse_comile_ss:
6927     case Intrinsic::x86_sse2_comile_sd:
6928       Opc = X86ISD::COMI;
6929       CC = ISD::SETLE;
6930       break;
6931     case Intrinsic::x86_sse_comigt_ss:
6932     case Intrinsic::x86_sse2_comigt_sd:
6933       Opc = X86ISD::COMI;
6934       CC = ISD::SETGT;
6935       break;
6936     case Intrinsic::x86_sse_comige_ss:
6937     case Intrinsic::x86_sse2_comige_sd:
6938       Opc = X86ISD::COMI;
6939       CC = ISD::SETGE;
6940       break;
6941     case Intrinsic::x86_sse_comineq_ss:
6942     case Intrinsic::x86_sse2_comineq_sd:
6943       Opc = X86ISD::COMI;
6944       CC = ISD::SETNE;
6945       break;
6946     case Intrinsic::x86_sse_ucomieq_ss:
6947     case Intrinsic::x86_sse2_ucomieq_sd:
6948       Opc = X86ISD::UCOMI;
6949       CC = ISD::SETEQ;
6950       break;
6951     case Intrinsic::x86_sse_ucomilt_ss:
6952     case Intrinsic::x86_sse2_ucomilt_sd:
6953       Opc = X86ISD::UCOMI;
6954       CC = ISD::SETLT;
6955       break;
6956     case Intrinsic::x86_sse_ucomile_ss:
6957     case Intrinsic::x86_sse2_ucomile_sd:
6958       Opc = X86ISD::UCOMI;
6959       CC = ISD::SETLE;
6960       break;
6961     case Intrinsic::x86_sse_ucomigt_ss:
6962     case Intrinsic::x86_sse2_ucomigt_sd:
6963       Opc = X86ISD::UCOMI;
6964       CC = ISD::SETGT;
6965       break;
6966     case Intrinsic::x86_sse_ucomige_ss:
6967     case Intrinsic::x86_sse2_ucomige_sd:
6968       Opc = X86ISD::UCOMI;
6969       CC = ISD::SETGE;
6970       break;
6971     case Intrinsic::x86_sse_ucomineq_ss:
6972     case Intrinsic::x86_sse2_ucomineq_sd:
6973       Opc = X86ISD::UCOMI;
6974       CC = ISD::SETNE;
6975       break;
6976     }
6977
6978     SDValue LHS = Op.getOperand(1);
6979     SDValue RHS = Op.getOperand(2);
6980     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6981     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6982     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6983     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6984                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6985     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6986   }
6987   // ptest intrinsics. The intrinsic these come from are designed to return
6988   // an integer value, not just an instruction so lower it to the ptest
6989   // pattern and a setcc for the result.
6990   case Intrinsic::x86_sse41_ptestz:
6991   case Intrinsic::x86_sse41_ptestc:
6992   case Intrinsic::x86_sse41_ptestnzc:{
6993     unsigned X86CC = 0;
6994     switch (IntNo) {
6995     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6996     case Intrinsic::x86_sse41_ptestz:
6997       // ZF = 1
6998       X86CC = X86::COND_E;
6999       break;
7000     case Intrinsic::x86_sse41_ptestc:
7001       // CF = 1
7002       X86CC = X86::COND_B;
7003       break;
7004     case Intrinsic::x86_sse41_ptestnzc:
7005       // ZF and CF = 0
7006       X86CC = X86::COND_A;
7007       break;
7008     }
7009
7010     SDValue LHS = Op.getOperand(1);
7011     SDValue RHS = Op.getOperand(2);
7012     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
7013     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7014     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7015     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7016   }
7017
7018   // Fix vector shift instructions where the last operand is a non-immediate
7019   // i32 value.
7020   case Intrinsic::x86_sse2_pslli_w:
7021   case Intrinsic::x86_sse2_pslli_d:
7022   case Intrinsic::x86_sse2_pslli_q:
7023   case Intrinsic::x86_sse2_psrli_w:
7024   case Intrinsic::x86_sse2_psrli_d:
7025   case Intrinsic::x86_sse2_psrli_q:
7026   case Intrinsic::x86_sse2_psrai_w:
7027   case Intrinsic::x86_sse2_psrai_d:
7028   case Intrinsic::x86_mmx_pslli_w:
7029   case Intrinsic::x86_mmx_pslli_d:
7030   case Intrinsic::x86_mmx_pslli_q:
7031   case Intrinsic::x86_mmx_psrli_w:
7032   case Intrinsic::x86_mmx_psrli_d:
7033   case Intrinsic::x86_mmx_psrli_q:
7034   case Intrinsic::x86_mmx_psrai_w:
7035   case Intrinsic::x86_mmx_psrai_d: {
7036     SDValue ShAmt = Op.getOperand(2);
7037     if (isa<ConstantSDNode>(ShAmt))
7038       return SDValue();
7039
7040     unsigned NewIntNo = 0;
7041     EVT ShAmtVT = MVT::v4i32;
7042     switch (IntNo) {
7043     case Intrinsic::x86_sse2_pslli_w:
7044       NewIntNo = Intrinsic::x86_sse2_psll_w;
7045       break;
7046     case Intrinsic::x86_sse2_pslli_d:
7047       NewIntNo = Intrinsic::x86_sse2_psll_d;
7048       break;
7049     case Intrinsic::x86_sse2_pslli_q:
7050       NewIntNo = Intrinsic::x86_sse2_psll_q;
7051       break;
7052     case Intrinsic::x86_sse2_psrli_w:
7053       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7054       break;
7055     case Intrinsic::x86_sse2_psrli_d:
7056       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7057       break;
7058     case Intrinsic::x86_sse2_psrli_q:
7059       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7060       break;
7061     case Intrinsic::x86_sse2_psrai_w:
7062       NewIntNo = Intrinsic::x86_sse2_psra_w;
7063       break;
7064     case Intrinsic::x86_sse2_psrai_d:
7065       NewIntNo = Intrinsic::x86_sse2_psra_d;
7066       break;
7067     default: {
7068       ShAmtVT = MVT::v2i32;
7069       switch (IntNo) {
7070       case Intrinsic::x86_mmx_pslli_w:
7071         NewIntNo = Intrinsic::x86_mmx_psll_w;
7072         break;
7073       case Intrinsic::x86_mmx_pslli_d:
7074         NewIntNo = Intrinsic::x86_mmx_psll_d;
7075         break;
7076       case Intrinsic::x86_mmx_pslli_q:
7077         NewIntNo = Intrinsic::x86_mmx_psll_q;
7078         break;
7079       case Intrinsic::x86_mmx_psrli_w:
7080         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7081         break;
7082       case Intrinsic::x86_mmx_psrli_d:
7083         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7084         break;
7085       case Intrinsic::x86_mmx_psrli_q:
7086         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7087         break;
7088       case Intrinsic::x86_mmx_psrai_w:
7089         NewIntNo = Intrinsic::x86_mmx_psra_w;
7090         break;
7091       case Intrinsic::x86_mmx_psrai_d:
7092         NewIntNo = Intrinsic::x86_mmx_psra_d;
7093         break;
7094       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7095       }
7096       break;
7097     }
7098     }
7099
7100     // The vector shift intrinsics with scalars uses 32b shift amounts but
7101     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7102     // to be zero.
7103     SDValue ShOps[4];
7104     ShOps[0] = ShAmt;
7105     ShOps[1] = DAG.getConstant(0, MVT::i32);
7106     if (ShAmtVT == MVT::v4i32) {
7107       ShOps[2] = DAG.getUNDEF(MVT::i32);
7108       ShOps[3] = DAG.getUNDEF(MVT::i32);
7109       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7110     } else {
7111       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7112     }
7113
7114     EVT VT = Op.getValueType();
7115     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7116     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7117                        DAG.getConstant(NewIntNo, MVT::i32),
7118                        Op.getOperand(1), ShAmt);
7119   }
7120   }
7121 }
7122
7123 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7124                                            SelectionDAG &DAG) const {
7125   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7126   MFI->setReturnAddressIsTaken(true);
7127
7128   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7129   DebugLoc dl = Op.getDebugLoc();
7130
7131   if (Depth > 0) {
7132     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7133     SDValue Offset =
7134       DAG.getConstant(TD->getPointerSize(),
7135                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7136     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7137                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7138                                    FrameAddr, Offset),
7139                        NULL, 0, false, false, 0);
7140   }
7141
7142   // Just load the return address.
7143   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7144   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7145                      RetAddrFI, NULL, 0, false, false, 0);
7146 }
7147
7148 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7149   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7150   MFI->setFrameAddressIsTaken(true);
7151
7152   EVT VT = Op.getValueType();
7153   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7154   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7155   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7156   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7157   while (Depth--)
7158     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7159                             false, false, 0);
7160   return FrameAddr;
7161 }
7162
7163 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7164                                                      SelectionDAG &DAG) const {
7165   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7166 }
7167
7168 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7169   MachineFunction &MF = DAG.getMachineFunction();
7170   SDValue Chain     = Op.getOperand(0);
7171   SDValue Offset    = Op.getOperand(1);
7172   SDValue Handler   = Op.getOperand(2);
7173   DebugLoc dl       = Op.getDebugLoc();
7174
7175   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7176                                   getPointerTy());
7177   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7178
7179   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7180                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7181   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7182   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7183   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7184   MF.getRegInfo().addLiveOut(StoreAddrReg);
7185
7186   return DAG.getNode(X86ISD::EH_RETURN, dl,
7187                      MVT::Other,
7188                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7189 }
7190
7191 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7192                                              SelectionDAG &DAG) const {
7193   SDValue Root = Op.getOperand(0);
7194   SDValue Trmp = Op.getOperand(1); // trampoline
7195   SDValue FPtr = Op.getOperand(2); // nested function
7196   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7197   DebugLoc dl  = Op.getDebugLoc();
7198
7199   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7200
7201   if (Subtarget->is64Bit()) {
7202     SDValue OutChains[6];
7203
7204     // Large code-model.
7205     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7206     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7207
7208     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7209     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7210
7211     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7212
7213     // Load the pointer to the nested function into R11.
7214     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7215     SDValue Addr = Trmp;
7216     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7217                                 Addr, TrmpAddr, 0, false, false, 0);
7218
7219     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7220                        DAG.getConstant(2, MVT::i64));
7221     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7222                                 false, false, 2);
7223
7224     // Load the 'nest' parameter value into R10.
7225     // R10 is specified in X86CallingConv.td
7226     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7227     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7228                        DAG.getConstant(10, MVT::i64));
7229     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7230                                 Addr, TrmpAddr, 10, false, false, 0);
7231
7232     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7233                        DAG.getConstant(12, MVT::i64));
7234     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7235                                 false, false, 2);
7236
7237     // Jump to the nested function.
7238     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7239     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7240                        DAG.getConstant(20, MVT::i64));
7241     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7242                                 Addr, TrmpAddr, 20, false, false, 0);
7243
7244     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7245     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7246                        DAG.getConstant(22, MVT::i64));
7247     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7248                                 TrmpAddr, 22, false, false, 0);
7249
7250     SDValue Ops[] =
7251       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7252     return DAG.getMergeValues(Ops, 2, dl);
7253   } else {
7254     const Function *Func =
7255       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7256     CallingConv::ID CC = Func->getCallingConv();
7257     unsigned NestReg;
7258
7259     switch (CC) {
7260     default:
7261       llvm_unreachable("Unsupported calling convention");
7262     case CallingConv::C:
7263     case CallingConv::X86_StdCall: {
7264       // Pass 'nest' parameter in ECX.
7265       // Must be kept in sync with X86CallingConv.td
7266       NestReg = X86::ECX;
7267
7268       // Check that ECX wasn't needed by an 'inreg' parameter.
7269       const FunctionType *FTy = Func->getFunctionType();
7270       const AttrListPtr &Attrs = Func->getAttributes();
7271
7272       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7273         unsigned InRegCount = 0;
7274         unsigned Idx = 1;
7275
7276         for (FunctionType::param_iterator I = FTy->param_begin(),
7277              E = FTy->param_end(); I != E; ++I, ++Idx)
7278           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7279             // FIXME: should only count parameters that are lowered to integers.
7280             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7281
7282         if (InRegCount > 2) {
7283           report_fatal_error("Nest register in use - reduce number of inreg"
7284                              " parameters!");
7285         }
7286       }
7287       break;
7288     }
7289     case CallingConv::X86_FastCall:
7290     case CallingConv::X86_ThisCall:
7291     case CallingConv::Fast:
7292       // Pass 'nest' parameter in EAX.
7293       // Must be kept in sync with X86CallingConv.td
7294       NestReg = X86::EAX;
7295       break;
7296     }
7297
7298     SDValue OutChains[4];
7299     SDValue Addr, Disp;
7300
7301     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7302                        DAG.getConstant(10, MVT::i32));
7303     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7304
7305     // This is storing the opcode for MOV32ri.
7306     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7307     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7308     OutChains[0] = DAG.getStore(Root, dl,
7309                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7310                                 Trmp, TrmpAddr, 0, false, false, 0);
7311
7312     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7313                        DAG.getConstant(1, MVT::i32));
7314     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7315                                 false, false, 1);
7316
7317     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7318     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7319                        DAG.getConstant(5, MVT::i32));
7320     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7321                                 TrmpAddr, 5, false, false, 1);
7322
7323     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7324                        DAG.getConstant(6, MVT::i32));
7325     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7326                                 false, false, 1);
7327
7328     SDValue Ops[] =
7329       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7330     return DAG.getMergeValues(Ops, 2, dl);
7331   }
7332 }
7333
7334 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7335                                             SelectionDAG &DAG) const {
7336   /*
7337    The rounding mode is in bits 11:10 of FPSR, and has the following
7338    settings:
7339      00 Round to nearest
7340      01 Round to -inf
7341      10 Round to +inf
7342      11 Round to 0
7343
7344   FLT_ROUNDS, on the other hand, expects the following:
7345     -1 Undefined
7346      0 Round to 0
7347      1 Round to nearest
7348      2 Round to +inf
7349      3 Round to -inf
7350
7351   To perform the conversion, we do:
7352     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7353   */
7354
7355   MachineFunction &MF = DAG.getMachineFunction();
7356   const TargetMachine &TM = MF.getTarget();
7357   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7358   unsigned StackAlignment = TFI.getStackAlignment();
7359   EVT VT = Op.getValueType();
7360   DebugLoc dl = Op.getDebugLoc();
7361
7362   // Save FP Control Word to stack slot
7363   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7364   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7365
7366   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7367                               DAG.getEntryNode(), StackSlot);
7368
7369   // Load FP Control Word from stack slot
7370   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7371                             false, false, 0);
7372
7373   // Transform as necessary
7374   SDValue CWD1 =
7375     DAG.getNode(ISD::SRL, dl, MVT::i16,
7376                 DAG.getNode(ISD::AND, dl, MVT::i16,
7377                             CWD, DAG.getConstant(0x800, MVT::i16)),
7378                 DAG.getConstant(11, MVT::i8));
7379   SDValue CWD2 =
7380     DAG.getNode(ISD::SRL, dl, MVT::i16,
7381                 DAG.getNode(ISD::AND, dl, MVT::i16,
7382                             CWD, DAG.getConstant(0x400, MVT::i16)),
7383                 DAG.getConstant(9, MVT::i8));
7384
7385   SDValue RetVal =
7386     DAG.getNode(ISD::AND, dl, MVT::i16,
7387                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7388                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7389                             DAG.getConstant(1, MVT::i16)),
7390                 DAG.getConstant(3, MVT::i16));
7391
7392
7393   return DAG.getNode((VT.getSizeInBits() < 16 ?
7394                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7395 }
7396
7397 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7398   EVT VT = Op.getValueType();
7399   EVT OpVT = VT;
7400   unsigned NumBits = VT.getSizeInBits();
7401   DebugLoc dl = Op.getDebugLoc();
7402
7403   Op = Op.getOperand(0);
7404   if (VT == MVT::i8) {
7405     // Zero extend to i32 since there is not an i8 bsr.
7406     OpVT = MVT::i32;
7407     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7408   }
7409
7410   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7411   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7412   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7413
7414   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7415   SDValue Ops[] = {
7416     Op,
7417     DAG.getConstant(NumBits+NumBits-1, OpVT),
7418     DAG.getConstant(X86::COND_E, MVT::i8),
7419     Op.getValue(1)
7420   };
7421   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7422
7423   // Finally xor with NumBits-1.
7424   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7425
7426   if (VT == MVT::i8)
7427     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7428   return Op;
7429 }
7430
7431 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7432   EVT VT = Op.getValueType();
7433   EVT OpVT = VT;
7434   unsigned NumBits = VT.getSizeInBits();
7435   DebugLoc dl = Op.getDebugLoc();
7436
7437   Op = Op.getOperand(0);
7438   if (VT == MVT::i8) {
7439     OpVT = MVT::i32;
7440     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7441   }
7442
7443   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7444   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7445   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7446
7447   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7448   SDValue Ops[] = {
7449     Op,
7450     DAG.getConstant(NumBits, OpVT),
7451     DAG.getConstant(X86::COND_E, MVT::i8),
7452     Op.getValue(1)
7453   };
7454   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7455
7456   if (VT == MVT::i8)
7457     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7458   return Op;
7459 }
7460
7461 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7462   EVT VT = Op.getValueType();
7463   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7464   DebugLoc dl = Op.getDebugLoc();
7465
7466   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7467   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7468   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7469   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7470   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7471   //
7472   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7473   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7474   //  return AloBlo + AloBhi + AhiBlo;
7475
7476   SDValue A = Op.getOperand(0);
7477   SDValue B = Op.getOperand(1);
7478
7479   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7480                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7481                        A, DAG.getConstant(32, MVT::i32));
7482   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7483                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7484                        B, DAG.getConstant(32, MVT::i32));
7485   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7486                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7487                        A, B);
7488   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7489                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7490                        A, Bhi);
7491   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7492                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7493                        Ahi, B);
7494   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7495                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7496                        AloBhi, DAG.getConstant(32, MVT::i32));
7497   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7498                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7499                        AhiBlo, DAG.getConstant(32, MVT::i32));
7500   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7501   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7502   return Res;
7503 }
7504
7505 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
7506   EVT VT = Op.getValueType();
7507   DebugLoc dl = Op.getDebugLoc();
7508   SDValue R = Op.getOperand(0);
7509
7510   LLVMContext *Context = DAG.getContext();
7511
7512   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
7513
7514   if (VT == MVT::v4i32) {
7515     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7516                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7517                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
7518
7519     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
7520     
7521     std::vector<Constant*> CV(4, CI);
7522     Constant *C = ConstantVector::get(CV);
7523     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7524     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7525                                  PseudoSourceValue::getConstantPool(), 0,
7526                                  false, false, 16);
7527
7528     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
7529     Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
7530     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
7531     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
7532   }
7533   if (VT == MVT::v16i8) {
7534     // a = a << 5;
7535     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7536                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
7537                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
7538
7539     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
7540     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
7541
7542     std::vector<Constant*> CVM1(16, CM1);
7543     std::vector<Constant*> CVM2(16, CM2);
7544     Constant *C = ConstantVector::get(CVM1);
7545     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7546     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7547                             PseudoSourceValue::getConstantPool(), 0,
7548                             false, false, 16);
7549
7550     // r = pblendv(r, psllw(r & (char16)15, 4), a);
7551     M = DAG.getNode(ISD::AND, dl, VT, R, M);
7552     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7553                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
7554                     DAG.getConstant(4, MVT::i32));
7555     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7556                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
7557                     R, M, Op);
7558     // a += a
7559     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
7560     
7561     C = ConstantVector::get(CVM2);
7562     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7563     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7564                     PseudoSourceValue::getConstantPool(), 0, false, false, 16);
7565     
7566     // r = pblendv(r, psllw(r & (char16)63, 2), a);
7567     M = DAG.getNode(ISD::AND, dl, VT, R, M);
7568     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7569                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
7570                     DAG.getConstant(2, MVT::i32));
7571     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7572                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
7573                     R, M, Op);
7574     // a += a
7575     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
7576     
7577     // return pblendv(r, r+r, a);
7578     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7579                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
7580                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
7581     return R;
7582   }
7583   return SDValue();
7584 }
7585
7586 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7587   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7588   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7589   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7590   // has only one use.
7591   SDNode *N = Op.getNode();
7592   SDValue LHS = N->getOperand(0);
7593   SDValue RHS = N->getOperand(1);
7594   unsigned BaseOp = 0;
7595   unsigned Cond = 0;
7596   DebugLoc dl = Op.getDebugLoc();
7597
7598   switch (Op.getOpcode()) {
7599   default: llvm_unreachable("Unknown ovf instruction!");
7600   case ISD::SADDO:
7601     // A subtract of one will be selected as a INC. Note that INC doesn't
7602     // set CF, so we can't do this for UADDO.
7603     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7604       if (C->getAPIntValue() == 1) {
7605         BaseOp = X86ISD::INC;
7606         Cond = X86::COND_O;
7607         break;
7608       }
7609     BaseOp = X86ISD::ADD;
7610     Cond = X86::COND_O;
7611     break;
7612   case ISD::UADDO:
7613     BaseOp = X86ISD::ADD;
7614     Cond = X86::COND_B;
7615     break;
7616   case ISD::SSUBO:
7617     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7618     // set CF, so we can't do this for USUBO.
7619     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7620       if (C->getAPIntValue() == 1) {
7621         BaseOp = X86ISD::DEC;
7622         Cond = X86::COND_O;
7623         break;
7624       }
7625     BaseOp = X86ISD::SUB;
7626     Cond = X86::COND_O;
7627     break;
7628   case ISD::USUBO:
7629     BaseOp = X86ISD::SUB;
7630     Cond = X86::COND_B;
7631     break;
7632   case ISD::SMULO:
7633     BaseOp = X86ISD::SMUL;
7634     Cond = X86::COND_O;
7635     break;
7636   case ISD::UMULO:
7637     BaseOp = X86ISD::UMUL;
7638     Cond = X86::COND_B;
7639     break;
7640   }
7641
7642   // Also sets EFLAGS.
7643   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7644   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7645
7646   SDValue SetCC =
7647     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7648                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7649
7650   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7651   return Sum;
7652 }
7653
7654 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
7655   DebugLoc dl = Op.getDebugLoc();
7656   
7657   if (!Subtarget->hasSSE2()) {
7658     SDValue Zero = DAG.getConstant(0,
7659                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7660     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
7661                        Zero);
7662   }
7663   
7664   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7665   if(!isDev)
7666     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
7667   else {
7668     unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7669     unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7670     unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
7671     unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
7672     
7673     // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
7674     if (!Op1 && !Op2 && !Op3 && Op4)
7675       return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
7676     
7677     // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
7678     if (Op1 && !Op2 && !Op3 && !Op4)
7679       return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
7680     
7681     // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 
7682     //           (MFENCE)>;
7683     return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
7684   }
7685 }
7686
7687 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7688   EVT T = Op.getValueType();
7689   DebugLoc dl = Op.getDebugLoc();
7690   unsigned Reg = 0;
7691   unsigned size = 0;
7692   switch(T.getSimpleVT().SimpleTy) {
7693   default:
7694     assert(false && "Invalid value type!");
7695   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7696   case MVT::i16: Reg = X86::AX;  size = 2; break;
7697   case MVT::i32: Reg = X86::EAX; size = 4; break;
7698   case MVT::i64:
7699     assert(Subtarget->is64Bit() && "Node not type legal!");
7700     Reg = X86::RAX; size = 8;
7701     break;
7702   }
7703   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7704                                     Op.getOperand(2), SDValue());
7705   SDValue Ops[] = { cpIn.getValue(0),
7706                     Op.getOperand(1),
7707                     Op.getOperand(3),
7708                     DAG.getTargetConstant(size, MVT::i8),
7709                     cpIn.getValue(1) };
7710   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7711   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7712   SDValue cpOut =
7713     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7714   return cpOut;
7715 }
7716
7717 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7718                                                  SelectionDAG &DAG) const {
7719   assert(Subtarget->is64Bit() && "Result not type legalized?");
7720   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7721   SDValue TheChain = Op.getOperand(0);
7722   DebugLoc dl = Op.getDebugLoc();
7723   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7724   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7725   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7726                                    rax.getValue(2));
7727   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7728                             DAG.getConstant(32, MVT::i8));
7729   SDValue Ops[] = {
7730     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7731     rdx.getValue(1)
7732   };
7733   return DAG.getMergeValues(Ops, 2, dl);
7734 }
7735
7736 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
7737                                             SelectionDAG &DAG) const {
7738   EVT SrcVT = Op.getOperand(0).getValueType();
7739   EVT DstVT = Op.getValueType();
7740   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
7741           Subtarget->hasMMX() && !DisableMMX) &&
7742          "Unexpected custom BIT_CONVERT");
7743   assert((DstVT == MVT::i64 || 
7744           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
7745          "Unexpected custom BIT_CONVERT");
7746   // i64 <=> MMX conversions are Legal.
7747   if (SrcVT==MVT::i64 && DstVT.isVector())
7748     return Op;
7749   if (DstVT==MVT::i64 && SrcVT.isVector())
7750     return Op;
7751   // MMX <=> MMX conversions are Legal.
7752   if (SrcVT.isVector() && DstVT.isVector())
7753     return Op;
7754   // All other conversions need to be expanded.
7755   return SDValue();
7756 }
7757 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7758   SDNode *Node = Op.getNode();
7759   DebugLoc dl = Node->getDebugLoc();
7760   EVT T = Node->getValueType(0);
7761   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7762                               DAG.getConstant(0, T), Node->getOperand(2));
7763   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7764                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7765                        Node->getOperand(0),
7766                        Node->getOperand(1), negOp,
7767                        cast<AtomicSDNode>(Node)->getSrcValue(),
7768                        cast<AtomicSDNode>(Node)->getAlignment());
7769 }
7770
7771 /// LowerOperation - Provide custom lowering hooks for some operations.
7772 ///
7773 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7774   switch (Op.getOpcode()) {
7775   default: llvm_unreachable("Should not custom lower this!");
7776   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
7777   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7778   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7779   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7780   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7781   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7782   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7783   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7784   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7785   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7786   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7787   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7788   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7789   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7790   case ISD::SHL_PARTS:
7791   case ISD::SRA_PARTS:
7792   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7793   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7794   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7795   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7796   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7797   case ISD::FABS:               return LowerFABS(Op, DAG);
7798   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7799   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7800   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7801   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7802   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7803   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7804   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7805   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7806   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7807   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7808   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7809   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7810   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7811   case ISD::FRAME_TO_ARGS_OFFSET:
7812                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7813   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7814   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7815   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7816   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7817   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7818   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7819   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7820   case ISD::SHL:                return LowerSHL(Op, DAG);
7821   case ISD::SADDO:
7822   case ISD::UADDO:
7823   case ISD::SSUBO:
7824   case ISD::USUBO:
7825   case ISD::SMULO:
7826   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7827   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7828   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
7829   }
7830 }
7831
7832 void X86TargetLowering::
7833 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7834                         SelectionDAG &DAG, unsigned NewOp) const {
7835   EVT T = Node->getValueType(0);
7836   DebugLoc dl = Node->getDebugLoc();
7837   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7838
7839   SDValue Chain = Node->getOperand(0);
7840   SDValue In1 = Node->getOperand(1);
7841   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7842                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7843   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7844                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7845   SDValue Ops[] = { Chain, In1, In2L, In2H };
7846   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7847   SDValue Result =
7848     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7849                             cast<MemSDNode>(Node)->getMemOperand());
7850   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7851   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7852   Results.push_back(Result.getValue(2));
7853 }
7854
7855 /// ReplaceNodeResults - Replace a node with an illegal result type
7856 /// with a new node built out of custom code.
7857 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7858                                            SmallVectorImpl<SDValue>&Results,
7859                                            SelectionDAG &DAG) const {
7860   DebugLoc dl = N->getDebugLoc();
7861   switch (N->getOpcode()) {
7862   default:
7863     assert(false && "Do not know how to custom type legalize this operation!");
7864     return;
7865   case ISD::FP_TO_SINT: {
7866     std::pair<SDValue,SDValue> Vals =
7867         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7868     SDValue FIST = Vals.first, StackSlot = Vals.second;
7869     if (FIST.getNode() != 0) {
7870       EVT VT = N->getValueType(0);
7871       // Return a load from the stack slot.
7872       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7873                                     false, false, 0));
7874     }
7875     return;
7876   }
7877   case ISD::READCYCLECOUNTER: {
7878     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7879     SDValue TheChain = N->getOperand(0);
7880     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7881     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7882                                      rd.getValue(1));
7883     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7884                                      eax.getValue(2));
7885     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7886     SDValue Ops[] = { eax, edx };
7887     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7888     Results.push_back(edx.getValue(1));
7889     return;
7890   }
7891   case ISD::ATOMIC_CMP_SWAP: {
7892     EVT T = N->getValueType(0);
7893     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7894     SDValue cpInL, cpInH;
7895     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7896                         DAG.getConstant(0, MVT::i32));
7897     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7898                         DAG.getConstant(1, MVT::i32));
7899     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7900     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7901                              cpInL.getValue(1));
7902     SDValue swapInL, swapInH;
7903     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7904                           DAG.getConstant(0, MVT::i32));
7905     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7906                           DAG.getConstant(1, MVT::i32));
7907     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7908                                cpInH.getValue(1));
7909     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7910                                swapInL.getValue(1));
7911     SDValue Ops[] = { swapInH.getValue(0),
7912                       N->getOperand(1),
7913                       swapInH.getValue(1) };
7914     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7915     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7916     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7917                                         MVT::i32, Result.getValue(1));
7918     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7919                                         MVT::i32, cpOutL.getValue(2));
7920     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7921     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7922     Results.push_back(cpOutH.getValue(1));
7923     return;
7924   }
7925   case ISD::ATOMIC_LOAD_ADD:
7926     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7927     return;
7928   case ISD::ATOMIC_LOAD_AND:
7929     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7930     return;
7931   case ISD::ATOMIC_LOAD_NAND:
7932     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7933     return;
7934   case ISD::ATOMIC_LOAD_OR:
7935     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7936     return;
7937   case ISD::ATOMIC_LOAD_SUB:
7938     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7939     return;
7940   case ISD::ATOMIC_LOAD_XOR:
7941     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7942     return;
7943   case ISD::ATOMIC_SWAP:
7944     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7945     return;
7946   }
7947 }
7948
7949 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7950   switch (Opcode) {
7951   default: return NULL;
7952   case X86ISD::BSF:                return "X86ISD::BSF";
7953   case X86ISD::BSR:                return "X86ISD::BSR";
7954   case X86ISD::SHLD:               return "X86ISD::SHLD";
7955   case X86ISD::SHRD:               return "X86ISD::SHRD";
7956   case X86ISD::FAND:               return "X86ISD::FAND";
7957   case X86ISD::FOR:                return "X86ISD::FOR";
7958   case X86ISD::FXOR:               return "X86ISD::FXOR";
7959   case X86ISD::FSRL:               return "X86ISD::FSRL";
7960   case X86ISD::FILD:               return "X86ISD::FILD";
7961   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7962   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7963   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7964   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7965   case X86ISD::FLD:                return "X86ISD::FLD";
7966   case X86ISD::FST:                return "X86ISD::FST";
7967   case X86ISD::CALL:               return "X86ISD::CALL";
7968   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7969   case X86ISD::BT:                 return "X86ISD::BT";
7970   case X86ISD::CMP:                return "X86ISD::CMP";
7971   case X86ISD::COMI:               return "X86ISD::COMI";
7972   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7973   case X86ISD::SETCC:              return "X86ISD::SETCC";
7974   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7975   case X86ISD::CMOV:               return "X86ISD::CMOV";
7976   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7977   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7978   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7979   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7980   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7981   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7982   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7983   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7984   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7985   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7986   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7987   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7988   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7989   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7990   case X86ISD::FMAX:               return "X86ISD::FMAX";
7991   case X86ISD::FMIN:               return "X86ISD::FMIN";
7992   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7993   case X86ISD::FRCP:               return "X86ISD::FRCP";
7994   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7995   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
7996   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7997   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7998   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7999   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8000   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8001   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8002   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8003   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8004   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8005   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8006   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8007   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8008   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8009   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8010   case X86ISD::VSHL:               return "X86ISD::VSHL";
8011   case X86ISD::VSRL:               return "X86ISD::VSRL";
8012   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8013   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8014   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8015   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8016   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8017   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8018   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8019   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8020   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8021   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8022   case X86ISD::ADD:                return "X86ISD::ADD";
8023   case X86ISD::SUB:                return "X86ISD::SUB";
8024   case X86ISD::SMUL:               return "X86ISD::SMUL";
8025   case X86ISD::UMUL:               return "X86ISD::UMUL";
8026   case X86ISD::INC:                return "X86ISD::INC";
8027   case X86ISD::DEC:                return "X86ISD::DEC";
8028   case X86ISD::OR:                 return "X86ISD::OR";
8029   case X86ISD::XOR:                return "X86ISD::XOR";
8030   case X86ISD::AND:                return "X86ISD::AND";
8031   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8032   case X86ISD::PTEST:              return "X86ISD::PTEST";
8033   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8034   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
8035   }
8036 }
8037
8038 // isLegalAddressingMode - Return true if the addressing mode represented
8039 // by AM is legal for this target, for a load/store of the specified type.
8040 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8041                                               const Type *Ty) const {
8042   // X86 supports extremely general addressing modes.
8043   CodeModel::Model M = getTargetMachine().getCodeModel();
8044
8045   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8046   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8047     return false;
8048
8049   if (AM.BaseGV) {
8050     unsigned GVFlags =
8051       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8052
8053     // If a reference to this global requires an extra load, we can't fold it.
8054     if (isGlobalStubReference(GVFlags))
8055       return false;
8056
8057     // If BaseGV requires a register for the PIC base, we cannot also have a
8058     // BaseReg specified.
8059     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8060       return false;
8061
8062     // If lower 4G is not available, then we must use rip-relative addressing.
8063     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8064       return false;
8065   }
8066
8067   switch (AM.Scale) {
8068   case 0:
8069   case 1:
8070   case 2:
8071   case 4:
8072   case 8:
8073     // These scales always work.
8074     break;
8075   case 3:
8076   case 5:
8077   case 9:
8078     // These scales are formed with basereg+scalereg.  Only accept if there is
8079     // no basereg yet.
8080     if (AM.HasBaseReg)
8081       return false;
8082     break;
8083   default:  // Other stuff never works.
8084     return false;
8085   }
8086
8087   return true;
8088 }
8089
8090
8091 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8092   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8093     return false;
8094   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8095   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8096   if (NumBits1 <= NumBits2)
8097     return false;
8098   return true;
8099 }
8100
8101 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8102   if (!VT1.isInteger() || !VT2.isInteger())
8103     return false;
8104   unsigned NumBits1 = VT1.getSizeInBits();
8105   unsigned NumBits2 = VT2.getSizeInBits();
8106   if (NumBits1 <= NumBits2)
8107     return false;
8108   return true;
8109 }
8110
8111 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8112   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8113   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8114 }
8115
8116 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8117   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8118   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8119 }
8120
8121 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8122   // i16 instructions are longer (0x66 prefix) and potentially slower.
8123   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8124 }
8125
8126 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8127 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8128 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8129 /// are assumed to be legal.
8130 bool
8131 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8132                                       EVT VT) const {
8133   // Very little shuffling can be done for 64-bit vectors right now.
8134   if (VT.getSizeInBits() == 64)
8135     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8136
8137   // FIXME: pshufb, blends, shifts.
8138   return (VT.getVectorNumElements() == 2 ||
8139           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8140           isMOVLMask(M, VT) ||
8141           isSHUFPMask(M, VT) ||
8142           isPSHUFDMask(M, VT) ||
8143           isPSHUFHWMask(M, VT) ||
8144           isPSHUFLWMask(M, VT) ||
8145           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8146           isUNPCKLMask(M, VT) ||
8147           isUNPCKHMask(M, VT) ||
8148           isUNPCKL_v_undef_Mask(M, VT) ||
8149           isUNPCKH_v_undef_Mask(M, VT));
8150 }
8151
8152 bool
8153 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8154                                           EVT VT) const {
8155   unsigned NumElts = VT.getVectorNumElements();
8156   // FIXME: This collection of masks seems suspect.
8157   if (NumElts == 2)
8158     return true;
8159   if (NumElts == 4 && VT.getSizeInBits() == 128) {
8160     return (isMOVLMask(Mask, VT)  ||
8161             isCommutedMOVLMask(Mask, VT, true) ||
8162             isSHUFPMask(Mask, VT) ||
8163             isCommutedSHUFPMask(Mask, VT));
8164   }
8165   return false;
8166 }
8167
8168 //===----------------------------------------------------------------------===//
8169 //                           X86 Scheduler Hooks
8170 //===----------------------------------------------------------------------===//
8171
8172 // private utility function
8173 MachineBasicBlock *
8174 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8175                                                        MachineBasicBlock *MBB,
8176                                                        unsigned regOpc,
8177                                                        unsigned immOpc,
8178                                                        unsigned LoadOpc,
8179                                                        unsigned CXchgOpc,
8180                                                        unsigned notOpc,
8181                                                        unsigned EAXreg,
8182                                                        TargetRegisterClass *RC,
8183                                                        bool invSrc) const {
8184   // For the atomic bitwise operator, we generate
8185   //   thisMBB:
8186   //   newMBB:
8187   //     ld  t1 = [bitinstr.addr]
8188   //     op  t2 = t1, [bitinstr.val]
8189   //     mov EAX = t1
8190   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8191   //     bz  newMBB
8192   //     fallthrough -->nextMBB
8193   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8194   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8195   MachineFunction::iterator MBBIter = MBB;
8196   ++MBBIter;
8197
8198   /// First build the CFG
8199   MachineFunction *F = MBB->getParent();
8200   MachineBasicBlock *thisMBB = MBB;
8201   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8202   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8203   F->insert(MBBIter, newMBB);
8204   F->insert(MBBIter, nextMBB);
8205
8206   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8207   nextMBB->splice(nextMBB->begin(), thisMBB,
8208                   llvm::next(MachineBasicBlock::iterator(bInstr)),
8209                   thisMBB->end());
8210   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8211
8212   // Update thisMBB to fall through to newMBB
8213   thisMBB->addSuccessor(newMBB);
8214
8215   // newMBB jumps to itself and fall through to nextMBB
8216   newMBB->addSuccessor(nextMBB);
8217   newMBB->addSuccessor(newMBB);
8218
8219   // Insert instructions into newMBB based on incoming instruction
8220   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
8221          "unexpected number of operands");
8222   DebugLoc dl = bInstr->getDebugLoc();
8223   MachineOperand& destOper = bInstr->getOperand(0);
8224   MachineOperand* argOpers[2 + X86::AddrNumOperands];
8225   int numArgs = bInstr->getNumOperands() - 1;
8226   for (int i=0; i < numArgs; ++i)
8227     argOpers[i] = &bInstr->getOperand(i+1);
8228
8229   // x86 address has 4 operands: base, index, scale, and displacement
8230   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8231   int valArgIndx = lastAddrIndx + 1;
8232
8233   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8234   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8235   for (int i=0; i <= lastAddrIndx; ++i)
8236     (*MIB).addOperand(*argOpers[i]);
8237
8238   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8239   if (invSrc) {
8240     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8241   }
8242   else
8243     tt = t1;
8244
8245   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8246   assert((argOpers[valArgIndx]->isReg() ||
8247           argOpers[valArgIndx]->isImm()) &&
8248          "invalid operand");
8249   if (argOpers[valArgIndx]->isReg())
8250     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8251   else
8252     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8253   MIB.addReg(tt);
8254   (*MIB).addOperand(*argOpers[valArgIndx]);
8255
8256   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
8257   MIB.addReg(t1);
8258
8259   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8260   for (int i=0; i <= lastAddrIndx; ++i)
8261     (*MIB).addOperand(*argOpers[i]);
8262   MIB.addReg(t2);
8263   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8264   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8265                     bInstr->memoperands_end());
8266
8267   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
8268   MIB.addReg(EAXreg);
8269
8270   // insert branch
8271   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8272
8273   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
8274   return nextMBB;
8275 }
8276
8277 // private utility function:  64 bit atomics on 32 bit host.
8278 MachineBasicBlock *
8279 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8280                                                        MachineBasicBlock *MBB,
8281                                                        unsigned regOpcL,
8282                                                        unsigned regOpcH,
8283                                                        unsigned immOpcL,
8284                                                        unsigned immOpcH,
8285                                                        bool invSrc) const {
8286   // For the atomic bitwise operator, we generate
8287   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8288   //     ld t1,t2 = [bitinstr.addr]
8289   //   newMBB:
8290   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8291   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8292   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8293   //     mov ECX, EBX <- t5, t6
8294   //     mov EAX, EDX <- t1, t2
8295   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8296   //     mov t3, t4 <- EAX, EDX
8297   //     bz  newMBB
8298   //     result in out1, out2
8299   //     fallthrough -->nextMBB
8300
8301   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8302   const unsigned LoadOpc = X86::MOV32rm;
8303   const unsigned NotOpc = X86::NOT32r;
8304   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8305   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8306   MachineFunction::iterator MBBIter = MBB;
8307   ++MBBIter;
8308
8309   /// First build the CFG
8310   MachineFunction *F = MBB->getParent();
8311   MachineBasicBlock *thisMBB = MBB;
8312   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8313   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8314   F->insert(MBBIter, newMBB);
8315   F->insert(MBBIter, nextMBB);
8316
8317   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8318   nextMBB->splice(nextMBB->begin(), thisMBB,
8319                   llvm::next(MachineBasicBlock::iterator(bInstr)),
8320                   thisMBB->end());
8321   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8322
8323   // Update thisMBB to fall through to newMBB
8324   thisMBB->addSuccessor(newMBB);
8325
8326   // newMBB jumps to itself and fall through to nextMBB
8327   newMBB->addSuccessor(nextMBB);
8328   newMBB->addSuccessor(newMBB);
8329
8330   DebugLoc dl = bInstr->getDebugLoc();
8331   // Insert instructions into newMBB based on incoming instruction
8332   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8333   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
8334          "unexpected number of operands");
8335   MachineOperand& dest1Oper = bInstr->getOperand(0);
8336   MachineOperand& dest2Oper = bInstr->getOperand(1);
8337   MachineOperand* argOpers[2 + X86::AddrNumOperands];
8338   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
8339     argOpers[i] = &bInstr->getOperand(i+2);
8340
8341     // We use some of the operands multiple times, so conservatively just
8342     // clear any kill flags that might be present.
8343     if (argOpers[i]->isReg() && argOpers[i]->isUse())
8344       argOpers[i]->setIsKill(false);
8345   }
8346
8347   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8348   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8349
8350   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8351   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8352   for (int i=0; i <= lastAddrIndx; ++i)
8353     (*MIB).addOperand(*argOpers[i]);
8354   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8355   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8356   // add 4 to displacement.
8357   for (int i=0; i <= lastAddrIndx-2; ++i)
8358     (*MIB).addOperand(*argOpers[i]);
8359   MachineOperand newOp3 = *(argOpers[3]);
8360   if (newOp3.isImm())
8361     newOp3.setImm(newOp3.getImm()+4);
8362   else
8363     newOp3.setOffset(newOp3.getOffset()+4);
8364   (*MIB).addOperand(newOp3);
8365   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8366
8367   // t3/4 are defined later, at the bottom of the loop
8368   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8369   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8370   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8371     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8372   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8373     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8374
8375   // The subsequent operations should be using the destination registers of
8376   //the PHI instructions.
8377   if (invSrc) {
8378     t1 = F->getRegInfo().createVirtualRegister(RC);
8379     t2 = F->getRegInfo().createVirtualRegister(RC);
8380     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8381     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8382   } else {
8383     t1 = dest1Oper.getReg();
8384     t2 = dest2Oper.getReg();
8385   }
8386
8387   int valArgIndx = lastAddrIndx + 1;
8388   assert((argOpers[valArgIndx]->isReg() ||
8389           argOpers[valArgIndx]->isImm()) &&
8390          "invalid operand");
8391   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8392   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8393   if (argOpers[valArgIndx]->isReg())
8394     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8395   else
8396     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8397   if (regOpcL != X86::MOV32rr)
8398     MIB.addReg(t1);
8399   (*MIB).addOperand(*argOpers[valArgIndx]);
8400   assert(argOpers[valArgIndx + 1]->isReg() ==
8401          argOpers[valArgIndx]->isReg());
8402   assert(argOpers[valArgIndx + 1]->isImm() ==
8403          argOpers[valArgIndx]->isImm());
8404   if (argOpers[valArgIndx + 1]->isReg())
8405     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8406   else
8407     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8408   if (regOpcH != X86::MOV32rr)
8409     MIB.addReg(t2);
8410   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8411
8412   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
8413   MIB.addReg(t1);
8414   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
8415   MIB.addReg(t2);
8416
8417   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
8418   MIB.addReg(t5);
8419   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
8420   MIB.addReg(t6);
8421
8422   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8423   for (int i=0; i <= lastAddrIndx; ++i)
8424     (*MIB).addOperand(*argOpers[i]);
8425
8426   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8427   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8428                     bInstr->memoperands_end());
8429
8430   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
8431   MIB.addReg(X86::EAX);
8432   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
8433   MIB.addReg(X86::EDX);
8434
8435   // insert branch
8436   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8437
8438   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
8439   return nextMBB;
8440 }
8441
8442 // private utility function
8443 MachineBasicBlock *
8444 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8445                                                       MachineBasicBlock *MBB,
8446                                                       unsigned cmovOpc) const {
8447   // For the atomic min/max operator, we generate
8448   //   thisMBB:
8449   //   newMBB:
8450   //     ld t1 = [min/max.addr]
8451   //     mov t2 = [min/max.val]
8452   //     cmp  t1, t2
8453   //     cmov[cond] t2 = t1
8454   //     mov EAX = t1
8455   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8456   //     bz   newMBB
8457   //     fallthrough -->nextMBB
8458   //
8459   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8460   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8461   MachineFunction::iterator MBBIter = MBB;
8462   ++MBBIter;
8463
8464   /// First build the CFG
8465   MachineFunction *F = MBB->getParent();
8466   MachineBasicBlock *thisMBB = MBB;
8467   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8468   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8469   F->insert(MBBIter, newMBB);
8470   F->insert(MBBIter, nextMBB);
8471
8472   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8473   nextMBB->splice(nextMBB->begin(), thisMBB,
8474                   llvm::next(MachineBasicBlock::iterator(mInstr)),
8475                   thisMBB->end());
8476   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8477
8478   // Update thisMBB to fall through to newMBB
8479   thisMBB->addSuccessor(newMBB);
8480
8481   // newMBB jumps to newMBB and fall through to nextMBB
8482   newMBB->addSuccessor(nextMBB);
8483   newMBB->addSuccessor(newMBB);
8484
8485   DebugLoc dl = mInstr->getDebugLoc();
8486   // Insert instructions into newMBB based on incoming instruction
8487   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
8488          "unexpected number of operands");
8489   MachineOperand& destOper = mInstr->getOperand(0);
8490   MachineOperand* argOpers[2 + X86::AddrNumOperands];
8491   int numArgs = mInstr->getNumOperands() - 1;
8492   for (int i=0; i < numArgs; ++i)
8493     argOpers[i] = &mInstr->getOperand(i+1);
8494
8495   // x86 address has 4 operands: base, index, scale, and displacement
8496   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8497   int valArgIndx = lastAddrIndx + 1;
8498
8499   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8500   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8501   for (int i=0; i <= lastAddrIndx; ++i)
8502     (*MIB).addOperand(*argOpers[i]);
8503
8504   // We only support register and immediate values
8505   assert((argOpers[valArgIndx]->isReg() ||
8506           argOpers[valArgIndx]->isImm()) &&
8507          "invalid operand");
8508
8509   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8510   if (argOpers[valArgIndx]->isReg())
8511     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
8512   else
8513     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8514   (*MIB).addOperand(*argOpers[valArgIndx]);
8515
8516   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
8517   MIB.addReg(t1);
8518
8519   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8520   MIB.addReg(t1);
8521   MIB.addReg(t2);
8522
8523   // Generate movc
8524   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8525   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8526   MIB.addReg(t2);
8527   MIB.addReg(t1);
8528
8529   // Cmp and exchange if none has modified the memory location
8530   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8531   for (int i=0; i <= lastAddrIndx; ++i)
8532     (*MIB).addOperand(*argOpers[i]);
8533   MIB.addReg(t3);
8534   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8535   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8536                     mInstr->memoperands_end());
8537
8538   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
8539   MIB.addReg(X86::EAX);
8540
8541   // insert branch
8542   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8543
8544   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
8545   return nextMBB;
8546 }
8547
8548 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8549 // or XMM0_V32I8 in AVX all of this code can be replaced with that
8550 // in the .td file.
8551 MachineBasicBlock *
8552 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8553                             unsigned numArgs, bool memArg) const {
8554
8555   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
8556          "Target must have SSE4.2 or AVX features enabled");
8557
8558   DebugLoc dl = MI->getDebugLoc();
8559   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8560
8561   unsigned Opc;
8562
8563   if (!Subtarget->hasAVX()) {
8564     if (memArg)
8565       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8566     else
8567       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8568   } else {
8569     if (memArg)
8570       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
8571     else
8572       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
8573   }
8574
8575   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8576
8577   for (unsigned i = 0; i < numArgs; ++i) {
8578     MachineOperand &Op = MI->getOperand(i+1);
8579
8580     if (!(Op.isReg() && Op.isImplicit()))
8581       MIB.addOperand(Op);
8582   }
8583
8584   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8585     .addReg(X86::XMM0);
8586
8587   MI->eraseFromParent();
8588
8589   return BB;
8590 }
8591
8592 MachineBasicBlock *
8593 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8594                                                  MachineInstr *MI,
8595                                                  MachineBasicBlock *MBB) const {
8596   // Emit code to save XMM registers to the stack. The ABI says that the
8597   // number of registers to save is given in %al, so it's theoretically
8598   // possible to do an indirect jump trick to avoid saving all of them,
8599   // however this code takes a simpler approach and just executes all
8600   // of the stores if %al is non-zero. It's less code, and it's probably
8601   // easier on the hardware branch predictor, and stores aren't all that
8602   // expensive anyway.
8603
8604   // Create the new basic blocks. One block contains all the XMM stores,
8605   // and one block is the final destination regardless of whether any
8606   // stores were performed.
8607   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8608   MachineFunction *F = MBB->getParent();
8609   MachineFunction::iterator MBBIter = MBB;
8610   ++MBBIter;
8611   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8612   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8613   F->insert(MBBIter, XMMSaveMBB);
8614   F->insert(MBBIter, EndMBB);
8615
8616   // Transfer the remainder of MBB and its successor edges to EndMBB.
8617   EndMBB->splice(EndMBB->begin(), MBB,
8618                  llvm::next(MachineBasicBlock::iterator(MI)),
8619                  MBB->end());
8620   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
8621
8622   // The original block will now fall through to the XMM save block.
8623   MBB->addSuccessor(XMMSaveMBB);
8624   // The XMMSaveMBB will fall through to the end block.
8625   XMMSaveMBB->addSuccessor(EndMBB);
8626
8627   // Now add the instructions.
8628   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8629   DebugLoc DL = MI->getDebugLoc();
8630
8631   unsigned CountReg = MI->getOperand(0).getReg();
8632   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8633   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8634
8635   if (!Subtarget->isTargetWin64()) {
8636     // If %al is 0, branch around the XMM save block.
8637     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8638     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8639     MBB->addSuccessor(EndMBB);
8640   }
8641
8642   // In the XMM save block, save all the XMM argument registers.
8643   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8644     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8645     MachineMemOperand *MMO =
8646       F->getMachineMemOperand(
8647         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8648         MachineMemOperand::MOStore, Offset,
8649         /*Size=*/16, /*Align=*/16);
8650     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8651       .addFrameIndex(RegSaveFrameIndex)
8652       .addImm(/*Scale=*/1)
8653       .addReg(/*IndexReg=*/0)
8654       .addImm(/*Disp=*/Offset)
8655       .addReg(/*Segment=*/0)
8656       .addReg(MI->getOperand(i).getReg())
8657       .addMemOperand(MMO);
8658   }
8659
8660   MI->eraseFromParent();   // The pseudo instruction is gone now.
8661
8662   return EndMBB;
8663 }
8664
8665 MachineBasicBlock *
8666 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8667                                      MachineBasicBlock *BB) const {
8668   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8669   DebugLoc DL = MI->getDebugLoc();
8670
8671   // To "insert" a SELECT_CC instruction, we actually have to insert the
8672   // diamond control-flow pattern.  The incoming instruction knows the
8673   // destination vreg to set, the condition code register to branch on, the
8674   // true/false values to select between, and a branch opcode to use.
8675   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8676   MachineFunction::iterator It = BB;
8677   ++It;
8678
8679   //  thisMBB:
8680   //  ...
8681   //   TrueVal = ...
8682   //   cmpTY ccX, r1, r2
8683   //   bCC copy1MBB
8684   //   fallthrough --> copy0MBB
8685   MachineBasicBlock *thisMBB = BB;
8686   MachineFunction *F = BB->getParent();
8687   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8688   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8689   F->insert(It, copy0MBB);
8690   F->insert(It, sinkMBB);
8691
8692   // If the EFLAGS register isn't dead in the terminator, then claim that it's
8693   // live into the sink and copy blocks.
8694   const MachineFunction *MF = BB->getParent();
8695   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
8696   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
8697
8698   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
8699     const MachineOperand &MO = MI->getOperand(I);
8700     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
8701     unsigned Reg = MO.getReg();
8702     if (Reg != X86::EFLAGS) continue;
8703     copy0MBB->addLiveIn(Reg);
8704     sinkMBB->addLiveIn(Reg);
8705   }
8706
8707   // Transfer the remainder of BB and its successor edges to sinkMBB.
8708   sinkMBB->splice(sinkMBB->begin(), BB,
8709                   llvm::next(MachineBasicBlock::iterator(MI)),
8710                   BB->end());
8711   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8712
8713   // Add the true and fallthrough blocks as its successors.
8714   BB->addSuccessor(copy0MBB);
8715   BB->addSuccessor(sinkMBB);
8716
8717   // Create the conditional branch instruction.
8718   unsigned Opc =
8719     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8720   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8721
8722   //  copy0MBB:
8723   //   %FalseValue = ...
8724   //   # fallthrough to sinkMBB
8725   copy0MBB->addSuccessor(sinkMBB);
8726
8727   //  sinkMBB:
8728   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8729   //  ...
8730   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8731           TII->get(X86::PHI), MI->getOperand(0).getReg())
8732     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8733     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8734
8735   MI->eraseFromParent();   // The pseudo instruction is gone now.
8736   return sinkMBB;
8737 }
8738
8739 MachineBasicBlock *
8740 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8741                                           MachineBasicBlock *BB) const {
8742   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8743   DebugLoc DL = MI->getDebugLoc();
8744
8745   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8746   // non-trivial part is impdef of ESP.
8747   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8748   // mingw-w64.
8749
8750   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
8751     .addExternalSymbol("_alloca")
8752     .addReg(X86::EAX, RegState::Implicit)
8753     .addReg(X86::ESP, RegState::Implicit)
8754     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8755     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8756
8757   MI->eraseFromParent();   // The pseudo instruction is gone now.
8758   return BB;
8759 }
8760
8761 MachineBasicBlock *
8762 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
8763                                       MachineBasicBlock *BB) const {
8764   // This is pretty easy.  We're taking the value that we received from
8765   // our load from the relocation, sticking it in either RDI (x86-64)
8766   // or EAX and doing an indirect call.  The return value will then
8767   // be in the normal return register.
8768   const X86InstrInfo *TII 
8769     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
8770   DebugLoc DL = MI->getDebugLoc();
8771   MachineFunction *F = BB->getParent();
8772   
8773   assert(MI->getOperand(3).isGlobal() && "This should be a global");
8774   
8775   if (Subtarget->is64Bit()) {
8776     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8777                                       TII->get(X86::MOV64rm), X86::RDI)
8778     .addReg(X86::RIP)
8779     .addImm(0).addReg(0)
8780     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8781                       MI->getOperand(3).getTargetFlags())
8782     .addReg(0);
8783     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
8784     addDirectMem(MIB, X86::RDI);
8785   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
8786     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8787                                       TII->get(X86::MOV32rm), X86::EAX)
8788     .addReg(0)
8789     .addImm(0).addReg(0)
8790     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8791                       MI->getOperand(3).getTargetFlags())
8792     .addReg(0);
8793     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
8794     addDirectMem(MIB, X86::EAX);
8795   } else {
8796     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8797                                       TII->get(X86::MOV32rm), X86::EAX)
8798     .addReg(TII->getGlobalBaseReg(F))
8799     .addImm(0).addReg(0)
8800     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8801                       MI->getOperand(3).getTargetFlags())
8802     .addReg(0);
8803     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
8804     addDirectMem(MIB, X86::EAX);
8805   }
8806   
8807   MI->eraseFromParent(); // The pseudo instruction is gone now.
8808   return BB;
8809 }
8810
8811 MachineBasicBlock *
8812 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8813                                                MachineBasicBlock *BB) const {
8814   switch (MI->getOpcode()) {
8815   default: assert(false && "Unexpected instr type to insert");
8816   case X86::MINGW_ALLOCA:
8817     return EmitLoweredMingwAlloca(MI, BB);
8818   case X86::TLSCall_32:
8819   case X86::TLSCall_64:
8820     return EmitLoweredTLSCall(MI, BB);
8821   case X86::CMOV_GR8:
8822   case X86::CMOV_V1I64:
8823   case X86::CMOV_FR32:
8824   case X86::CMOV_FR64:
8825   case X86::CMOV_V4F32:
8826   case X86::CMOV_V2F64:
8827   case X86::CMOV_V2I64:
8828   case X86::CMOV_GR16:
8829   case X86::CMOV_GR32:
8830   case X86::CMOV_RFP32:
8831   case X86::CMOV_RFP64:
8832   case X86::CMOV_RFP80:
8833     return EmitLoweredSelect(MI, BB);
8834
8835   case X86::FP32_TO_INT16_IN_MEM:
8836   case X86::FP32_TO_INT32_IN_MEM:
8837   case X86::FP32_TO_INT64_IN_MEM:
8838   case X86::FP64_TO_INT16_IN_MEM:
8839   case X86::FP64_TO_INT32_IN_MEM:
8840   case X86::FP64_TO_INT64_IN_MEM:
8841   case X86::FP80_TO_INT16_IN_MEM:
8842   case X86::FP80_TO_INT32_IN_MEM:
8843   case X86::FP80_TO_INT64_IN_MEM: {
8844     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8845     DebugLoc DL = MI->getDebugLoc();
8846
8847     // Change the floating point control register to use "round towards zero"
8848     // mode when truncating to an integer value.
8849     MachineFunction *F = BB->getParent();
8850     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8851     addFrameReference(BuildMI(*BB, MI, DL,
8852                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
8853
8854     // Load the old value of the high byte of the control word...
8855     unsigned OldCW =
8856       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8857     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
8858                       CWFrameIdx);
8859
8860     // Set the high part to be round to zero...
8861     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8862       .addImm(0xC7F);
8863
8864     // Reload the modified control word now...
8865     addFrameReference(BuildMI(*BB, MI, DL,
8866                               TII->get(X86::FLDCW16m)), CWFrameIdx);
8867
8868     // Restore the memory image of control word to original value
8869     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8870       .addReg(OldCW);
8871
8872     // Get the X86 opcode to use.
8873     unsigned Opc;
8874     switch (MI->getOpcode()) {
8875     default: llvm_unreachable("illegal opcode!");
8876     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8877     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8878     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8879     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8880     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8881     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8882     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8883     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8884     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8885     }
8886
8887     X86AddressMode AM;
8888     MachineOperand &Op = MI->getOperand(0);
8889     if (Op.isReg()) {
8890       AM.BaseType = X86AddressMode::RegBase;
8891       AM.Base.Reg = Op.getReg();
8892     } else {
8893       AM.BaseType = X86AddressMode::FrameIndexBase;
8894       AM.Base.FrameIndex = Op.getIndex();
8895     }
8896     Op = MI->getOperand(1);
8897     if (Op.isImm())
8898       AM.Scale = Op.getImm();
8899     Op = MI->getOperand(2);
8900     if (Op.isImm())
8901       AM.IndexReg = Op.getImm();
8902     Op = MI->getOperand(3);
8903     if (Op.isGlobal()) {
8904       AM.GV = Op.getGlobal();
8905     } else {
8906       AM.Disp = Op.getImm();
8907     }
8908     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
8909                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
8910
8911     // Reload the original control word now.
8912     addFrameReference(BuildMI(*BB, MI, DL,
8913                               TII->get(X86::FLDCW16m)), CWFrameIdx);
8914
8915     MI->eraseFromParent();   // The pseudo instruction is gone now.
8916     return BB;
8917   }
8918     // String/text processing lowering.
8919   case X86::PCMPISTRM128REG:
8920   case X86::VPCMPISTRM128REG:
8921     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8922   case X86::PCMPISTRM128MEM:
8923   case X86::VPCMPISTRM128MEM:
8924     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8925   case X86::PCMPESTRM128REG:
8926   case X86::VPCMPESTRM128REG:
8927     return EmitPCMP(MI, BB, 5, false /* in mem */);
8928   case X86::PCMPESTRM128MEM:
8929   case X86::VPCMPESTRM128MEM:
8930     return EmitPCMP(MI, BB, 5, true /* in mem */);
8931
8932     // Atomic Lowering.
8933   case X86::ATOMAND32:
8934     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8935                                                X86::AND32ri, X86::MOV32rm,
8936                                                X86::LCMPXCHG32,
8937                                                X86::NOT32r, X86::EAX,
8938                                                X86::GR32RegisterClass);
8939   case X86::ATOMOR32:
8940     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8941                                                X86::OR32ri, X86::MOV32rm,
8942                                                X86::LCMPXCHG32,
8943                                                X86::NOT32r, X86::EAX,
8944                                                X86::GR32RegisterClass);
8945   case X86::ATOMXOR32:
8946     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8947                                                X86::XOR32ri, X86::MOV32rm,
8948                                                X86::LCMPXCHG32,
8949                                                X86::NOT32r, X86::EAX,
8950                                                X86::GR32RegisterClass);
8951   case X86::ATOMNAND32:
8952     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8953                                                X86::AND32ri, X86::MOV32rm,
8954                                                X86::LCMPXCHG32,
8955                                                X86::NOT32r, X86::EAX,
8956                                                X86::GR32RegisterClass, true);
8957   case X86::ATOMMIN32:
8958     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8959   case X86::ATOMMAX32:
8960     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8961   case X86::ATOMUMIN32:
8962     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8963   case X86::ATOMUMAX32:
8964     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8965
8966   case X86::ATOMAND16:
8967     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8968                                                X86::AND16ri, X86::MOV16rm,
8969                                                X86::LCMPXCHG16,
8970                                                X86::NOT16r, X86::AX,
8971                                                X86::GR16RegisterClass);
8972   case X86::ATOMOR16:
8973     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8974                                                X86::OR16ri, X86::MOV16rm,
8975                                                X86::LCMPXCHG16,
8976                                                X86::NOT16r, X86::AX,
8977                                                X86::GR16RegisterClass);
8978   case X86::ATOMXOR16:
8979     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8980                                                X86::XOR16ri, X86::MOV16rm,
8981                                                X86::LCMPXCHG16,
8982                                                X86::NOT16r, X86::AX,
8983                                                X86::GR16RegisterClass);
8984   case X86::ATOMNAND16:
8985     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8986                                                X86::AND16ri, X86::MOV16rm,
8987                                                X86::LCMPXCHG16,
8988                                                X86::NOT16r, X86::AX,
8989                                                X86::GR16RegisterClass, true);
8990   case X86::ATOMMIN16:
8991     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8992   case X86::ATOMMAX16:
8993     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8994   case X86::ATOMUMIN16:
8995     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8996   case X86::ATOMUMAX16:
8997     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8998
8999   case X86::ATOMAND8:
9000     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9001                                                X86::AND8ri, X86::MOV8rm,
9002                                                X86::LCMPXCHG8,
9003                                                X86::NOT8r, X86::AL,
9004                                                X86::GR8RegisterClass);
9005   case X86::ATOMOR8:
9006     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9007                                                X86::OR8ri, X86::MOV8rm,
9008                                                X86::LCMPXCHG8,
9009                                                X86::NOT8r, X86::AL,
9010                                                X86::GR8RegisterClass);
9011   case X86::ATOMXOR8:
9012     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9013                                                X86::XOR8ri, X86::MOV8rm,
9014                                                X86::LCMPXCHG8,
9015                                                X86::NOT8r, X86::AL,
9016                                                X86::GR8RegisterClass);
9017   case X86::ATOMNAND8:
9018     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9019                                                X86::AND8ri, X86::MOV8rm,
9020                                                X86::LCMPXCHG8,
9021                                                X86::NOT8r, X86::AL,
9022                                                X86::GR8RegisterClass, true);
9023   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9024   // This group is for 64-bit host.
9025   case X86::ATOMAND64:
9026     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9027                                                X86::AND64ri32, X86::MOV64rm,
9028                                                X86::LCMPXCHG64,
9029                                                X86::NOT64r, X86::RAX,
9030                                                X86::GR64RegisterClass);
9031   case X86::ATOMOR64:
9032     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9033                                                X86::OR64ri32, X86::MOV64rm,
9034                                                X86::LCMPXCHG64,
9035                                                X86::NOT64r, X86::RAX,
9036                                                X86::GR64RegisterClass);
9037   case X86::ATOMXOR64:
9038     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9039                                                X86::XOR64ri32, X86::MOV64rm,
9040                                                X86::LCMPXCHG64,
9041                                                X86::NOT64r, X86::RAX,
9042                                                X86::GR64RegisterClass);
9043   case X86::ATOMNAND64:
9044     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9045                                                X86::AND64ri32, X86::MOV64rm,
9046                                                X86::LCMPXCHG64,
9047                                                X86::NOT64r, X86::RAX,
9048                                                X86::GR64RegisterClass, true);
9049   case X86::ATOMMIN64:
9050     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9051   case X86::ATOMMAX64:
9052     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9053   case X86::ATOMUMIN64:
9054     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9055   case X86::ATOMUMAX64:
9056     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9057
9058   // This group does 64-bit operations on a 32-bit host.
9059   case X86::ATOMAND6432:
9060     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9061                                                X86::AND32rr, X86::AND32rr,
9062                                                X86::AND32ri, X86::AND32ri,
9063                                                false);
9064   case X86::ATOMOR6432:
9065     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9066                                                X86::OR32rr, X86::OR32rr,
9067                                                X86::OR32ri, X86::OR32ri,
9068                                                false);
9069   case X86::ATOMXOR6432:
9070     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9071                                                X86::XOR32rr, X86::XOR32rr,
9072                                                X86::XOR32ri, X86::XOR32ri,
9073                                                false);
9074   case X86::ATOMNAND6432:
9075     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9076                                                X86::AND32rr, X86::AND32rr,
9077                                                X86::AND32ri, X86::AND32ri,
9078                                                true);
9079   case X86::ATOMADD6432:
9080     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9081                                                X86::ADD32rr, X86::ADC32rr,
9082                                                X86::ADD32ri, X86::ADC32ri,
9083                                                false);
9084   case X86::ATOMSUB6432:
9085     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9086                                                X86::SUB32rr, X86::SBB32rr,
9087                                                X86::SUB32ri, X86::SBB32ri,
9088                                                false);
9089   case X86::ATOMSWAP6432:
9090     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9091                                                X86::MOV32rr, X86::MOV32rr,
9092                                                X86::MOV32ri, X86::MOV32ri,
9093                                                false);
9094   case X86::VASTART_SAVE_XMM_REGS:
9095     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9096   }
9097 }
9098
9099 //===----------------------------------------------------------------------===//
9100 //                           X86 Optimization Hooks
9101 //===----------------------------------------------------------------------===//
9102
9103 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9104                                                        const APInt &Mask,
9105                                                        APInt &KnownZero,
9106                                                        APInt &KnownOne,
9107                                                        const SelectionDAG &DAG,
9108                                                        unsigned Depth) const {
9109   unsigned Opc = Op.getOpcode();
9110   assert((Opc >= ISD::BUILTIN_OP_END ||
9111           Opc == ISD::INTRINSIC_WO_CHAIN ||
9112           Opc == ISD::INTRINSIC_W_CHAIN ||
9113           Opc == ISD::INTRINSIC_VOID) &&
9114          "Should use MaskedValueIsZero if you don't know whether Op"
9115          " is a target node!");
9116
9117   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
9118   switch (Opc) {
9119   default: break;
9120   case X86ISD::ADD:
9121   case X86ISD::SUB:
9122   case X86ISD::SMUL:
9123   case X86ISD::UMUL:
9124   case X86ISD::INC:
9125   case X86ISD::DEC:
9126   case X86ISD::OR:
9127   case X86ISD::XOR:
9128   case X86ISD::AND:
9129     // These nodes' second result is a boolean.
9130     if (Op.getResNo() == 0)
9131       break;
9132     // Fallthrough
9133   case X86ISD::SETCC:
9134     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9135                                        Mask.getBitWidth() - 1);
9136     break;
9137   }
9138 }
9139
9140 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9141 /// node is a GlobalAddress + offset.
9142 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9143                                        const GlobalValue* &GA,
9144                                        int64_t &Offset) const {
9145   if (N->getOpcode() == X86ISD::Wrapper) {
9146     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9147       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9148       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9149       return true;
9150     }
9151   }
9152   return TargetLowering::isGAPlusOffset(N, GA, Offset);
9153 }
9154
9155 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9156 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9157 /// if the load addresses are consecutive, non-overlapping, and in the right
9158 /// order.
9159 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9160                                      const TargetLowering &TLI) {
9161   DebugLoc dl = N->getDebugLoc();
9162   EVT VT = N->getValueType(0);
9163   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9164
9165   if (VT.getSizeInBits() != 128)
9166     return SDValue();
9167
9168   SmallVector<SDValue, 16> Elts;
9169   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9170     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
9171   
9172   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9173 }
9174
9175 /// PerformShuffleCombine - Detect vector gather/scatter index generation
9176 /// and convert it from being a bunch of shuffles and extracts to a simple
9177 /// store and scalar loads to extract the elements.
9178 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
9179                                                 const TargetLowering &TLI) {
9180   SDValue InputVector = N->getOperand(0);
9181
9182   // Only operate on vectors of 4 elements, where the alternative shuffling
9183   // gets to be more expensive.
9184   if (InputVector.getValueType() != MVT::v4i32)
9185     return SDValue();
9186
9187   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
9188   // single use which is a sign-extend or zero-extend, and all elements are
9189   // used.
9190   SmallVector<SDNode *, 4> Uses;
9191   unsigned ExtractedElements = 0;
9192   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
9193        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
9194     if (UI.getUse().getResNo() != InputVector.getResNo())
9195       return SDValue();
9196
9197     SDNode *Extract = *UI;
9198     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9199       return SDValue();
9200
9201     if (Extract->getValueType(0) != MVT::i32)
9202       return SDValue();
9203     if (!Extract->hasOneUse())
9204       return SDValue();
9205     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
9206         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
9207       return SDValue();
9208     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
9209       return SDValue();
9210
9211     // Record which element was extracted.
9212     ExtractedElements |=
9213       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
9214
9215     Uses.push_back(Extract);
9216   }
9217
9218   // If not all the elements were used, this may not be worthwhile.
9219   if (ExtractedElements != 15)
9220     return SDValue();
9221
9222   // Ok, we've now decided to do the transformation.
9223   DebugLoc dl = InputVector.getDebugLoc();
9224
9225   // Store the value to a temporary stack slot.
9226   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
9227   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL,
9228                             0, false, false, 0);
9229
9230   // Replace each use (extract) with a load of the appropriate element.
9231   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
9232        UE = Uses.end(); UI != UE; ++UI) {
9233     SDNode *Extract = *UI;
9234
9235     // Compute the element's address.
9236     SDValue Idx = Extract->getOperand(1);
9237     unsigned EltSize =
9238         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9239     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9240     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9241
9242     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
9243                                      OffsetVal, StackPtr);
9244
9245     // Load the scalar.
9246     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
9247                                      ScalarAddr, NULL, 0, false, false, 0);
9248
9249     // Replace the exact with the load.
9250     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9251   }
9252
9253   // The replacement was made in place; don't return anything.
9254   return SDValue();
9255 }
9256
9257 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9258 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9259                                     const X86Subtarget *Subtarget) {
9260   DebugLoc DL = N->getDebugLoc();
9261   SDValue Cond = N->getOperand(0);
9262   // Get the LHS/RHS of the select.
9263   SDValue LHS = N->getOperand(1);
9264   SDValue RHS = N->getOperand(2);
9265
9266   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9267   // instructions match the semantics of the common C idiom x<y?x:y but not
9268   // x<=y?x:y, because of how they handle negative zero (which can be
9269   // ignored in unsafe-math mode).
9270   if (Subtarget->hasSSE2() &&
9271       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9272       Cond.getOpcode() == ISD::SETCC) {
9273     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9274
9275     unsigned Opcode = 0;
9276     // Check for x CC y ? x : y.
9277     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9278         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9279       switch (CC) {
9280       default: break;
9281       case ISD::SETULT:
9282         // Converting this to a min would handle NaNs incorrectly, and swapping
9283         // the operands would cause it to handle comparisons between positive
9284         // and negative zero incorrectly.
9285         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
9286           if (!UnsafeFPMath &&
9287               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9288             break;
9289           std::swap(LHS, RHS);
9290         }
9291         Opcode = X86ISD::FMIN;
9292         break;
9293       case ISD::SETOLE:
9294         // Converting this to a min would handle comparisons between positive
9295         // and negative zero incorrectly.
9296         if (!UnsafeFPMath &&
9297             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9298           break;
9299         Opcode = X86ISD::FMIN;
9300         break;
9301       case ISD::SETULE:
9302         // Converting this to a min would handle both negative zeros and NaNs
9303         // incorrectly, but we can swap the operands to fix both.
9304         std::swap(LHS, RHS);
9305       case ISD::SETOLT:
9306       case ISD::SETLT:
9307       case ISD::SETLE:
9308         Opcode = X86ISD::FMIN;
9309         break;
9310
9311       case ISD::SETOGE:
9312         // Converting this to a max would handle comparisons between positive
9313         // and negative zero incorrectly.
9314         if (!UnsafeFPMath &&
9315             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9316           break;
9317         Opcode = X86ISD::FMAX;
9318         break;
9319       case ISD::SETUGT:
9320         // Converting this to a max would handle NaNs incorrectly, and swapping
9321         // the operands would cause it to handle comparisons between positive
9322         // and negative zero incorrectly.
9323         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
9324           if (!UnsafeFPMath &&
9325               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9326             break;
9327           std::swap(LHS, RHS);
9328         }
9329         Opcode = X86ISD::FMAX;
9330         break;
9331       case ISD::SETUGE:
9332         // Converting this to a max would handle both negative zeros and NaNs
9333         // incorrectly, but we can swap the operands to fix both.
9334         std::swap(LHS, RHS);
9335       case ISD::SETOGT:
9336       case ISD::SETGT:
9337       case ISD::SETGE:
9338         Opcode = X86ISD::FMAX;
9339         break;
9340       }
9341     // Check for x CC y ? y : x -- a min/max with reversed arms.
9342     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9343                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9344       switch (CC) {
9345       default: break;
9346       case ISD::SETOGE:
9347         // Converting this to a min would handle comparisons between positive
9348         // and negative zero incorrectly, and swapping the operands would
9349         // cause it to handle NaNs incorrectly.
9350         if (!UnsafeFPMath &&
9351             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9352           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9353             break;
9354           std::swap(LHS, RHS);
9355         }
9356         Opcode = X86ISD::FMIN;
9357         break;
9358       case ISD::SETUGT:
9359         // Converting this to a min would handle NaNs incorrectly.
9360         if (!UnsafeFPMath &&
9361             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9362           break;
9363         Opcode = X86ISD::FMIN;
9364         break;
9365       case ISD::SETUGE:
9366         // Converting this to a min would handle both negative zeros and NaNs
9367         // incorrectly, but we can swap the operands to fix both.
9368         std::swap(LHS, RHS);
9369       case ISD::SETOGT:
9370       case ISD::SETGT:
9371       case ISD::SETGE:
9372         Opcode = X86ISD::FMIN;
9373         break;
9374
9375       case ISD::SETULT:
9376         // Converting this to a max would handle NaNs incorrectly.
9377         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9378           break;
9379         Opcode = X86ISD::FMAX;
9380         break;
9381       case ISD::SETOLE:
9382         // Converting this to a max would handle comparisons between positive
9383         // and negative zero incorrectly, and swapping the operands would
9384         // cause it to handle NaNs incorrectly.
9385         if (!UnsafeFPMath &&
9386             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9387           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9388             break;
9389           std::swap(LHS, RHS);
9390         }
9391         Opcode = X86ISD::FMAX;
9392         break;
9393       case ISD::SETULE:
9394         // Converting this to a max would handle both negative zeros and NaNs
9395         // incorrectly, but we can swap the operands to fix both.
9396         std::swap(LHS, RHS);
9397       case ISD::SETOLT:
9398       case ISD::SETLT:
9399       case ISD::SETLE:
9400         Opcode = X86ISD::FMAX;
9401         break;
9402       }
9403     }
9404
9405     if (Opcode)
9406       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9407   }
9408
9409   // If this is a select between two integer constants, try to do some
9410   // optimizations.
9411   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9412     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9413       // Don't do this for crazy integer types.
9414       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9415         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9416         // so that TrueC (the true value) is larger than FalseC.
9417         bool NeedsCondInvert = false;
9418
9419         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9420             // Efficiently invertible.
9421             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9422              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9423               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9424           NeedsCondInvert = true;
9425           std::swap(TrueC, FalseC);
9426         }
9427
9428         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9429         if (FalseC->getAPIntValue() == 0 &&
9430             TrueC->getAPIntValue().isPowerOf2()) {
9431           if (NeedsCondInvert) // Invert the condition if needed.
9432             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9433                                DAG.getConstant(1, Cond.getValueType()));
9434
9435           // Zero extend the condition if needed.
9436           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9437
9438           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9439           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9440                              DAG.getConstant(ShAmt, MVT::i8));
9441         }
9442
9443         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9444         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9445           if (NeedsCondInvert) // Invert the condition if needed.
9446             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9447                                DAG.getConstant(1, Cond.getValueType()));
9448
9449           // Zero extend the condition if needed.
9450           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9451                              FalseC->getValueType(0), Cond);
9452           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9453                              SDValue(FalseC, 0));
9454         }
9455
9456         // Optimize cases that will turn into an LEA instruction.  This requires
9457         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9458         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9459           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9460           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9461
9462           bool isFastMultiplier = false;
9463           if (Diff < 10) {
9464             switch ((unsigned char)Diff) {
9465               default: break;
9466               case 1:  // result = add base, cond
9467               case 2:  // result = lea base(    , cond*2)
9468               case 3:  // result = lea base(cond, cond*2)
9469               case 4:  // result = lea base(    , cond*4)
9470               case 5:  // result = lea base(cond, cond*4)
9471               case 8:  // result = lea base(    , cond*8)
9472               case 9:  // result = lea base(cond, cond*8)
9473                 isFastMultiplier = true;
9474                 break;
9475             }
9476           }
9477
9478           if (isFastMultiplier) {
9479             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9480             if (NeedsCondInvert) // Invert the condition if needed.
9481               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9482                                  DAG.getConstant(1, Cond.getValueType()));
9483
9484             // Zero extend the condition if needed.
9485             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9486                                Cond);
9487             // Scale the condition by the difference.
9488             if (Diff != 1)
9489               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9490                                  DAG.getConstant(Diff, Cond.getValueType()));
9491
9492             // Add the base if non-zero.
9493             if (FalseC->getAPIntValue() != 0)
9494               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9495                                  SDValue(FalseC, 0));
9496             return Cond;
9497           }
9498         }
9499       }
9500   }
9501
9502   return SDValue();
9503 }
9504
9505 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9506 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9507                                   TargetLowering::DAGCombinerInfo &DCI) {
9508   DebugLoc DL = N->getDebugLoc();
9509
9510   // If the flag operand isn't dead, don't touch this CMOV.
9511   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9512     return SDValue();
9513
9514   // If this is a select between two integer constants, try to do some
9515   // optimizations.  Note that the operands are ordered the opposite of SELECT
9516   // operands.
9517   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9518     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9519       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9520       // larger than FalseC (the false value).
9521       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9522
9523       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9524         CC = X86::GetOppositeBranchCondition(CC);
9525         std::swap(TrueC, FalseC);
9526       }
9527
9528       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9529       // This is efficient for any integer data type (including i8/i16) and
9530       // shift amount.
9531       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9532         SDValue Cond = N->getOperand(3);
9533         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9534                            DAG.getConstant(CC, MVT::i8), Cond);
9535
9536         // Zero extend the condition if needed.
9537         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9538
9539         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9540         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9541                            DAG.getConstant(ShAmt, MVT::i8));
9542         if (N->getNumValues() == 2)  // Dead flag value?
9543           return DCI.CombineTo(N, Cond, SDValue());
9544         return Cond;
9545       }
9546
9547       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9548       // for any integer data type, including i8/i16.
9549       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9550         SDValue Cond = N->getOperand(3);
9551         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9552                            DAG.getConstant(CC, MVT::i8), Cond);
9553
9554         // Zero extend the condition if needed.
9555         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9556                            FalseC->getValueType(0), Cond);
9557         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9558                            SDValue(FalseC, 0));
9559
9560         if (N->getNumValues() == 2)  // Dead flag value?
9561           return DCI.CombineTo(N, Cond, SDValue());
9562         return Cond;
9563       }
9564
9565       // Optimize cases that will turn into an LEA instruction.  This requires
9566       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9567       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9568         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9569         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9570
9571         bool isFastMultiplier = false;
9572         if (Diff < 10) {
9573           switch ((unsigned char)Diff) {
9574           default: break;
9575           case 1:  // result = add base, cond
9576           case 2:  // result = lea base(    , cond*2)
9577           case 3:  // result = lea base(cond, cond*2)
9578           case 4:  // result = lea base(    , cond*4)
9579           case 5:  // result = lea base(cond, cond*4)
9580           case 8:  // result = lea base(    , cond*8)
9581           case 9:  // result = lea base(cond, cond*8)
9582             isFastMultiplier = true;
9583             break;
9584           }
9585         }
9586
9587         if (isFastMultiplier) {
9588           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9589           SDValue Cond = N->getOperand(3);
9590           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9591                              DAG.getConstant(CC, MVT::i8), Cond);
9592           // Zero extend the condition if needed.
9593           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9594                              Cond);
9595           // Scale the condition by the difference.
9596           if (Diff != 1)
9597             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9598                                DAG.getConstant(Diff, Cond.getValueType()));
9599
9600           // Add the base if non-zero.
9601           if (FalseC->getAPIntValue() != 0)
9602             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9603                                SDValue(FalseC, 0));
9604           if (N->getNumValues() == 2)  // Dead flag value?
9605             return DCI.CombineTo(N, Cond, SDValue());
9606           return Cond;
9607         }
9608       }
9609     }
9610   }
9611   return SDValue();
9612 }
9613
9614
9615 /// PerformMulCombine - Optimize a single multiply with constant into two
9616 /// in order to implement it with two cheaper instructions, e.g.
9617 /// LEA + SHL, LEA + LEA.
9618 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9619                                  TargetLowering::DAGCombinerInfo &DCI) {
9620   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9621     return SDValue();
9622
9623   EVT VT = N->getValueType(0);
9624   if (VT != MVT::i64)
9625     return SDValue();
9626
9627   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9628   if (!C)
9629     return SDValue();
9630   uint64_t MulAmt = C->getZExtValue();
9631   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9632     return SDValue();
9633
9634   uint64_t MulAmt1 = 0;
9635   uint64_t MulAmt2 = 0;
9636   if ((MulAmt % 9) == 0) {
9637     MulAmt1 = 9;
9638     MulAmt2 = MulAmt / 9;
9639   } else if ((MulAmt % 5) == 0) {
9640     MulAmt1 = 5;
9641     MulAmt2 = MulAmt / 5;
9642   } else if ((MulAmt % 3) == 0) {
9643     MulAmt1 = 3;
9644     MulAmt2 = MulAmt / 3;
9645   }
9646   if (MulAmt2 &&
9647       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9648     DebugLoc DL = N->getDebugLoc();
9649
9650     if (isPowerOf2_64(MulAmt2) &&
9651         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9652       // If second multiplifer is pow2, issue it first. We want the multiply by
9653       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9654       // is an add.
9655       std::swap(MulAmt1, MulAmt2);
9656
9657     SDValue NewMul;
9658     if (isPowerOf2_64(MulAmt1))
9659       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9660                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9661     else
9662       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9663                            DAG.getConstant(MulAmt1, VT));
9664
9665     if (isPowerOf2_64(MulAmt2))
9666       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9667                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9668     else
9669       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9670                            DAG.getConstant(MulAmt2, VT));
9671
9672     // Do not add new nodes to DAG combiner worklist.
9673     DCI.CombineTo(N, NewMul, false);
9674   }
9675   return SDValue();
9676 }
9677
9678 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9679   SDValue N0 = N->getOperand(0);
9680   SDValue N1 = N->getOperand(1);
9681   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9682   EVT VT = N0.getValueType();
9683
9684   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9685   // since the result of setcc_c is all zero's or all ones.
9686   if (N1C && N0.getOpcode() == ISD::AND &&
9687       N0.getOperand(1).getOpcode() == ISD::Constant) {
9688     SDValue N00 = N0.getOperand(0);
9689     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9690         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9691           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9692          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9693       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9694       APInt ShAmt = N1C->getAPIntValue();
9695       Mask = Mask.shl(ShAmt);
9696       if (Mask != 0)
9697         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9698                            N00, DAG.getConstant(Mask, VT));
9699     }
9700   }
9701
9702   return SDValue();
9703 }
9704
9705 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9706 ///                       when possible.
9707 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9708                                    const X86Subtarget *Subtarget) {
9709   EVT VT = N->getValueType(0);
9710   if (!VT.isVector() && VT.isInteger() &&
9711       N->getOpcode() == ISD::SHL)
9712     return PerformSHLCombine(N, DAG);
9713
9714   // On X86 with SSE2 support, we can transform this to a vector shift if
9715   // all elements are shifted by the same amount.  We can't do this in legalize
9716   // because the a constant vector is typically transformed to a constant pool
9717   // so we have no knowledge of the shift amount.
9718   if (!Subtarget->hasSSE2())
9719     return SDValue();
9720
9721   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9722     return SDValue();
9723
9724   SDValue ShAmtOp = N->getOperand(1);
9725   EVT EltVT = VT.getVectorElementType();
9726   DebugLoc DL = N->getDebugLoc();
9727   SDValue BaseShAmt = SDValue();
9728   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9729     unsigned NumElts = VT.getVectorNumElements();
9730     unsigned i = 0;
9731     for (; i != NumElts; ++i) {
9732       SDValue Arg = ShAmtOp.getOperand(i);
9733       if (Arg.getOpcode() == ISD::UNDEF) continue;
9734       BaseShAmt = Arg;
9735       break;
9736     }
9737     for (; i != NumElts; ++i) {
9738       SDValue Arg = ShAmtOp.getOperand(i);
9739       if (Arg.getOpcode() == ISD::UNDEF) continue;
9740       if (Arg != BaseShAmt) {
9741         return SDValue();
9742       }
9743     }
9744   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9745              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9746     SDValue InVec = ShAmtOp.getOperand(0);
9747     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9748       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9749       unsigned i = 0;
9750       for (; i != NumElts; ++i) {
9751         SDValue Arg = InVec.getOperand(i);
9752         if (Arg.getOpcode() == ISD::UNDEF) continue;
9753         BaseShAmt = Arg;
9754         break;
9755       }
9756     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9757        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9758          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9759          if (C->getZExtValue() == SplatIdx)
9760            BaseShAmt = InVec.getOperand(1);
9761        }
9762     }
9763     if (BaseShAmt.getNode() == 0)
9764       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9765                               DAG.getIntPtrConstant(0));
9766   } else
9767     return SDValue();
9768
9769   // The shift amount is an i32.
9770   if (EltVT.bitsGT(MVT::i32))
9771     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9772   else if (EltVT.bitsLT(MVT::i32))
9773     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9774
9775   // The shift amount is identical so we can do a vector shift.
9776   SDValue  ValOp = N->getOperand(0);
9777   switch (N->getOpcode()) {
9778   default:
9779     llvm_unreachable("Unknown shift opcode!");
9780     break;
9781   case ISD::SHL:
9782     if (VT == MVT::v2i64)
9783       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9784                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9785                          ValOp, BaseShAmt);
9786     if (VT == MVT::v4i32)
9787       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9788                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9789                          ValOp, BaseShAmt);
9790     if (VT == MVT::v8i16)
9791       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9792                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9793                          ValOp, BaseShAmt);
9794     break;
9795   case ISD::SRA:
9796     if (VT == MVT::v4i32)
9797       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9798                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9799                          ValOp, BaseShAmt);
9800     if (VT == MVT::v8i16)
9801       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9802                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9803                          ValOp, BaseShAmt);
9804     break;
9805   case ISD::SRL:
9806     if (VT == MVT::v2i64)
9807       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9808                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9809                          ValOp, BaseShAmt);
9810     if (VT == MVT::v4i32)
9811       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9812                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9813                          ValOp, BaseShAmt);
9814     if (VT ==  MVT::v8i16)
9815       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9816                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9817                          ValOp, BaseShAmt);
9818     break;
9819   }
9820   return SDValue();
9821 }
9822
9823 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9824                                 TargetLowering::DAGCombinerInfo &DCI,
9825                                 const X86Subtarget *Subtarget) {
9826   if (DCI.isBeforeLegalizeOps())
9827     return SDValue();
9828
9829   EVT VT = N->getValueType(0);
9830   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9831     return SDValue();
9832
9833   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9834   SDValue N0 = N->getOperand(0);
9835   SDValue N1 = N->getOperand(1);
9836   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9837     std::swap(N0, N1);
9838   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9839     return SDValue();
9840   if (!N0.hasOneUse() || !N1.hasOneUse())
9841     return SDValue();
9842
9843   SDValue ShAmt0 = N0.getOperand(1);
9844   if (ShAmt0.getValueType() != MVT::i8)
9845     return SDValue();
9846   SDValue ShAmt1 = N1.getOperand(1);
9847   if (ShAmt1.getValueType() != MVT::i8)
9848     return SDValue();
9849   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9850     ShAmt0 = ShAmt0.getOperand(0);
9851   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9852     ShAmt1 = ShAmt1.getOperand(0);
9853
9854   DebugLoc DL = N->getDebugLoc();
9855   unsigned Opc = X86ISD::SHLD;
9856   SDValue Op0 = N0.getOperand(0);
9857   SDValue Op1 = N1.getOperand(0);
9858   if (ShAmt0.getOpcode() == ISD::SUB) {
9859     Opc = X86ISD::SHRD;
9860     std::swap(Op0, Op1);
9861     std::swap(ShAmt0, ShAmt1);
9862   }
9863
9864   unsigned Bits = VT.getSizeInBits();
9865   if (ShAmt1.getOpcode() == ISD::SUB) {
9866     SDValue Sum = ShAmt1.getOperand(0);
9867     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9868       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
9869       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
9870         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
9871       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
9872         return DAG.getNode(Opc, DL, VT,
9873                            Op0, Op1,
9874                            DAG.getNode(ISD::TRUNCATE, DL,
9875                                        MVT::i8, ShAmt0));
9876     }
9877   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9878     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9879     if (ShAmt0C &&
9880         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9881       return DAG.getNode(Opc, DL, VT,
9882                          N0.getOperand(0), N1.getOperand(0),
9883                          DAG.getNode(ISD::TRUNCATE, DL,
9884                                        MVT::i8, ShAmt0));
9885   }
9886
9887   return SDValue();
9888 }
9889
9890 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9891 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9892                                    const X86Subtarget *Subtarget) {
9893   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9894   // the FP state in cases where an emms may be missing.
9895   // A preferable solution to the general problem is to figure out the right
9896   // places to insert EMMS.  This qualifies as a quick hack.
9897
9898   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9899   StoreSDNode *St = cast<StoreSDNode>(N);
9900   EVT VT = St->getValue().getValueType();
9901   if (VT.getSizeInBits() != 64)
9902     return SDValue();
9903
9904   const Function *F = DAG.getMachineFunction().getFunction();
9905   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9906   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9907     && Subtarget->hasSSE2();
9908   if ((VT.isVector() ||
9909        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9910       isa<LoadSDNode>(St->getValue()) &&
9911       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9912       St->getChain().hasOneUse() && !St->isVolatile()) {
9913     SDNode* LdVal = St->getValue().getNode();
9914     LoadSDNode *Ld = 0;
9915     int TokenFactorIndex = -1;
9916     SmallVector<SDValue, 8> Ops;
9917     SDNode* ChainVal = St->getChain().getNode();
9918     // Must be a store of a load.  We currently handle two cases:  the load
9919     // is a direct child, and it's under an intervening TokenFactor.  It is
9920     // possible to dig deeper under nested TokenFactors.
9921     if (ChainVal == LdVal)
9922       Ld = cast<LoadSDNode>(St->getChain());
9923     else if (St->getValue().hasOneUse() &&
9924              ChainVal->getOpcode() == ISD::TokenFactor) {
9925       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9926         if (ChainVal->getOperand(i).getNode() == LdVal) {
9927           TokenFactorIndex = i;
9928           Ld = cast<LoadSDNode>(St->getValue());
9929         } else
9930           Ops.push_back(ChainVal->getOperand(i));
9931       }
9932     }
9933
9934     if (!Ld || !ISD::isNormalLoad(Ld))
9935       return SDValue();
9936
9937     // If this is not the MMX case, i.e. we are just turning i64 load/store
9938     // into f64 load/store, avoid the transformation if there are multiple
9939     // uses of the loaded value.
9940     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9941       return SDValue();
9942
9943     DebugLoc LdDL = Ld->getDebugLoc();
9944     DebugLoc StDL = N->getDebugLoc();
9945     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9946     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9947     // pair instead.
9948     if (Subtarget->is64Bit() || F64IsLegal) {
9949       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9950       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9951                                   Ld->getBasePtr(), Ld->getSrcValue(),
9952                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9953                                   Ld->isNonTemporal(), Ld->getAlignment());
9954       SDValue NewChain = NewLd.getValue(1);
9955       if (TokenFactorIndex != -1) {
9956         Ops.push_back(NewChain);
9957         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9958                                Ops.size());
9959       }
9960       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9961                           St->getSrcValue(), St->getSrcValueOffset(),
9962                           St->isVolatile(), St->isNonTemporal(),
9963                           St->getAlignment());
9964     }
9965
9966     // Otherwise, lower to two pairs of 32-bit loads / stores.
9967     SDValue LoAddr = Ld->getBasePtr();
9968     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9969                                  DAG.getConstant(4, MVT::i32));
9970
9971     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9972                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9973                                Ld->isVolatile(), Ld->isNonTemporal(),
9974                                Ld->getAlignment());
9975     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9976                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9977                                Ld->isVolatile(), Ld->isNonTemporal(),
9978                                MinAlign(Ld->getAlignment(), 4));
9979
9980     SDValue NewChain = LoLd.getValue(1);
9981     if (TokenFactorIndex != -1) {
9982       Ops.push_back(LoLd);
9983       Ops.push_back(HiLd);
9984       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9985                              Ops.size());
9986     }
9987
9988     LoAddr = St->getBasePtr();
9989     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9990                          DAG.getConstant(4, MVT::i32));
9991
9992     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9993                                 St->getSrcValue(), St->getSrcValueOffset(),
9994                                 St->isVolatile(), St->isNonTemporal(),
9995                                 St->getAlignment());
9996     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9997                                 St->getSrcValue(),
9998                                 St->getSrcValueOffset() + 4,
9999                                 St->isVolatile(),
10000                                 St->isNonTemporal(),
10001                                 MinAlign(St->getAlignment(), 4));
10002     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10003   }
10004   return SDValue();
10005 }
10006
10007 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10008 /// X86ISD::FXOR nodes.
10009 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10010   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10011   // F[X]OR(0.0, x) -> x
10012   // F[X]OR(x, 0.0) -> x
10013   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10014     if (C->getValueAPF().isPosZero())
10015       return N->getOperand(1);
10016   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10017     if (C->getValueAPF().isPosZero())
10018       return N->getOperand(0);
10019   return SDValue();
10020 }
10021
10022 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10023 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10024   // FAND(0.0, x) -> 0.0
10025   // FAND(x, 0.0) -> 0.0
10026   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10027     if (C->getValueAPF().isPosZero())
10028       return N->getOperand(0);
10029   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10030     if (C->getValueAPF().isPosZero())
10031       return N->getOperand(1);
10032   return SDValue();
10033 }
10034
10035 static SDValue PerformBTCombine(SDNode *N,
10036                                 SelectionDAG &DAG,
10037                                 TargetLowering::DAGCombinerInfo &DCI) {
10038   // BT ignores high bits in the bit index operand.
10039   SDValue Op1 = N->getOperand(1);
10040   if (Op1.hasOneUse()) {
10041     unsigned BitWidth = Op1.getValueSizeInBits();
10042     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10043     APInt KnownZero, KnownOne;
10044     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10045                                           !DCI.isBeforeLegalizeOps());
10046     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10047     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10048         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10049       DCI.CommitTargetLoweringOpt(TLO);
10050   }
10051   return SDValue();
10052 }
10053
10054 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10055   SDValue Op = N->getOperand(0);
10056   if (Op.getOpcode() == ISD::BIT_CONVERT)
10057     Op = Op.getOperand(0);
10058   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10059   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10060       VT.getVectorElementType().getSizeInBits() ==
10061       OpVT.getVectorElementType().getSizeInBits()) {
10062     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10063   }
10064   return SDValue();
10065 }
10066
10067 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10068   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
10069   //           (and (i32 x86isd::setcc_carry), 1)
10070   // This eliminates the zext. This transformation is necessary because
10071   // ISD::SETCC is always legalized to i8.
10072   DebugLoc dl = N->getDebugLoc();
10073   SDValue N0 = N->getOperand(0);
10074   EVT VT = N->getValueType(0);
10075   if (N0.getOpcode() == ISD::AND &&
10076       N0.hasOneUse() &&
10077       N0.getOperand(0).hasOneUse()) {
10078     SDValue N00 = N0.getOperand(0);
10079     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10080       return SDValue();
10081     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10082     if (!C || C->getZExtValue() != 1)
10083       return SDValue();
10084     return DAG.getNode(ISD::AND, dl, VT,
10085                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10086                                    N00.getOperand(0), N00.getOperand(1)),
10087                        DAG.getConstant(1, VT));
10088   }
10089
10090   return SDValue();
10091 }
10092
10093 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10094                                              DAGCombinerInfo &DCI) const {
10095   SelectionDAG &DAG = DCI.DAG;
10096   switch (N->getOpcode()) {
10097   default: break;
10098   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10099   case ISD::EXTRACT_VECTOR_ELT:
10100                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10101   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
10102   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
10103   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
10104   case ISD::SHL:
10105   case ISD::SRA:
10106   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
10107   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
10108   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
10109   case X86ISD::FXOR:
10110   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
10111   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
10112   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
10113   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
10114   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
10115   }
10116
10117   return SDValue();
10118 }
10119
10120 /// isTypeDesirableForOp - Return true if the target has native support for
10121 /// the specified value type and it is 'desirable' to use the type for the
10122 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10123 /// instruction encodings are longer and some i16 instructions are slow.
10124 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10125   if (!isTypeLegal(VT))
10126     return false;
10127   if (VT != MVT::i16)
10128     return true;
10129
10130   switch (Opc) {
10131   default:
10132     return true;
10133   case ISD::LOAD:
10134   case ISD::SIGN_EXTEND:
10135   case ISD::ZERO_EXTEND:
10136   case ISD::ANY_EXTEND:
10137   case ISD::SHL:
10138   case ISD::SRL:
10139   case ISD::SUB:
10140   case ISD::ADD:
10141   case ISD::MUL:
10142   case ISD::AND:
10143   case ISD::OR:
10144   case ISD::XOR:
10145     return false;
10146   }
10147 }
10148
10149 static bool MayFoldLoad(SDValue Op) {
10150   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
10151 }
10152
10153 static bool MayFoldIntoStore(SDValue Op) {
10154   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
10155 }
10156
10157 /// IsDesirableToPromoteOp - This method query the target whether it is
10158 /// beneficial for dag combiner to promote the specified node. If true, it
10159 /// should return the desired promotion type by reference.
10160 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10161   EVT VT = Op.getValueType();
10162   if (VT != MVT::i16)
10163     return false;
10164
10165   bool Promote = false;
10166   bool Commute = false;
10167   switch (Op.getOpcode()) {
10168   default: break;
10169   case ISD::LOAD: {
10170     LoadSDNode *LD = cast<LoadSDNode>(Op);
10171     // If the non-extending load has a single use and it's not live out, then it
10172     // might be folded.
10173     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
10174                                                      Op.hasOneUse()*/) {
10175       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10176              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
10177         // The only case where we'd want to promote LOAD (rather then it being
10178         // promoted as an operand is when it's only use is liveout.
10179         if (UI->getOpcode() != ISD::CopyToReg)
10180           return false;
10181       }
10182     }
10183     Promote = true;
10184     break;
10185   }
10186   case ISD::SIGN_EXTEND:
10187   case ISD::ZERO_EXTEND:
10188   case ISD::ANY_EXTEND:
10189     Promote = true;
10190     break;
10191   case ISD::SHL:
10192   case ISD::SRL: {
10193     SDValue N0 = Op.getOperand(0);
10194     // Look out for (store (shl (load), x)).
10195     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
10196       return false;
10197     Promote = true;
10198     break;
10199   }
10200   case ISD::ADD:
10201   case ISD::MUL:
10202   case ISD::AND:
10203   case ISD::OR:
10204   case ISD::XOR:
10205     Commute = true;
10206     // fallthrough
10207   case ISD::SUB: {
10208     SDValue N0 = Op.getOperand(0);
10209     SDValue N1 = Op.getOperand(1);
10210     if (!Commute && MayFoldLoad(N1))
10211       return false;
10212     // Avoid disabling potential load folding opportunities.
10213     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
10214       return false;
10215     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
10216       return false;
10217     Promote = true;
10218   }
10219   }
10220
10221   PVT = MVT::i32;
10222   return Promote;
10223 }
10224
10225 //===----------------------------------------------------------------------===//
10226 //                           X86 Inline Assembly Support
10227 //===----------------------------------------------------------------------===//
10228
10229 static bool LowerToBSwap(CallInst *CI) {
10230   // FIXME: this should verify that we are targetting a 486 or better.  If not,
10231   // we will turn this bswap into something that will be lowered to logical ops
10232   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
10233   // so don't worry about this.
10234
10235   // Verify this is a simple bswap.
10236   if (CI->getNumArgOperands() != 1 ||
10237       CI->getType() != CI->getArgOperand(0)->getType() ||
10238       !CI->getType()->isIntegerTy())
10239     return false;
10240
10241   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10242   if (!Ty || Ty->getBitWidth() % 16 != 0)
10243     return false;
10244
10245   // Okay, we can do this xform, do so now.
10246   const Type *Tys[] = { Ty };
10247   Module *M = CI->getParent()->getParent()->getParent();
10248   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10249
10250   Value *Op = CI->getArgOperand(0);
10251   Op = CallInst::Create(Int, Op, CI->getName(), CI);
10252
10253   CI->replaceAllUsesWith(Op);
10254   CI->eraseFromParent();
10255   return true;
10256 }
10257
10258 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10259   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10260   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10261
10262   std::string AsmStr = IA->getAsmString();
10263
10264   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10265   SmallVector<StringRef, 4> AsmPieces;
10266   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
10267
10268   switch (AsmPieces.size()) {
10269   default: return false;
10270   case 1:
10271     AsmStr = AsmPieces[0];
10272     AsmPieces.clear();
10273     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
10274
10275     // bswap $0
10276     if (AsmPieces.size() == 2 &&
10277         (AsmPieces[0] == "bswap" ||
10278          AsmPieces[0] == "bswapq" ||
10279          AsmPieces[0] == "bswapl") &&
10280         (AsmPieces[1] == "$0" ||
10281          AsmPieces[1] == "${0:q}")) {
10282       // No need to check constraints, nothing other than the equivalent of
10283       // "=r,0" would be valid here.
10284       return LowerToBSwap(CI);
10285     }
10286     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
10287     if (CI->getType()->isIntegerTy(16) &&
10288         AsmPieces.size() == 3 &&
10289         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10290         AsmPieces[1] == "$$8," &&
10291         AsmPieces[2] == "${0:w}" &&
10292         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10293       AsmPieces.clear();
10294       const std::string &Constraints = IA->getConstraintString();
10295       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10296       std::sort(AsmPieces.begin(), AsmPieces.end());
10297       if (AsmPieces.size() == 4 &&
10298           AsmPieces[0] == "~{cc}" &&
10299           AsmPieces[1] == "~{dirflag}" &&
10300           AsmPieces[2] == "~{flags}" &&
10301           AsmPieces[3] == "~{fpsr}") {
10302         return LowerToBSwap(CI);
10303       }
10304     }
10305     break;
10306   case 3:
10307     if (CI->getType()->isIntegerTy(64) &&
10308         Constraints.size() >= 2 &&
10309         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10310         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10311       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
10312       SmallVector<StringRef, 4> Words;
10313       SplitString(AsmPieces[0], Words, " \t");
10314       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10315         Words.clear();
10316         SplitString(AsmPieces[1], Words, " \t");
10317         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10318           Words.clear();
10319           SplitString(AsmPieces[2], Words, " \t,");
10320           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10321               Words[2] == "%edx") {
10322             return LowerToBSwap(CI);
10323           }
10324         }
10325       }
10326     }
10327     break;
10328   }
10329   return false;
10330 }
10331
10332
10333
10334 /// getConstraintType - Given a constraint letter, return the type of
10335 /// constraint it is for this target.
10336 X86TargetLowering::ConstraintType
10337 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10338   if (Constraint.size() == 1) {
10339     switch (Constraint[0]) {
10340     case 'A':
10341       return C_Register;
10342     case 'f':
10343     case 'r':
10344     case 'R':
10345     case 'l':
10346     case 'q':
10347     case 'Q':
10348     case 'x':
10349     case 'y':
10350     case 'Y':
10351       return C_RegisterClass;
10352     case 'e':
10353     case 'Z':
10354       return C_Other;
10355     default:
10356       break;
10357     }
10358   }
10359   return TargetLowering::getConstraintType(Constraint);
10360 }
10361
10362 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10363 /// with another that has more specific requirements based on the type of the
10364 /// corresponding operand.
10365 const char *X86TargetLowering::
10366 LowerXConstraint(EVT ConstraintVT) const {
10367   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10368   // 'f' like normal targets.
10369   if (ConstraintVT.isFloatingPoint()) {
10370     if (Subtarget->hasSSE2())
10371       return "Y";
10372     if (Subtarget->hasSSE1())
10373       return "x";
10374   }
10375
10376   return TargetLowering::LowerXConstraint(ConstraintVT);
10377 }
10378
10379 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10380 /// vector.  If it is invalid, don't add anything to Ops.
10381 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10382                                                      char Constraint,
10383                                                      std::vector<SDValue>&Ops,
10384                                                      SelectionDAG &DAG) const {
10385   SDValue Result(0, 0);
10386
10387   switch (Constraint) {
10388   default: break;
10389   case 'I':
10390     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10391       if (C->getZExtValue() <= 31) {
10392         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10393         break;
10394       }
10395     }
10396     return;
10397   case 'J':
10398     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10399       if (C->getZExtValue() <= 63) {
10400         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10401         break;
10402       }
10403     }
10404     return;
10405   case 'K':
10406     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10407       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10408         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10409         break;
10410       }
10411     }
10412     return;
10413   case 'N':
10414     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10415       if (C->getZExtValue() <= 255) {
10416         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10417         break;
10418       }
10419     }
10420     return;
10421   case 'e': {
10422     // 32-bit signed value
10423     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10424       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10425                                            C->getSExtValue())) {
10426         // Widen to 64 bits here to get it sign extended.
10427         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10428         break;
10429       }
10430     // FIXME gcc accepts some relocatable values here too, but only in certain
10431     // memory models; it's complicated.
10432     }
10433     return;
10434   }
10435   case 'Z': {
10436     // 32-bit unsigned value
10437     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10438       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10439                                            C->getZExtValue())) {
10440         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10441         break;
10442       }
10443     }
10444     // FIXME gcc accepts some relocatable values here too, but only in certain
10445     // memory models; it's complicated.
10446     return;
10447   }
10448   case 'i': {
10449     // Literal immediates are always ok.
10450     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10451       // Widen to 64 bits here to get it sign extended.
10452       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10453       break;
10454     }
10455
10456     // In any sort of PIC mode addresses need to be computed at runtime by
10457     // adding in a register or some sort of table lookup.  These can't
10458     // be used as immediates.
10459     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
10460       return;
10461
10462     // If we are in non-pic codegen mode, we allow the address of a global (with
10463     // an optional displacement) to be used with 'i'.
10464     GlobalAddressSDNode *GA = 0;
10465     int64_t Offset = 0;
10466
10467     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10468     while (1) {
10469       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10470         Offset += GA->getOffset();
10471         break;
10472       } else if (Op.getOpcode() == ISD::ADD) {
10473         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10474           Offset += C->getZExtValue();
10475           Op = Op.getOperand(0);
10476           continue;
10477         }
10478       } else if (Op.getOpcode() == ISD::SUB) {
10479         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10480           Offset += -C->getZExtValue();
10481           Op = Op.getOperand(0);
10482           continue;
10483         }
10484       }
10485
10486       // Otherwise, this isn't something we can handle, reject it.
10487       return;
10488     }
10489
10490     const GlobalValue *GV = GA->getGlobal();
10491     // If we require an extra load to get this address, as in PIC mode, we
10492     // can't accept it.
10493     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10494                                                         getTargetMachine())))
10495       return;
10496
10497     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
10498                                         GA->getValueType(0), Offset);
10499     break;
10500   }
10501   }
10502
10503   if (Result.getNode()) {
10504     Ops.push_back(Result);
10505     return;
10506   }
10507   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10508 }
10509
10510 std::vector<unsigned> X86TargetLowering::
10511 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10512                                   EVT VT) const {
10513   if (Constraint.size() == 1) {
10514     // FIXME: not handling fp-stack yet!
10515     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10516     default: break;  // Unknown constraint letter
10517     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10518       if (Subtarget->is64Bit()) {
10519         if (VT == MVT::i32)
10520           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10521                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10522                                        X86::R10D,X86::R11D,X86::R12D,
10523                                        X86::R13D,X86::R14D,X86::R15D,
10524                                        X86::EBP, X86::ESP, 0);
10525         else if (VT == MVT::i16)
10526           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10527                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10528                                        X86::R10W,X86::R11W,X86::R12W,
10529                                        X86::R13W,X86::R14W,X86::R15W,
10530                                        X86::BP,  X86::SP, 0);
10531         else if (VT == MVT::i8)
10532           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10533                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10534                                        X86::R10B,X86::R11B,X86::R12B,
10535                                        X86::R13B,X86::R14B,X86::R15B,
10536                                        X86::BPL, X86::SPL, 0);
10537
10538         else if (VT == MVT::i64)
10539           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10540                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10541                                        X86::R10, X86::R11, X86::R12,
10542                                        X86::R13, X86::R14, X86::R15,
10543                                        X86::RBP, X86::RSP, 0);
10544
10545         break;
10546       }
10547       // 32-bit fallthrough
10548     case 'Q':   // Q_REGS
10549       if (VT == MVT::i32)
10550         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10551       else if (VT == MVT::i16)
10552         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10553       else if (VT == MVT::i8)
10554         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10555       else if (VT == MVT::i64)
10556         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10557       break;
10558     }
10559   }
10560
10561   return std::vector<unsigned>();
10562 }
10563
10564 std::pair<unsigned, const TargetRegisterClass*>
10565 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10566                                                 EVT VT) const {
10567   // First, see if this is a constraint that directly corresponds to an LLVM
10568   // register class.
10569   if (Constraint.size() == 1) {
10570     // GCC Constraint Letters
10571     switch (Constraint[0]) {
10572     default: break;
10573     case 'r':   // GENERAL_REGS
10574     case 'l':   // INDEX_REGS
10575       if (VT == MVT::i8)
10576         return std::make_pair(0U, X86::GR8RegisterClass);
10577       if (VT == MVT::i16)
10578         return std::make_pair(0U, X86::GR16RegisterClass);
10579       if (VT == MVT::i32 || !Subtarget->is64Bit())
10580         return std::make_pair(0U, X86::GR32RegisterClass);
10581       return std::make_pair(0U, X86::GR64RegisterClass);
10582     case 'R':   // LEGACY_REGS
10583       if (VT == MVT::i8)
10584         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10585       if (VT == MVT::i16)
10586         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10587       if (VT == MVT::i32 || !Subtarget->is64Bit())
10588         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10589       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10590     case 'f':  // FP Stack registers.
10591       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10592       // value to the correct fpstack register class.
10593       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10594         return std::make_pair(0U, X86::RFP32RegisterClass);
10595       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10596         return std::make_pair(0U, X86::RFP64RegisterClass);
10597       return std::make_pair(0U, X86::RFP80RegisterClass);
10598     case 'y':   // MMX_REGS if MMX allowed.
10599       if (!Subtarget->hasMMX()) break;
10600       return std::make_pair(0U, X86::VR64RegisterClass);
10601     case 'Y':   // SSE_REGS if SSE2 allowed
10602       if (!Subtarget->hasSSE2()) break;
10603       // FALL THROUGH.
10604     case 'x':   // SSE_REGS if SSE1 allowed
10605       if (!Subtarget->hasSSE1()) break;
10606
10607       switch (VT.getSimpleVT().SimpleTy) {
10608       default: break;
10609       // Scalar SSE types.
10610       case MVT::f32:
10611       case MVT::i32:
10612         return std::make_pair(0U, X86::FR32RegisterClass);
10613       case MVT::f64:
10614       case MVT::i64:
10615         return std::make_pair(0U, X86::FR64RegisterClass);
10616       // Vector types.
10617       case MVT::v16i8:
10618       case MVT::v8i16:
10619       case MVT::v4i32:
10620       case MVT::v2i64:
10621       case MVT::v4f32:
10622       case MVT::v2f64:
10623         return std::make_pair(0U, X86::VR128RegisterClass);
10624       }
10625       break;
10626     }
10627   }
10628
10629   // Use the default implementation in TargetLowering to convert the register
10630   // constraint into a member of a register class.
10631   std::pair<unsigned, const TargetRegisterClass*> Res;
10632   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10633
10634   // Not found as a standard register?
10635   if (Res.second == 0) {
10636     // Map st(0) -> st(7) -> ST0
10637     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10638         tolower(Constraint[1]) == 's' &&
10639         tolower(Constraint[2]) == 't' &&
10640         Constraint[3] == '(' &&
10641         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10642         Constraint[5] == ')' &&
10643         Constraint[6] == '}') {
10644
10645       Res.first = X86::ST0+Constraint[4]-'0';
10646       Res.second = X86::RFP80RegisterClass;
10647       return Res;
10648     }
10649
10650     // GCC allows "st(0)" to be called just plain "st".
10651     if (StringRef("{st}").equals_lower(Constraint)) {
10652       Res.first = X86::ST0;
10653       Res.second = X86::RFP80RegisterClass;
10654       return Res;
10655     }
10656
10657     // flags -> EFLAGS
10658     if (StringRef("{flags}").equals_lower(Constraint)) {
10659       Res.first = X86::EFLAGS;
10660       Res.second = X86::CCRRegisterClass;
10661       return Res;
10662     }
10663
10664     // 'A' means EAX + EDX.
10665     if (Constraint == "A") {
10666       Res.first = X86::EAX;
10667       Res.second = X86::GR32_ADRegisterClass;
10668       return Res;
10669     }
10670     return Res;
10671   }
10672
10673   // Otherwise, check to see if this is a register class of the wrong value
10674   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10675   // turn into {ax},{dx}.
10676   if (Res.second->hasType(VT))
10677     return Res;   // Correct type already, nothing to do.
10678
10679   // All of the single-register GCC register classes map their values onto
10680   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10681   // really want an 8-bit or 32-bit register, map to the appropriate register
10682   // class and return the appropriate register.
10683   if (Res.second == X86::GR16RegisterClass) {
10684     if (VT == MVT::i8) {
10685       unsigned DestReg = 0;
10686       switch (Res.first) {
10687       default: break;
10688       case X86::AX: DestReg = X86::AL; break;
10689       case X86::DX: DestReg = X86::DL; break;
10690       case X86::CX: DestReg = X86::CL; break;
10691       case X86::BX: DestReg = X86::BL; break;
10692       }
10693       if (DestReg) {
10694         Res.first = DestReg;
10695         Res.second = X86::GR8RegisterClass;
10696       }
10697     } else if (VT == MVT::i32) {
10698       unsigned DestReg = 0;
10699       switch (Res.first) {
10700       default: break;
10701       case X86::AX: DestReg = X86::EAX; break;
10702       case X86::DX: DestReg = X86::EDX; break;
10703       case X86::CX: DestReg = X86::ECX; break;
10704       case X86::BX: DestReg = X86::EBX; break;
10705       case X86::SI: DestReg = X86::ESI; break;
10706       case X86::DI: DestReg = X86::EDI; break;
10707       case X86::BP: DestReg = X86::EBP; break;
10708       case X86::SP: DestReg = X86::ESP; break;
10709       }
10710       if (DestReg) {
10711         Res.first = DestReg;
10712         Res.second = X86::GR32RegisterClass;
10713       }
10714     } else if (VT == MVT::i64) {
10715       unsigned DestReg = 0;
10716       switch (Res.first) {
10717       default: break;
10718       case X86::AX: DestReg = X86::RAX; break;
10719       case X86::DX: DestReg = X86::RDX; break;
10720       case X86::CX: DestReg = X86::RCX; break;
10721       case X86::BX: DestReg = X86::RBX; break;
10722       case X86::SI: DestReg = X86::RSI; break;
10723       case X86::DI: DestReg = X86::RDI; break;
10724       case X86::BP: DestReg = X86::RBP; break;
10725       case X86::SP: DestReg = X86::RSP; break;
10726       }
10727       if (DestReg) {
10728         Res.first = DestReg;
10729         Res.second = X86::GR64RegisterClass;
10730       }
10731     }
10732   } else if (Res.second == X86::FR32RegisterClass ||
10733              Res.second == X86::FR64RegisterClass ||
10734              Res.second == X86::VR128RegisterClass) {
10735     // Handle references to XMM physical registers that got mapped into the
10736     // wrong class.  This can happen with constraints like {xmm0} where the
10737     // target independent register mapper will just pick the first match it can
10738     // find, ignoring the required type.
10739     if (VT == MVT::f32)
10740       Res.second = X86::FR32RegisterClass;
10741     else if (VT == MVT::f64)
10742       Res.second = X86::FR64RegisterClass;
10743     else if (X86::VR128RegisterClass->hasType(VT))
10744       Res.second = X86::VR128RegisterClass;
10745   }
10746
10747   return Res;
10748 }